looking for some solutions? You are welcome.

SOLVED: PInvoke WindowsAPI CreateFile from C#

DrLechter:

When PInvoking the WindowsAPI CreateFile from a c# program is it best to call the generic CreateFile, ANSI CreateFileA, or the Unicode CreateFileW version?

Each of the API's has a different signature for the relevant CharSet:

// CreateFile generic
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern SafeFileHandle CreateFile (
    [MarshalAs(UnmanagedType.LPTStr)] string lpFileName,
    ...

 // CreateFileA ANSI 
 [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
 public static extern SafeFileHandle CreateFileA (
    [MarshalAs(UnmanagedType.LPStr)] string lpFileName,
    ...

// CreateFileW Unicode
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern SafeFileHandle CreateFileW (
    [MarshalAs(UnmanagedType.LPWStr)] string lpFileName,
    ...

According to Microsoft documentation1, for C# the default CharSet is Charset.ANSI. That seems really strange since strings in C# are Unicode. If the documentation is right, it means that CreateFile will ultimately call CreateFileA at runtime (with appropriate conversions to ANSI to and fro along the way).

Another Micrsoft doc2 says, "When the CharSet is Unicode or the argument is explicitly marked as [MarshalAs(UnmanagedType.LPWSTR)] and the string is passed by value (not ref or out), the string will be pinned and used directly by native code (rather than copied)." This seems great for avoiding copying potentially large strings and providing max performance.

Assume that I want to call the CreateFile flavor that works optimally with C# strings, has best performance, minimal casting / translations, works on Windows x64 OS and secondarily has maximum portability.

Approach 1: Call generic CreateFile but change signature to CharSet.Unicode.
This may be a problem because CreateFile marshals the lpFileName as UnmanagedType.LPTStr whereas CreateFileW marshalls it as UnmanagedType.LPWStr. It seems like the marshaling would have to perform conversions? to get the right LP type (more than once). Another inefficiency is that CreateFile would have to call CreateFileW internally. Also, I want to make sure the "pinning" is happening for max performance and I'm not sure that would happen here.

Approach 2: Call generic CreateFile with signature CharSet.Auto This seems to provide maximum portability for target OS but will wind up calling CreateFileA internally which is inappropriate for C# strings (Unicode).

Approach 3: Call CreateFileW directly. This also seems less than optimal because if I am compiling for a different target OS like Win x86 (that uses only ANSI strings) than the program will not be able to run at all.

It seems like Approach 1 would be best but the MarshalAs LPTStr doesn't look right to me (considering that the CreateFileW version marshals as LPWStr).

I would appreciate any help you can give on this. I have been digging through dozens of conflicting webpages and can not find a definitive answer.

References:

1 DllImportAttribute.CharSet Field

2 Native interoperability best practices

3 Copying and Pinning



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

SOLVED: cannot create INSTEAD OF triggers on table, trying to do a manual cascade delete

Jenny Lawrence:

I am trying to have my information stored from a whole database every time a repair job is deleted which means it's child car_problems also needs to be deleted but for some reason it won't let me do instead of delete on repair_job. Basically my main task for this trigger is to log everything that is deleted from repair_job. Here is my code:

 CREATE TABLE repair_job(repairId varchar(5) PRIMARY KEY, licenceNo 
                        varchar(7), 
                        contact varchar(25),time_in timestamp,
                        time_out timestamp, employeeId varchar(5), 
                        laborHrs number,
                         FOREIGN KEY(licenceNo) REFERENCES 
                         car(licenceNo),
                         FOREIGN KEY(contact) REFERENCES 
                         Customer(contact),
                         FOREIGN KEY(employeeId) REFERENCES 
                         mechanic(employeeId));

    CREATE TABLE car_problems(probId varchar(7), repairId varchar(5), 
                partName varchar(25), partPrice number,
                FOREIGN KEY(probId) REFERENCES problem(probId), 
                FOREIGN KEY(repairId) REFERENCES 
                repair_job(repairId));
    CREATE TABLE repairLog(repairId varchar(5), licenceNo varchar(7), 
                        model varchar(25), name varchar(25), 
                        address varchar(30), contact varchar(25),
                        probId varchar(7), probType varchar(30),
                        employeeId varchar(5), mechName varchar(25),
                        mechPhone varchar(10), hrlyRate number,
                        partName varchar(25), partPrice number,
                        time_in timestamp, time_out timestamp, 
                        laborHrs number);

    CREATE OR REPLACE TRIGGER logRepair
    INSTEAD OF DELETE
        ON repair_job
        FOR EACH ROW
        DECLARE



    mod varchar(25);
    addr varchar(30);
    custName varchar(25);
    mechName varchar(25);
    mechPhone varchar(10);
    hrlyRate number;
    partName varchar(25);
    partPrice number;
    probId varchar(7);
    probType varchar(30);

    CURSOR parts is
        SELECT car_problems.partName , car_problems.partPrice,
                car_problems.probId , problem.probType 
                FROM car_problems, problem
                WHERE car_problems.repairId = :old.repairId 
                AND car_problems.probId = problem.probId;


    BEGIN 

        select model into mod from car where contact = :old.contact;
        select name, address into custName, addr from Customer 
            where contact = :old.contact;
        select mechName, mechPhone, hrlyRate into mechName, mechPhone, 
              hrlyRate 
            from mechanic where employeeId = :old.employeeId;

        OPEN parts;
        LOOP
        FETCH parts into partName, partPrice, probId, probType;
            EXIT WHEN parts%notfound;
            INSERT INTO repairLog(repairId,licenceNo,
                            model, name, address,contact,
                            probId,probType, employeeId,
                            mechName,mechPhone,hrlyRate,
                            partName,partPrice, time_in, 
                            time_out, laborHrs) 

              VALUES(:old.repairId,:old.licenceNo,mod,custName,addr,
                                :old.contact,probId,
                            probType, :old.employeeId,
                            mechName, mechPhone, hrlyRate,


     partName,partPrice,:old.time_in,:old.time_out,:old.laborHrs);
        END LOOP;
        CLOSE parts;
    DELETE FROM car_problems where repairId=:old.repairId;
    DELETE FROM repair_job where repairId=:old.repairId;


    END;
    /
    SHOW ERRORS;



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

SOLVED: How to program a UserForm to Update A Monthly Tracker

J Carlos:

I was looking for some help or a walk-through on how to program a userform to update a tracker, based on the Month, Day, Shift, Area. I currently have each month broke up in different tabs. I created the userform already and have tried a few different things that I found online, but can't seem to get it to work.

I attached the excel work-book, but if anyone can explain it to me that would be greatly appreciated.

What the Spreadsheet looks like

What the Spreadsheet looks like

UserForm I created

UserForm I created

Code for the ComboBox

Code for the ComboBox



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

SOLVED: How to create a child process using multiprocessing in Python2.7.10 without the child sharing resources with parent?

Jigar Bhalodia:

We are trying to move our python 2.7.10 codebase from Windows to Linux. We recently discovered that multiprocessing library in Python 2.7 behaves differently on Windows vs Linux. We have found many articles like this one describing the problem however, we are unable to find a solution online for Python 2.7. This is a fix for this issue in Python 3.4 however, we are unable to upgrade to Python 3.4. Is there any way to use multiprocessing in Python 2.7 on Linux without the child and parent sharing memory? We can also use guidance on modifying forking.py code in python 2.7 to ensure child and parent process aren't sharing memory and doing Copy-on-Write. Thanks!



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

SOLVED: Changing an image in Django inlineformset_factory puts it to the end of the list

MarcoBianchi:

Supposing I am making a "How to" Django webapp where users make posts about how to- do different things like.

  • "How to" make a rope
  • "How to" make an earthen pot
  • "How to" learn to ride a bike

You get the idea. I have made the post create view for this.Now when members make the post.They add additional images to the post

Example: "How to" make a rope

  • This has Post Title = How to make a rope
  • Post description = "Some description"
  • Post Image = Main Image

Now they have to show images step by step how the rope is made

  • Image 1: Do this 1st
  • Image 2: Do this 2nd

I am using Django formsets along with my post model to achieve this. Everything is working absolutely fine in create view. no problems. But in update view things break.

The Problem

The problem is when a user wants to EDIT their post and switch image number 2. from their post to a different image. Even though they changed the 2nd image. That image now ends up at the very end of the list. Making the user to re-upload all the images. To bring back the Order. Making my app look buggy.

Example: Lets assume user has the below post

main post Title 
" Some description "
Main Image = Post_image.jpg  

1st Image = A.jpg
   Image Title
   Image description
2nd Image = B.jpg
   Image Title
   Image description
3rd Image = C.jpg
   Image Title
   Image description
4st Image = D.jpg
    Image Title
     Image description
5th Image = E.jpg
     Image Title
     Image description
6th Image = F.img
     Image Title
     Image description

Now if I changed 2nd image B.jpg to b.jpg b.jpg moves to the very end of the list and you have the order as A, C, D, E, F, b

Below are my models:

 class Post(models.Model):
    user = models.ForeignKey(User, related_name='posts')
    created_at = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(allow_unicode=True, unique=True,max_length=500)
    post_image = models.ImageField()
    message = models.TextField()

class Prep (models.Model): #(Images)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_prep')
    image = models.ImageField(upload_to='images/', blank=True, null=True, default='')
    image_title = models.CharField(max_length=100, default='')
    image_description = models.CharField(max_length=250, default='')

My post Edit View:

class PostPrepUpdate(LoginRequiredMixin, UpdateView):
    model = Post
    fields = ('title', 'message', 'post_image')
    template_name = 'posts/post_edit.html'
    success_url = reverse_lazy('home')

    def get_context_data(self, **kwargs):
        data = super(PostPrepUpdate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['prep'] = PrepFormSet(self.request.POST, self.request.FILES, instance=self.object)
        else:
            data['prep'] = PrepFormSet(instance=self.object)
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        prep = context['prep']
        with transaction.atomic():
            self.object = form.save()

            if prep.is_valid():
                prep.instance = self.object
                prep.save()
        return super(PostPrepUpdate, self).form_valid(form)

My post create view

def post_create(request):
    ImageFormSet = modelformset_factory(Prep, fields=('image', 'image_title', 'image_description'), extra=12, max_num=12,
                                        min_num=2)
    if request.method == "POST":
        form = PostForm(request.POST or None, request.FILES or None)
        formset = ImageFormSet(request.POST or None, request.FILES or None)
        if form.is_valid() and formset.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
            post_user = request.user
            for f in formset.cleaned_data:
                try:
                    photo = Prep(post=instance, image=f['image'], image_title=f['image_title'], image_description=f['image_description'])
                    photo.save()
                except Exception as e:
                    break

            return redirect('posts:single', username=instance.user.username, slug=instance.slug)
    else:
        form = PostForm()
        formset = ImageFormSet(queryset=Prep.objects.none())
    context = {
        'form': form,
        'formset': formset,
    }
    return render(request, 'posts/post_form.html', context)

My Forms.py

class PostEditForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'message', 'post_image' )


class PrepForm(forms.ModelForm):
    class Meta:
        model = Prep
        fields = ('image', 'image_title', 'image_description')


PrepFormSet = inlineformset_factory(Post, Prep, form=PrepForm, extra=5, max_num=7, min_num=2)

***Need help fixing this issue. Example if they change Image 2. Then it should stay at Number 2 position and not move to the end of the list



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

SOLVED: Click() is not working though there's no any error but its not opening up - (Cypress automation)

Bandana Singh:

last one cy.get('[data-cy=impact-area-table]').contains(impactareas.name).should('be.visible').click({force: true}); is not working though there's no any error ,it shows that it's fine and test pass but it doesnot open up the impact area ??

import { fillImpactAreaForm } from './utils';
import {contact, campaign, impactArea,impactareas} from '../support/commands.js';

describe('Fundraising test suite', function () {

    beforeEach(() => {
        cy.resetDb();
        cy.visit('/');
    });
it('should allow the user to create transactions', () => {
    cy.seedOrgAndLogin().then(() => {
        return cy.factoryCreate('PersonContacts', contact);

    }).then(() => {
        cy.factoryCreate('Campaigns', campaign);

    }).then(() => {
        cy.factoryCreate('ImpactAreas', impactArea);

    }).then(() => {
        cy.get('[data-cy="sidebar-Impact Areas"]').click({force: true});

        cy.reload(true);

        cy.get('[data-cy=create-impactarea]').click();

        cy.get('[data-cy=impact-area-form]').contains('Close').click();

        cy.get('[data-cy=create-impactarea]').click();

        fillImpactAreaForm(impactareas);
        cy. wait(2000);

        cy.get('[data-cy=impact-area-table]').contains(impactareas.name).should('be.visible').click({force: true});
       //cy.get('.content-scroll-wrapper.block-content').find('.content-scroll-body').contains(impactArea.name).click({force: true});

    });
});

});



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

SOLVED: How do i pass result of callback into variable and access the var freely

flix:

I know there's a ton of question similar to my question, but i didn't see any good case to help me,

I have a callback from native function bridge and this how i used it on JS:

getAllParameter((data)=>{
  console.log(data) // data is Javascript Object
})

I've tried this to get the value of data:

getAllParameter((data)=>{
  return new Promise((resolve)=> resolve(showToken(data.Token)))
})

async function showToken(token){
  var res = await token
  return res
}

var isiToken = showToken()
console.log("isiToken")
console.log(isiToken)

but the result is:

isiToken
{ _40: 0, _65: 0, _55: null, _72: null }

i don't know whats wrong with my code, i want to get the value of data outside of the getAllParameter, how can i do that properly?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

Recent