问:
Overcoming lazy loading issues in Hibernate, many-to-many, relationship
Teaching myself Hibernate, I have the following table structure/relationship

Which is represented by the following classes...

Users

```<code>@Entity
@Table(name = "users")
public class User implements IUser<Role>, Serializable {

    @Id
    @GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
    @SequenceGenerator(name = "user_key_seq")
    @Column(name = "key", insertable = false, updatable = false)
    private Long key;

    @Column(name = "name")
    private String name;

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name = "userroles",
                    joinColumns = {
                        @JoinColumn(name = "userkey")},
                    inverseJoinColumns = {
                        @JoinColumn(name = "rolekey")})
    private Set<Role> roles = new HashSet<>(5);

    @Override
    public Set<Role> getRoles() {
        return roles;
    }

    // Other setters and getters

}
</code>```

Roles

```<code>@Entity
@Table(name = "roles")
public class Role implements IRole, Serializable {

    @Id
    @GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
    @SequenceGenerator(name = "roles_key_seq")
    @Column(name = "key", insertable = false, updatable = false)
    private Long key;

    @Column(name="name")
    private String name;

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name="parentroles",
                    joinColumns = {@JoinColumn(name="childkey")},
                    inverseJoinColumns = {@JoinColumn(name="parentkey")})
    private Set<Role> roles = new HashSet<>(5);

    // Other setters and getters

}
</code>```

The problem I'm getting is this...

```<code>org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.kaizen.chishiki.core.data.User.roles, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142)
    at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:180)
    at og.kaizen.chishiki.core.testdatacore.Main.<init>(Main.java:37)
    at og.kaizen.chishiki.core.testdatacore.Main.main(Main.java:25)
</code>```

Now, I know I could set the fetch type to FetchType.EAGER, but I'd prefer not to do that, apart from performance concerns, I'm trying to learn my way around these problems ;)

I was wondering if there was a way to write a Hibernate query to satisfy this relationship and load the rows manually (it would also allow me to return the interface of Role instead of the implementation as I'm having to do now (would allow me to maintain that contract)).

From what I've read, it would seem that I would need to construct an Entity for UserRoles.  Not that I'm against this solution, but I was curious if there was a way to get around it.

roles appears in a number of other relationships, so there is no way it can form a direct relationship with the parent table (that is, I can't put the key of the parent table in the role table directly, besides, users can have multiple roles)

The other solution I had in mind was to write a stored procedure to do it for me.  While this is viable solution that I'm not above doing, it does make migrating the application to another database more difficult, not a show stopper, but I'm trying to keep these ideas in mind.

答: I solved this problem by annotating the method in the controller as transactional.As lazy-load basically returns a list of future objects ,the method needs to be transactional.</p>

Body:
Teaching myself Hibernate, I have the following table structure/relationship

Which is represented by the following classes...

Users

@Entity
@Table(name = "users")
public class User implements IUser<Role>, Serializable {

    @Id
    @GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
    @SequenceGenerator(name = "user_key_seq")
    @Column(name = "key", insertable = false, updatable = false)
    private Long key;

    @Column(name = "name")
    private String name;

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name = "userroles",
                    joinColumns = {
                        @JoinColumn(name = "userkey")},
                    inverseJoinColumns = {
                        @JoinColumn(name = "rolekey")})
    private Set<Role> roles = new HashSet<>(5);

    @Override
    public Set<Role> getRoles() {
        return roles;
    }

    // Other setters and getters

}

Roles

@Entity
@Table(name = "roles")
public class Role implements IRole, Serializable {

    @Id
    @GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
    @SequenceGenerator(name = "roles_key_seq")
    @Column(name = "key", insertable = false, updatable = false)
    private Long key;

    @Column(name="name")
    private String name;

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name="parentroles",
                    joinColumns = {@JoinColumn(name="childkey")},
                    inverseJoinColumns = {@JoinColumn(name="parentkey")})
    private Set<Role> roles = new HashSet<>(5);

    // Other setters and getters

}

The problem I'm getting is this...

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: org.kaizen.chishiki.core.data.User.roles, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142)
    at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:180)
    at og.kaizen.chishiki.core.testdatacore.Main.<init>(Main.java:37)
    at og.kaizen.chishiki.core.testdatacore.Main.main(Main.java:25)

Now, I know I could set the fetch type to FetchType.EAGER, but I'd prefer not to do that, apart from performance concerns, I'm trying to learn my way around these problems ;)

I was wondering if there was a way to write a Hibernate query to satisfy this relationship and load the rows manually (it would also allow me to return the interface of Role instead of the implementation as I'm having to do now (would allow me to maintain that contract)).

From what I've read, it would seem that I would need to construct an Entity for UserRoles.  Not that I'm against this solution, but I was curious if there was a way to get around it.

roles appears in a number of other relationships, so there is no way it can form a direct relationship with the parent table (that is, I can't put the key of the parent table in the role table directly, besides, users can have multiple roles)

The other solution I had in mind was to write a stored procedure to do it for me.  While this is viable solution that I'm not above doing, it does make migrating the application to another database more difficult, not a show stopper, but I'm trying to keep these ideas in mind.


来源: stackexchange

问:
Select tab programmatically custom tab bar ios
I have used the following tutorial to implement custom tabs in ios
Its working fine when i tap on any of the item. Now I want to move it Programatically. e.g. I received the notification form Firebase and want to open third tab. But I am getting nil. I have referenced the MainTabbarController instance in appdelegate.
Here is what i have tried
In CustomTabBar

```<code>func customTapped(index :Int){
        animateTabBarSelection(from: selectedTabBarItemIndex, to: index)
        selectedTabBarItemIndex = index
        delegate.didSelectViewController(self, atIndex: index)
}
</code>```

In AppDelegate

```<code>mainTabBarController?.customTabBar?.customTapped( index: 2)
</code>```

答:
From the link that you have provided along with the question, the following are the statements that I found to be responsible for switching the tabs

```<code>func barItemTapped(sender : UIButton) {
    let index = tabBarButtons.indexOf(sender)!

    animateTabBarSelection(from: selectedTabBarItemIndex, to: index)
    selectedTabBarItemIndex = index
    delegate.didSelectViewController(self, atIndex: index)
}
</code>```

You can just modify this code as

```<code>func barItemTapped(sender : UIButton) {
    let index = tabBarButtons.indexOf(sender)!
    tabSelectedAt(index)

}

func tabSelectedAt(_ index:Int) {
 if selectedTabBarItemIndex != nil {
   animateTabBarSelection(from: selectedTabBarItemIndex, to: index)
  }
    selectedTabBarItemIndex = index
    delegate.didSelectViewController(self, atIndex: index)
}
</code>```

So call the function func tabSelectedAt(_ index:Int) with the index of the tab which you wants to switch.

ContentLicense: CC BY-SA 3.0

Body:
I have used the following tutorial to implement custom tabs in ios
Its working fine when i tap on any of the item. Now I want to move it Programatically. e.g. I received the notification form Firebase and want to open third tab. But I am getting nil. I have referenced the MainTabbarController instance in appdelegate.
Here is what i have tried
In CustomTabBar

func customTapped(index :Int){
        animateTabBarSelection(from: selectedTabBarItemIndex, to: index)
        selectedTabBarItemIndex = index
        delegate.didSelectViewController(self, atIndex: index)
}

In AppDelegate

mainTabBarController?.customTabBar?.customTapped( index: 2)

Body:
From the link that you have provided along with the question, the following are the statements that I found to be responsible for switching the tabs

func barItemTapped(sender : UIButton) {
    let index = tabBarButtons.indexOf(sender)!

    animateTabBarSelection(from: selectedTabBarItemIndex, to: index)
    selectedTabBarItemIndex = index
    delegate.didSelectViewController(self, atIndex: index)
}

You can just modify this code as

func barItemTapped(sender : UIButton) {
    let index = tabBarButtons.indexOf(sender)!
    tabSelectedAt(index)

}

func tabSelectedAt(_ index:Int) {
 if selectedTabBarItemIndex != nil {
   animateTabBarSelection(from: selectedTabBarItemIndex, to: index)
  }
    selectedTabBarItemIndex = index
    delegate.didSelectViewController(self, atIndex: index)
}

So call the function func tabSelectedAt(_ index:Int) with the index of the tab which you wants to switch.


问:
VBS Invalid Query in Windows 10
Why does the following VBS code work in Windows 7 but gives error on Windows 10:

```<code>strComputer="."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'notepad.exe'")
Wscript.Echo colProcesses.Count
</code>```

The error I'm getting in Windows 10 is:

test_2.vbs(4,1) SWbemObjectSet: Invalid query

What am I doing wrong here?

答:
Try and use the below code. This should work</p>

```<code>strQuery = "select * from win32_process where Name = " & """" & "Notepad.exe" & """"
strComputer="."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery(strQuery)
Wscript.Echo colProcesses.Count
</code>```

Title: VBS Invalid Query in Windows 10

Body:
Why does the following VBS code work in Windows 7 but gives error on Windows 10:

strComputer="."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'notepad.exe'")
Wscript.Echo colProcesses.Count

The error I'm getting in Windows 10 is:

test_2.vbs(4,1) SWbemObjectSet: Invalid query

What am I doing wrong here?

Body:
Try and use the below code. This should work

strQuery = "select * from win32_process where Name = " & """" & "Notepad.exe" & """"
strComputer="."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcesses = objWMIService.ExecQuery(strQuery)
Wscript.Echo colProcesses.Count


问:
using UIImage drawInRect still renders it upside down
I have read some posts on this website about using drawInRect instead of the CGContext draw methods. It still draws it upside down? I thought using drawInRect would print it right side up with the coordinate system originating at the top left?

```<code>-(void) drawImage:(UIImage*) image atX:(float) x andY:(float) y withWidth:(float) width andHeight:(float) height onContext:(CGContextRef) context{
UIGraphicsPushContext(context);
[image drawInRect:CGRectMake(x, size.height-y-height, width, height)];
UIGraphicsPopContext();
}
</code>```

Notice I'm doing size.height-y-height and if I don't do that it doesn't go where I expect (assuming drawInRect using a topleft coordinate system). It renders in the correct spot with the above code but still upside down. HELP!!!!!!

UPDATE

Thanks to the answer below this is the working method

```<code>-(void) drawImage:(UIImage*) image atX:(float) x andY:(float) y withWidth:(float) width andHeight:(float) height onContext:(CGContextRef) context{
UIGraphicsPushContext(context);
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
[image drawInRect:CGRectMake(x, y, width, height)];
CGContextRestoreGState(context);
UIGraphicsPopContext();
}
</code>```

答:
```<code>    UIGraphicsBeginImageContext(imageViewSize);
CGContextRef imageContext = UIGraphicsGetCurrentContext();

// Draw the image in the upper left corner (0,0) with its actual size
CGContextDrawImage(imageContext, imageViewRect, oldImage.CGImage);

//  As it draws the image from lower right corner,
//  following code will flip it up side down vertically.

CGContextTranslateCTM(imageContext, 0.0, 0.0);
CGContextScaleCTM(imageContext, 1.0, -1.0);

CGContextDrawImage(imageContext, imageViewRect, oldImage.CGImage);
</code>```

Body:
I have read some posts on this website about using drawInRect instead of the CGContext draw methods. It still draws it upside down? I thought using drawInRect would print it right side up with the coordinate system originating at the top left?

-(void) drawImage:(UIImage*) image atX:(float) x andY:(float) y withWidth:(float) width andHeight:(float) height onContext:(CGContextRef) context{
UIGraphicsPushContext(context);
[image drawInRect:CGRectMake(x, size.height-y-height, width, height)];
UIGraphicsPopContext();
}

Notice I'm doing size.height-y-height and if I don't do that it doesn't go where I expect (assuming drawInRect using a topleft coordinate system). It renders in the correct spot with the above code but still upside down. HELP!!!!!!

UPDATE

Thanks to the answer below this is the working method

-(void) drawImage:(UIImage*) image atX:(float) x andY:(float) y withWidth:(float) width andHeight:(float) height onContext:(CGContextRef) context{
UIGraphicsPushContext(context);
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
[image drawInRect:CGRectMake(x, y, width, height)];
CGContextRestoreGState(context);
UIGraphicsPopContext();
}

ContentLicense: CC BY-SA 2.5


问:
Atomic bit-wise operations on POD type
Given the following:

```<code>#include<atomic>

struct Foo
{
    uint64_t data[1];
};

std::atomic<Foo> bar;

void DoAtomicOr(uint64_t value)
{
    std::atomic_fetch_or(&bar, value);
}
</code>```

My compiler is complaining that the type of the first parameter cannot be passed into the fetch because its type doesn't match any known overloads.  I can typecast it to:

```<code>std::atomic_fetch_or((std::atomic<uint64_t> *)&bar, value);
</code>```

But this is error prone as I already proved to myself early today.  Is there a better way to get the compiler to realize that he Pod type Foo here is actually just a glorified uint64_t?

答:
Foo is not an integral type and therefore you cannot use fetch_or().

One solution is to use data[1] (instead of Foo) as an atomic type:

```<code>struct Foo
{
    std::atomic<uint64_t> data[1];
};

Foo bar;

void DoAtomicOr(uint64_t value)
{
    std::atomic_fetch_or(&bar.data[0], value);
}
</code>```

In case you want to keep Foo atomic, you can use a compare-and-swap with an OR operation:

```<code>struct Foo
{
    uint64_t data[1];
};

std::atomic<Foo> bar;

void DoAtomicOr(uint64_t value)
{
    Foo expected = bar.load();
    Foo desired;

    do {
        desired = expected;

        desired.data[0] |= value;

    } while (!std::atomic_compare_exchange_weak(&bar, &expected, desired));
}
</code>```

Title: Atomic bit-wise operations on POD type

Body:
Given the following:

#include<atomic>

struct Foo
{
    uint64_t data[1];
};

std::atomic<Foo> bar;

void DoAtomicOr(uint64_t value)
{
    std::atomic_fetch_or(&bar, value);
}

My compiler is complaining that the type of the first parameter cannot be passed into the fetch because its type doesn't match any known overloads.  I can typecast it to:

std::atomic_fetch_or((std::atomic<uint64_t> *)&bar, value);

But this is error prone as I already proved to myself early today.  Is there a better way to get the compiler to realize that he Pod type Foo here is actually just a glorified uint64_t?

Body:
Foo is not an integral type and therefore you cannot use fetch_or().

One solution is to use data[1] (instead of Foo) as an atomic type:

struct Foo
{
    std::atomic<uint64_t> data[1];
};

Foo bar;

void DoAtomicOr(uint64_t value)
{
    std::atomic_fetch_or(&bar.data[0], value);
}

In case you want to keep Foo atomic, you can use a compare-and-swap with an OR operation:

struct Foo
{
    uint64_t data[1];
};

std::atomic<Foo> bar;

void DoAtomicOr(uint64_t value)
{
    Foo expected = bar.load();
    Foo desired;

    do {
        desired = expected;

        desired.data[0] |= value;

    } while (!std::atomic_compare_exchange_weak(&bar, &expected, desired));
}


问:
operators precedence in C
have a trouble understanding this expression:

```<code>(x + y - 1) / y * y
</code>```

The operators precedence is as follows (as per my understanding and K&R2, 2.12 table 2.1):

1) evaluate what is in the parens: firstly (x+y), then (x+y) -1

2) '*' operator has higher priority then '/' so it's supposed to go first, bit it appears  that (y * y)  is evaluated and then the result of (x+y-1) is divided by the product (y*y). I don't quite get it.

3) I ever heard that normally rounding up iw written in this form:

```<code>(x + y - 1) / y * y
</code>```

Is that correct? Thank you very much in advance!

答:
Unary operator * has higher precedence than /, but that is for pointer dereferencing.

Multiplication * and division / have the same left-to-right precedence.

Title: operators precedence in C

Body:
have a trouble understanding this expression:

(x + y - 1) / y * y

The operators precedence is as follows (as per my understanding and K&R2, 2.12 table 2.1):

1) evaluate what is in the parens: firstly (x+y), then (x+y) -1

2) '*' operator has higher priority then '/' so it's supposed to go first, bit it appears  that (y * y)  is evaluated and then the result of (x+y-1) is divided by the product (y*y). I don't quite get it.

3) I ever heard that normally rounding up iw written in this form:

(x + y - 1) / y * y

Is that correct? Thank you very much in advance!


问:
Unable to get return value from javascript function call
I am developing a simple angular2/ expressJS application. I have an http get router call in expressJS as follow, which should return all users from mongoDB and this works fine:

```<code>app.get('/getusers', function(req, res) {

userModel.find({}, function(err, userlist) {
    if (err) return handleError(err);
    else {
        return userlist;
    }
});
</code>```

Now I am trying to split the get user list part into a separate function as below, so that it can be reused.

```<code>app.get('/getusers', function(req, res) {
    var tmpUsrList = getAllUsers();
    console.log(tmpUsrList); //This prints undefined
    res.send(tmpUsrList);
});

function getAllUsers() {
    userModel.find({}, function(err, userlist) {
        if (err) return handleError(err);
        else {
            console.log(userlist); //This prints the correct list
            return userlist;
        }
    });
}
</code>```

However, after the return, the value is becoming undefined. I am from a java background, so I may be doing some basic mistake. Appreciate your help!!

Thanks

答:
You need to wrap it in a promise like this:</p>

```<code>app.get('/getusers', function(req, res) {
    getAllUsers()
    .then(tmpUsrList => {
        console.log(tmpUsrList);
        res.send(tmpUsrList);
    })
    .catch(err => handleError(err))
});

function getAllUsers() {
    return new Promise((resolve, reject) => {
      userModel.find({}, function(err, userlist) {
          if (err) return reject(err);
          // no need of else if you return
          console.log(userlist);
          resolve(userlist);
      });
    })
}
</code>```

Body:
I am developing a simple angular2/ expressJS application. I have an http get router call in expressJS as follow, which should return all users from mongoDB and this works fine:

app.get('/getusers', function(req, res) {

userModel.find({}, function(err, userlist) {
    if (err) return handleError(err);
    else {
        return userlist;
    }
});

Now I am trying to split the get user list part into a separate function as below, so that it can be reused.

app.get('/getusers', function(req, res) {
    var tmpUsrList = getAllUsers();
    console.log(tmpUsrList); //This prints undefined
    res.send(tmpUsrList);
});

function getAllUsers() {
    userModel.find({}, function(err, userlist) {
        if (err) return handleError(err);
        else {
            console.log(userlist); //This prints the correct list
            return userlist;
        }
    });
}

However, after the return, the value is becoming undefined. I am from a java background, so I may be doing some basic mistake. Appreciate your help!!

Thanks

Body:
You need to wrap it in a promise like this:

app.get('/getusers', function(req, res) {
    getAllUsers()
    .then(tmpUsrList => {
        console.log(tmpUsrList);
        res.send(tmpUsrList);
    })
    .catch(err => handleError(err))
});

function getAllUsers() {
    return new Promise((resolve, reject) => {
      userModel.find({}, function(err, userlist) {
          if (err) return reject(err);
          // no need of else if you return
          console.log(userlist);
          resolve(userlist);
      });
    })
}


问:
Android MediaPlayer unknown error
I am creating a MediaPlayer instance in MainActivity's onCreate() method like this

```<code> MediaPlayer mPlayer = MediaPlayer.create(this, Uri.fromFile(new File("/storage/emulated/0/soundrecorder/My recording #26.wav")));
</code>```

It is created successfully but I get this error:

```<code>07-06 18:33:44.266 18366-18366/com.audiorecorder.wel.voicerecorder E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
07-06 18:33:44.267 18366-18366/com.audiorecorder.wel.voicerecorder E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
</code>```

Also tried this but the same error on logcat:

```<code>MediaPlayer mp = new MediaPlayer();
    try {
        mp.setDataSource(this, Uri.fromFile(new File("/storage/emulated/0/soundrecorder/My recording #26.wav")));
    } catch (IOException e) {
        e.printStackTrace();
    }
    mp.prepareAsync();
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });
</code>```

I have tried different audio files with different formats but result is the same error. I have also tried searching the answer on stackoverflow but could not resolve the issue. Can you help me on this?

答:
It seems there is some issue with your file. Update that with this :

musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

And then follow these steps:

```<code>    1.  getLoaderManager().initLoader(0,null,this);
    2.  @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            switch (id){
                case 0 : return new CursorLoader(getApplicationContext(),musicUri,null,null,null,null);
            return new Loader<>(this);
        }

3. @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        switch (loader.getId()) {
            case 0 :
                if(data != null && data.moveToFirst()) {
                    songTitleColumnIndex = data.getColumnIndex(MediaStore.Audio.Media.TITLE);
                    do {
                        songTitle = data.getString(songTitleColumnIndex);
                        songsList.add(songTitle);
                    } while (data.moveToNext());
                }
                break;
</code>```

So the SongTitles are being put in the SongList which is an ArraList of String Type.

Hope This Helps.

Title: Android MediaPlayer unknown error

Body:
I am creating a MediaPlayer instance in MainActivity's onCreate() method like this

 MediaPlayer mPlayer = MediaPlayer.create(this, Uri.fromFile(new File("/storage/emulated/0/soundrecorder/My recording #26.wav")));

It is created successfully but I get this error:

07-06 18:33:44.266 18366-18366/com.audiorecorder.wel.voicerecorder E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
07-06 18:33:44.267 18366-18366/com.audiorecorder.wel.voicerecorder E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0

Also tried this but the same error on logcat:

MediaPlayer mp = new MediaPlayer();
    try {
        mp.setDataSource(this, Uri.fromFile(new File("/storage/emulated/0/soundrecorder/My recording #26.wav")));
    } catch (IOException e) {
        e.printStackTrace();
    }
    mp.prepareAsync();
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });

I have tried different audio files with different formats but result is the same error. I have also tried searching the answer on stackoverflow but could not resolve the issue. Can you help me on this?

Body:
It seems there is some issue with your file. Update that with this :

musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

And then follow these steps:

    1.  getLoaderManager().initLoader(0,null,this);
    2.  @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            switch (id){
                case 0 : return new CursorLoader(getApplicationContext(),musicUri,null,null,null,null);
            return new Loader<>(this);
        }

3. @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        switch (loader.getId()) {
            case 0 :
                if(data != null && data.moveToFirst()) {
                    songTitleColumnIndex = data.getColumnIndex(MediaStore.Audio.Media.TITLE);
                    do {
                        songTitle = data.getString(songTitleColumnIndex);
                        songsList.add(songTitle);
                    } while (data.moveToNext());
                }
                break;

So the SongTitles are being put in the SongList which is an ArraList of String Type.

Hope This Helps.


问:
How to run windows application from WebPage?
I have a webpage using PHP + apache.

And simple model like this:

How I run a app (write by C#) from my webpage?

Thank you.

答:
Solution 1:

As Per an Article Here :

```<code><script type="text/javascript" language="javascript">
    function RunFile() {
    WshShell = new ActiveXObject("WScript.Shell");
    WshShell.Run("c:/windows/system32/notepad.exe", 1, false);
    }
</script>
<a onclick='RunFile();'>NotePad</a>
</code>```

Solution 2 :

As Per Microsoft Article,
https://msdn.microsoft.com/library/aa767914(v=vs.85).aspx

You can Run a local application by Registering an Application to a URI Scheme.

Body:
Solution 1:

As Per an Article Here :

<script type="text/javascript" language="javascript">
    function RunFile() {
    WshShell = new ActiveXObject("WScript.Shell");
    WshShell.Run("c:/windows/system32/notepad.exe", 1, false);
    }
</script>
<a onclick='RunFile();'>NotePad</a>

Solution 2 :

As Per Microsoft Article,
https://msdn.microsoft.com/library/aa767914(v=vs.85).aspx

You can Run a local application by Registering an Application to a URI Scheme.


问:
python processes create same instance of class
I have a python app using the multiprocessing library and I'm running into an issue where I expect different processes to create a different instance of a class, however, they are actually creating the same instance of the class. Take this example:

```<code>from multiprocessing import Process
from time import sleep

class Foo:
    name = None

def get_foobar():
    return Foo()

class MyProcess(Process):
    def run(self):
        print('process {} running in pid {}'.format(self.name, self.pid))
        my_foo = get_foobar()
        print('got foo {}'.format(id(my_foo)))

        if my_foo.name is None:
            my_foo.name = self.name.upper()

        print("foo's name is {}".format(my_foo.name))

        # do some work
        sleep(3)

        print('process {} running in pid {} done'.format(self.name, self.pid))

for _ in range(2):
    p = MyProcess()
    p.start()
</code>```

I get the following output:

```<code>process MyProcess-1 running in pid 65975
got foo 4322815784
foo's name is MYPROCESS-1
process MyProcess-2 running in pid 65976
got foo 4322815784
foo's name is MYPROCESS-2
process MyProcess-1 running in pid 65975 done
process MyProcess-2 running in pid 65976 done
</code>```

I was expecting the second process to have a different instance of the class. How is get_foobar() able to return the same instance of Foo to each process?

EDIT / UPDATE:
I am running this in python 3.5 on OSX and Ubuntu.

答:
Basically your answer is here: Why is the id of a Python class not unique when called quickly?

The most relevant quote is:

The id of an object is only guaranteed to be unique during that object's lifetime, not over the entire lifetime of a program.

It seems that your first Foo() instance just "dies" before the second one is created, so they could end up getting the same ID.

Same things happens without multiprocessing:

```<code>>>> def run():
...     my_foo = get_foobar()
...     print('got foo {}'.format(id(my_foo))) ...
>>> run()
got foo 140690243732040
>>> run()
got foo 140690243732040
</code>```

EDIT: This is from the docs:

Return the “identity” of an object. This is an integer which is
  guaranteed to be unique and constant for this object during its
  lifetime. Two objects with non-overlapping lifetimes may have the same
  id() value.

In this context, the object's existence only within certain scopes (i.e the run function) may mean they have different lifetimes regardless. This is no different from the python 2 docs, but my guess is the implementation is different so that explains the results.

Body:
I have a python app using the multiprocessing library and I'm running into an issue where I expect different processes to create a different instance of a class, however, they are actually creating the same instance of the class. Take this example:

from multiprocessing import Process
from time import sleep

class Foo:
    name = None

def get_foobar():
    return Foo()

class MyProcess(Process):
    def run(self):
        print('process {} running in pid {}'.format(self.name, self.pid))
        my_foo = get_foobar()
        print('got foo {}'.format(id(my_foo)))

        if my_foo.name is None:
            my_foo.name = self.name.upper()

        print("foo's name is {}".format(my_foo.name))

        # do some work
        sleep(3)

        print('process {} running in pid {} done'.format(self.name, self.pid))

for _ in range(2):
    p = MyProcess()
    p.start()

I get the following output:

process MyProcess-1 running in pid 65975
got foo 4322815784
foo's name is MYPROCESS-1
process MyProcess-2 running in pid 65976
got foo 4322815784
foo's name is MYPROCESS-2
process MyProcess-1 running in pid 65975 done
process MyProcess-2 running in pid 65976 done

I was expecting the second process to have a different instance of the class. How is get_foobar() able to return the same instance of Foo to each process?

EDIT / UPDATE:
I am running this in python 3.5 on OSX and Ubuntu.

Body:
Basically your answer is here: Why is the id of a Python class not unique when called quickly?

The most relevant quote is:

The id of an object is only guaranteed to be unique during that object's lifetime, not over the entire lifetime of a program.

It seems that your first Foo() instance just "dies" before the second one is created, so they could end up getting the same ID.

Same things happens without multiprocessing:

>>> def run():
...     my_foo = get_foobar()
...     print('got foo {}'.format(id(my_foo))) ...
>>> run()
got foo 140690243732040
>>> run()
got foo 140690243732040

EDIT: This is from the docs:

Return the “identity” of an object. This is an integer which is
  guaranteed to be unique and constant for this object during its
  lifetime. Two objects with non-overlapping lifetimes may have the same
  id() value.

In this context, the object's existence only within certain scopes (i.e the run function) may mean they have different lifetimes regardless. This is no different from the python 2 docs, but my guess is the implementation is different so that explains the results.


问:
cascading combobox is not updating itemsource of dependent combobox
I have two comboboxes

```<code><ComboBox x:Name="cmbInstanceList" Margin="15,0,5,0" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding InstanceList}" SelectionChanged="cmbInstanceList_SelectionChanged"

                              Height="25"
                              Style="{StaticResource InputControlErrorsCombo}" Validation.ErrorTemplate="{StaticResource validationTemplate}"  />
<ComboBox x:Name="cmbDatabaseList" Margin="15,0,5,0" Grid.Row="2" Grid.Column="1" ItemsSource="{Binding DatabaseList}"

                              Height="25" Style="{StaticResource InputControlErrorsCombo}" Validation.ErrorTemplate="{StaticResource validationTemplate}" />
</code>```

Here, based on cmbInstanceList, I fill cmbDatabaseList through Itemsource property. InstanceList and DatabaseList are model properties of type List.

In code back-end I am using selectionchanged event to fill the second combobox.

```<code>private void cmbInstanceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbInstanceList.SelectedValue != null)
            {
                this.data.InstanceName = cmbInstanceList.SelectedValue.ToString();
                this.data.DatabaseList.Clear(); // this is not working
                FillData(this.data.InstanceName);
            }
        }
</code>```

where this.data represents the model class which contains all the properties.

FillData method contains a call to service and if data is not available the return data values will be just an empty list.

```<code>response = service.RequestDatabasesByInstance(request);
                if (response != null)
                {
                    if (response.DatabaseList != null && response.DatabaseList.Any())
                        this.data.DatabaseList = response.DatabaseList.ToList<string>();
                    else
                    {
                        this.data.DatabaseList.Clear();
                        throw new Exception("No data available");
                    }
                }
</code>```

Problem: when I select the value from cmbInstance and service returns the response with the list with values, all good and working fine.
When I select the value, where service is not able to retrieve the data and returns the empty list there is a problem. even though, I set the model property to clear the items, on UI I can still see combobox contains the values and items are not getting cleared.

答:
I have forgotten the basic concepts of MVVM.
I believe this answer may help someone like me who are trying to find the grass in the space.

The resolution to the problem is:
I have changed

this.data.DatabaseList.Clear(); // this is not working

to

this.data.DatabaseList= null;

and it started working.

Technically, when we change the value of the property, firing the PropertyChanged event (declared in the INotifyPropertyChanged interface)  notifies the Binding, which then updates the view. In my case, I was just clearing the collection object held by the property, which was not firing the PropertyChanged event.

Hope this helps someone.

Body:
I have two comboboxes

<ComboBox x:Name="cmbInstanceList" Margin="15,0,5,0" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding InstanceList}" SelectionChanged="cmbInstanceList_SelectionChanged"

                              Height="25"
                              Style="{StaticResource InputControlErrorsCombo}" Validation.ErrorTemplate="{StaticResource validationTemplate}"  />
<ComboBox x:Name="cmbDatabaseList" Margin="15,0,5,0" Grid.Row="2" Grid.Column="1" ItemsSource="{Binding DatabaseList}"

                              Height="25" Style="{StaticResource InputControlErrorsCombo}" Validation.ErrorTemplate="{StaticResource validationTemplate}" />

Here, based on cmbInstanceList, I fill cmbDatabaseList through Itemsource property. InstanceList and DatabaseList are model properties of type List.

In code back-end I am using selectionchanged event to fill the second combobox.

private void cmbInstanceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbInstanceList.SelectedValue != null)
            {
                this.data.InstanceName = cmbInstanceList.SelectedValue.ToString();
                this.data.DatabaseList.Clear(); // this is not working
                FillData(this.data.InstanceName);
            }
        }

where this.data represents the model class which contains all the properties.

FillData method contains a call to service and if data is not available the return data values will be just an empty list.

response = service.RequestDatabasesByInstance(request);
                if (response != null)
                {
                    if (response.DatabaseList != null && response.DatabaseList.Any())
                        this.data.DatabaseList = response.DatabaseList.ToList<string>();
                    else
                    {
                        this.data.DatabaseList.Clear();
                        throw new Exception("No data available");
                    }
                }

Problem: when I select the value from cmbInstance and service returns the response with the list with values, all good and working fine.
When I select the value, where service is not able to retrieve the data and returns the empty list there is a problem. even though, I set the model property to clear the items, on UI I can still see combobox contains the values and items are not getting cleared.


问:
TextView in LinearLayout pushed outside by another TextView
Good day! I am trying to achieve a specific kind of layout. I hope somebody could give me a hint on how to do it properly.

So, inside my layout, I have two TextView inside of a LinearLayout with horizontal orientation. The first TextView contains the name of the company and the second contains a number of the projects associated with it.

I wanted my layout to behave like this.

My current layout looks like this.

Here's the specific code for the layout:

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/contractor_item_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="Gem Seeker Company and  Supplies in"
        android:textColor="@color/list_title"
        android:textSize="16sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="(0)"
        android:textSize="16sp"
        android:textStyle="bold"
        android:maxLines="1"
        android:layout_marginStart="4dp"
        android:textColor="@color/space_gray_01"/>

</LinearLayout>
</code>```

Heres the complete code of the layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:background="@android:color/white"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/contractor_item_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:clickable="true"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/contractor_item_avatar"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:background="@color/space_gray_01"
            android:contentDescription="@string/image_description"
            android:src="@drawable/ic_user_light" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="16dp">

            <TextView
                android:id="@+id/contractor_item_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/contractor_item_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:maxLines="1"
                    android:text="Gem Seeker Company and  Supplies in"
                    android:textColor="@color/list_title"
                    android:textSize="16sp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="(0)"
                    android:textSize="16sp"
                    android:textStyle="bold"
                    android:maxLines="1"
                    android:layout_marginStart="4dp"
                    android:textColor="@color/space_gray_01"/>

            </LinearLayout>

            <TextView
                android:id="@+id/contractor_item_address"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:maxLines="1"
                android:text="@string/text_no_address"
                android:textColor="@color/list_subtitle"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/contractor_item_phone"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/text_no_contact"
                android:textColor="@color/list_subtitle"
                android:textSize="14sp" />

        </LinearLayout>

    </LinearLayout>

    <ImageView
        android:id="@+id/contractor_item_show"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_marginTop="8dp"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:clickable="true"
        android:contentDescription="@string/image_description"
        android:src="@drawable/ic_show"
        android:tint="@color/space_gray_02" />

</LinearLayout>
</code>```

答:
try this</p>

```<code>    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

<TextView
    android:id="@+id/contractor_item_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:maxLines="1"
    android:maxLength="10" // set ellipsize as per your reqiement
    android:text="Gem Seeker Company and  Supplies in"
    android:textSize="16sp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="(0)"
    android:textSize="16sp"
    android:textStyle="bold"
    android:maxLines="1"
    android:layout_marginStart="4dp"
    />
</LinearLayout>
</code>```

Body:
Good day! I am trying to achieve a specific kind of layout. I hope somebody could give me a hint on how to do it properly.

So, inside my layout, I have two TextView inside of a LinearLayout with horizontal orientation. The first TextView contains the name of the company and the second contains a number of the projects associated with it.

I wanted my layout to behave like this.

My current layout looks like this.

Here's the specific code for the layout:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/contractor_item_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="Gem Seeker Company and  Supplies in"
        android:textColor="@color/list_title"
        android:textSize="16sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="(0)"
        android:textSize="16sp"
        android:textStyle="bold"
        android:maxLines="1"
        android:layout_marginStart="4dp"
        android:textColor="@color/space_gray_01"/>

</LinearLayout>

Heres the complete code of the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:background="@android:color/white"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/contractor_item_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:clickable="true"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/contractor_item_avatar"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:background="@color/space_gray_01"
            android:contentDescription="@string/image_description"
            android:src="@drawable/ic_user_light" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="16dp">

            <TextView
                android:id="@+id/contractor_item_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/contractor_item_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:maxLines="1"
                    android:text="Gem Seeker Company and  Supplies in"
                    android:textColor="@color/list_title"
                    android:textSize="16sp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="(0)"
                    android:textSize="16sp"
                    android:textStyle="bold"
                    android:maxLines="1"
                    android:layout_marginStart="4dp"
                    android:textColor="@color/space_gray_01"/>

            </LinearLayout>

            <TextView
                android:id="@+id/contractor_item_address"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:maxLines="1"
                android:text="@string/text_no_address"
                android:textColor="@color/list_subtitle"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/contractor_item_phone"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/text_no_contact"
                android:textColor="@color/list_subtitle"
                android:textSize="14sp" />

        </LinearLayout>

    </LinearLayout>

    <ImageView
        android:id="@+id/contractor_item_show"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_marginTop="8dp"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:clickable="true"
        android:contentDescription="@string/image_description"
        android:src="@drawable/ic_show"
        android:tint="@color/space_gray_02" />

</LinearLayout>

Body:
try this

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

<TextView
    android:id="@+id/contractor_item_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:maxLines="1"
    android:maxLength="10" // set ellipsize as per your reqiement
    android:text="Gem Seeker Company and  Supplies in"
    android:textSize="16sp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="(0)"
    android:textSize="16sp"
    android:textStyle="bold"
    android:maxLines="1"
    android:layout_marginStart="4dp"
    />
</LinearLayout>


问:
Uploading latest version of Excel data like 2013 into SQL Server table without installing Access database engine
I get this error

The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I get this error when I try to upload Excel 2013 data into a SQL Server table using .NET. I need to solve this error without installing the Access database engine.

答:
```<code>Thank you for your response Mr.ArunGeorge. I solved my question .

I would use EPPlus and SqlBulkCopy for this. It saves having to install anything on the server, like Office or the Access database connector (ACE), and SqlBulkCopy is a very fast way to insert data into SQL Server from C# (or VB) code. Also, EPPlus will create an Excel workbook in memory from a stream which means that you don't have to save the uploaded Excel file to the server, thereby saving you from having to mess about with file permissions or clearing out saved files that are no longer needed.

You can get EPPlus from Nuget (install-package EPPlus). Once you have it, here's a very simple Web Forms example showing how to use it. First, the aspx file which only has a FileUpload and a Button:

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <asp:FileUpload ID="Upload" runat="server" />
    <asp:Button ID="Button1" runat="server" Text="Upload" />
</asp:Content>

Then the code-behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack && Upload.HasFile)
    {
        if(Path.GetExtension(Upload.FileName).Equals(".xlsx"))
        {
            var excel = new ExcelPackage(Upload.FileContent);
            var dt = excel.ToDataTable();
            using (var conn = new SqlConnection("Server=.;Database=YourDatabase;Integrated Security=SSPI"))
            {
                var bulkCopy = new SqlBulkCopy(conn);
                bulkCopy.DestinationTableName = "YourTable";
                foreach (DataColumn column in dt.Columns)
                {
                    //assumes that the Excel column names match the import table exactly
                    bulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
                }
                conn.Open();
                bulkCopy.WriteToServer(dt);
            }
        }
    }
}

You will need the following additional using statements at the top of the file:

using OfficeOpenXml;
using System.Data;
using System.Data.SqlClient;
And you will need the following extension method. Just create a class file called ExcelPackageExtensions and paste the following code into it:

public static class ExcelPackageExtensions
{
    public static DataTable ToDataTable(this ExcelPackage package)
    {
        ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
        DataTable table = new DataTable();
        foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])
        {
            table.Columns.Add(firstRowCell.Text);
        }
        for (var rowNumber = 2; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
        {
            var row = workSheet.Cells[rowNumber, 1, rowNumber, workSheet.Dimension.End.Column];
            var newRow = table.NewRow();
            foreach (var cell in row)
            {
                newRow[cell.Start.Column - 1] = cell.Text;
            }
            table.Rows.Add(newRow);
        }
        return table;
    }
}
You obviously need to change the connection string and table name to suit your needs, and if you have a mismatch between column names in the Excel file and the database (or don't have a header row in the Excel sheet) you will have to map columns individually instead of generically like I have here.
</code>```


问:
Scrappy xPath search the same node based on value
Any idea how to extract the value of "sku" based on this value, "configId": "785877"

Thanks

Scrape

```<code>response.xpath('//div[@class="c-quick-buy  c-product-card__buy-button"]/@data-js-component-params').extract()
</code>```

Data extract

```<code><div class="c-quick-buy  c-product-card__buy-button"

        data-js-component="quick-buy"
        data-js-component-params='{
            "product": {
                "sku": "NO225ELAQUDXANMY",
                "skuSimple": "NO225ELAQUDXANMY-799443",
                "price": "90.00",
                "configId": "785877",
                "ff": "1"
            },
            "hasSize": false
        }'
     >
</code>```

答:
Depending on how predictable is the inner json you could do something like:

```<code>xpath_query = '//div[contains(@data-js-component-params, \'"configId": "785877"\')]/@data-js-component-params'
js_data = response.xpath(xpath_query).extract_first() or '{}'
json.loads(js_data).get('product',{}).get('sku')
</code>```

you could even change the the query to

```<code>xpath_query = '//div[re:test(@data-js-component-params, \'"configId":\s+"785877"\')]/@data-js-component-params'
</code>```

Body:
Any idea how to extract the value of "sku" based on this value, "configId": "785877"

Thanks

Scrape

response.xpath('//div[@class="c-quick-buy  c-product-card__buy-button"]/@data-js-component-params').extract()

Data extract

Body:
Depending on how predictable is the inner json you could do something like:

xpath_query = '//div[contains(@data-js-component-params, \'"configId": "785877"\')]/@data-js-component-params'
js_data = response.xpath(xpath_query).extract_first() or '{}'
json.loads(js_data).get('product',{}).get('sku')

you could even change the the query to

xpath_query = '//div[re:test(@data-js-component-params, \'"configId":\s+"785877"\')]/@data-js-component-params'