问:
How can I implement an algorithm to encode my data into MD5 string in Python?
I'm not familiar with Python. I have a java snippet to implement an algorithm to encode my data into MD5 string. I'd like to convert it into Python. My java code is using commons-codec1.9 to encodeBase64.
Anyone can help? Thanks very much.</p>

```<code> public static void Main(args){
 String data ="token=cd264af2fbd&app_key=060176144a&client_os_type=4";
 String key = "87483ik98abh";
 String md5EncodedData = getEncodeData(data, key);
</code>```

<p>}  </p>

```<code>private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public String getEncodeData(String app_secret, String data){
    try{
        byte[] hmc = calculateRFC2104HMAC(Base64.encodeBase64(data.getBytes()), app_secret);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(hmc);
        return new String(Hex.encodeHex(thedigest));

    }catch (Exception ex){
        System.out.print(ex.getMessage().toString());
    }
    return "";
}
public static byte[] calculateRFC2104HMAC(byte[] data, String key)
        throws java.security.SignatureException
{
    try {

        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data);
        return rawHmac;

    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
}
</code>```

答:
If you want to efficiently code the MD5 Hashing using python, my github repository would definitely help to understand and interpret the mathematical definitions of MD% in python

Cryptographic Algoritms Implementation Using Python

```</p>

<p>def md5(message): </p>

```message = bytearray(message) #copy our input into a mutable buffer
orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff
message.append(0x80)
while len(message)%64 != 56:
    message.append(0)
message += orig_len_in_bits.to_bytes(8, byteorder='little')

hash_pieces = init_values[:]

for chunk_ofst in range(0, len(message), 64):
    a, b, c, d = hash_pieces
    chunk = message[chunk_ofst:chunk_ofst+64]
    for i in range(64):
        f = functions[i](b, c, d)
        g = index_functions[i](i)
        to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')
        new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF
        a, b, c, d = d, new_b, b, c
    for i, val in enumerate([a, b, c, d]):
        hash_pieces[i] += val
        hash_pieces[i] &= 0xFFFFFFFF

return sum(x<<(32*i) for i, x in enumerate(hash_pieces)
```

<p>```

Body:
I'm not familiar with Python. I have a java snippet to implement an algorithm to encode my data into MD5 string. I'd like to convert it into Python. My java code is using commons-codec1.9 to encodeBase64.
Anyone can help? Thanks very much.

 public static void Main(args){
 String data ="token=cd264af2fbd&app_key=060176144a&client_os_type=4";
 String key = "87483ik98abh";
 String md5EncodedData = getEncodeData(data, key);

}

private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public String getEncodeData(String app_secret, String data){
    try{
        byte[] hmc = calculateRFC2104HMAC(Base64.encodeBase64(data.getBytes()), app_secret);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(hmc);
        return new String(Hex.encodeHex(thedigest));

    }catch (Exception ex){
        System.out.print(ex.getMessage().toString());
    }
    return "";
}
public static byte[] calculateRFC2104HMAC(byte[] data, String key)
        throws java.security.SignatureException
{
    try {

        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data);
        return rawHmac;

    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
}

Body:
If you want to efficiently code the MD5 Hashing using python, my github repository would definitely help to understand and interpret the mathematical definitions of MD% in python

Cryptographic Algoritms Implementation Using Python

```</p>

<p>def md5(message): </p>

<pre><code>message = bytearray(message) #copy our input into a mutable buffer
orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff
message.append(0x80)
while len(message)%64 != 56:
    message.append(0)
message += orig_len_in_bits.to_bytes(8, byteorder='little')

hash_pieces = init_values[:]

for chunk_ofst in range(0, len(message), 64):
    a, b, c, d = hash_pieces
    chunk = message[chunk_ofst:chunk_ofst+64]
    for i in range(64):
        f = functions[i](b, c, d)
        g = index_functions[i](i)
        to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')
        new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF
        a, b, c, d = d, new_b, b, c
    for i, val in enumerate([a, b, c, d]):
        hash_pieces[i] += val
        hash_pieces[i] &= 0xFFFFFFFF

return sum(x<<(32*i) for i, x in enumerate(hash_pieces)
</code></pre>

<p>```


来源: stackexchange

问:
Importing styles from meteor into React Storybook
I am trying to set up react storybook with my meteor 1.4 project that has the package twbs:bootstrap3 and some custom styles.

After reading the info from the link to set up styles here I have the following code:

```<code>const path = require('path');

module.exports = {
  module: {
    loaders: [
      {
        test: /\.less?$/,
        loader: ["style", "css", "less"],
        include: path.resolve(__dirname, '../'),
      },
      {
        test: /\.css?$/,
        loader: ["style", "raw"],
        include: path.resolve(__dirname, '../'),
      },
   }
}
</code>```

Here is my story

```<code>import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { styles } from './shared';
import HomeSearch from '../features/Search/components/HomeSearch/HomeSearch.jsx';

storiesOf('HomeSearch', module)
  .add('normal', () => {
      return getItem();
    });

function getItem() {
  return <HomeSearch />
}
</code>```

But I am not sure how to import those "packed" styles into the stories.

答:
If the CSS is pre-compiled, and global, you can add the  tags in a custom preview-head.html file. see: https://storybook.js.org/configurations/add-custom-head-tags/

If the CSS is non global, or needs to be processed, you need to add the correct loaders to the custom webpack config. see https://storybook.js.org/configurations/custom-webpack-config/

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set up react storybook with my meteor 1.4 project that has the package twbs:bootstrap3 and some custom styles.

After reading the info from the link to set up styles here I have the following code:

const path = require('path');

module.exports = {
  module: {
    loaders: [
      {
        test: /\.less?$/,
        loader: ["style", "css", "less"],
        include: path.resolve(__dirname, '../'),
      },
      {
        test: /\.css?$/,
        loader: ["style", "raw"],
        include: path.resolve(__dirname, '../'),
      },
   }
}

Here is my story

import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { styles } from './shared';
import HomeSearch from '../features/Search/components/HomeSearch/HomeSearch.jsx';

storiesOf('HomeSearch', module)
  .add('normal', () => {
      return getItem();
    });

function getItem() {
  return <HomeSearch />
}

But I am not sure how to import those "packed" styles into the stories.


问:
Using wordpress editor in my projects
I think CKEditor is the most powerful WYSIWYG Editor, but CKEditor have some problem, and I found the Wordpress editor is powerful than CKEditor :)

But I don't know what is wordpress editor ? Is it OpenSource ?

How can I use WordPress Editor in my projects?

UPDATE:

I mean was wordpress default editor :

答:
Below answers guide you properly I hope

How to use Wordpress Text Editor in a custom plugin

https://codex.wordpress.org/Function_Reference/wp_editor

https://premium.wpmudev.org/blog/daily-tip-how-to-set-the-default-editor-to-visual-or-html-in-wordpress/

https://www.bloggersignal.com/set-html-editor-as-default-editor-in-wordpress/

https://www.webhostinghero.com/how-to-switch-the-wordpress-editor-to-html-by-default/

Title: Using wordpress editor in my projects


问:
Replacing specific characters in python string
I have a string which is

string = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"

I want to replace specific set of ' to %. It has to look like

```<code>string = "create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})"
</code>```

I'm trying to use replace function. But failed to get the exact result.

答:
Use re to replace patterns.

```<code>>>> import re
>>> s = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"
>>> S=re.sub(r"\'([A-Z]*)\'",r"%\1%",s)
create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})
</code>```

Body:
I have a string which is

string = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"

I want to replace specific set of ' to %. It has to look like

string = "create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})"

I'm trying to use replace function. But failed to get the exact result.

Body:
Use re to replace patterns.

>>> import re
>>> s = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"
>>> S=re.sub(r"\'([A-Z]*)\'",r"%\1%",s)
create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})


问:
oracle dynamic query issue: how to get value into a variable which is coming as a part of string
I need help in dynamic query for the following scenario.

I have a procedure A in which I am storing a string in an output variable which will be passed to a procedure B.

Procedure B receives tablename also as an input parameter but procedure A doesn't, however procedure A also uses the tablename variable.

I am thinking of how to use tablename variable in procedure A string such that when the string is passed to procedure B, its input variable value of tablename gets assigned to the tablename variable in the string of procedure A.

I will try to explain with some code sample. It's a sample and no actual code.

```<code>proc A
begin
--- string that uses tablename but has no variable input for tablename.

mystr:='AND DAY_OF_WEEK_ID IN (SELECT B.DAY_ID FROM DAY_OF_WEEK B
                                             INNER JOIN CD.' || 'v_tableName' || ' CD
                                             ON TRIM(TO_CHAR(TO_TIMESTAMP(CD.GMT_SEIZ_DT_TIME,''YYYYMMDDHH24MISS''), ''DAY'')) = B.NAME WHERE B.DAY_ID IN (1,7))';

end;

proc B
(v_tablename, mystr)
begin
mystr2:= 'insert into sometable
select ' || mystr || ' from ' || v_tablename
end;
</code>```

so the mystr string already contains tablename variable for which I want the same value to be assigned as the variable v_table_name of procedure B.

I apologies if I have made the scenario too complex but I couldn't find a better way.

Regards.

答:
In procedure B you need to substitute the placeholder in the passed string with the actual table name.

Your posted pseudo-code is a bit garbled, but it seems the placeholder in the string generated by procedure A is 'v_tablename' and the actual table name in procedure B is held in a variable called v_tablename. That being the case, this would work for you:

```<code>mystr := replace(mystr, 'v_tablename', v_tablename);
</code>```

Body:
I need help in dynamic query for the following scenario.

I have a procedure A in which I am storing a string in an output variable which will be passed to a procedure B.

Procedure B receives tablename also as an input parameter but procedure A doesn't, however procedure A also uses the tablename variable.

I am thinking of how to use tablename variable in procedure A string such that when the string is passed to procedure B, its input variable value of tablename gets assigned to the tablename variable in the string of procedure A.

I will try to explain with some code sample. It's a sample and no actual code.

proc A
begin
--- string that uses tablename but has no variable input for tablename.

mystr:='AND DAY_OF_WEEK_ID IN (SELECT B.DAY_ID FROM DAY_OF_WEEK B
                                             INNER JOIN CD.' || 'v_tableName' || ' CD
                                             ON TRIM(TO_CHAR(TO_TIMESTAMP(CD.GMT_SEIZ_DT_TIME,''YYYYMMDDHH24MISS''), ''DAY'')) = B.NAME WHERE B.DAY_ID IN (1,7))';

end;

proc B
(v_tablename, mystr)
begin
mystr2:= 'insert into sometable
select ' || mystr || ' from ' || v_tablename
end;

so the mystr string already contains tablename variable for which I want the same value to be assigned as the variable v_table_name of procedure B.

I apologies if I have made the scenario too complex but I couldn't find a better way.

Regards.

Body:
In procedure B you need to substitute the placeholder in the passed string with the actual table name.

Your posted pseudo-code is a bit garbled, but it seems the placeholder in the string generated by procedure A is 'v_tablename' and the actual table name in procedure B is held in a variable called v_tablename. That being the case, this would work for you:

mystr := replace(mystr, 'v_tablename', v_tablename);


问:
set favicon in django admin
I need to set up a favicon for django admin interface.

It would be best to do it globally, without overriding templates for all apps.

What is the cleanest way to do it? I tried searching Django documentation for this, but found nothing.

答:
Override the Django base.html template and put it under admin directory like my_app/templates/admin/base.html.

Add {% block extrahead %} to the overriding template.

```<code>   {% extends 'admin/base.html' %}
    {% load staticfiles %}
    {% block javascripts %}
        {{ block.super }}
    <script type="text/javascript" src="{% static 'app/js/action.js' %}"></script>

    {% endblock %}

    {% block extrahead %}
        <link rel="shortcut icon" href="{% static 'app/img/favicon.ico'  %}" />
    {% endblock %}
    {% block stylesheets %}

        {{ block.super }}
    {% endblock %}
</code>```

Title: set favicon in django admin

Body:
Override the Django base.html template and put it under admin directory like my_app/templates/admin/base.html.

Add {% block extrahead %} to the overriding template.

   {% extends 'admin/base.html' %}
    {% load staticfiles %}
    {% block javascripts %}
        {{ block.super }}
    <script type="text/javascript" src="{% static 'app/js/action.js' %}"></script>

    {% endblock %}

    {% block extrahead %}
        <link rel="shortcut icon" href="{% static 'app/img/favicon.ico'  %}" />
    {% endblock %}
    {% block stylesheets %}

        {{ block.super }}
    {% endblock %}

ContentLicense: CC BY-SA 4.0


问:
Getting list of my manager's directs except few of them using my employee id
I have an employee table with EmployeeId, ReportsToEmployeeId column, which gives list of employees in an org and whom the employee reports to.

```<code>EmployeeId, ReportsToEmployeeId
EMP2        EMP1
EMP3        EMP1
EMP4        EMP1
EMP5        EMP1
EMP6        EMP1
EMP7        EMP1
</code>```

I also have one more table - AssistantManager. This table specified under a manager, few of the directs act as assistant manager (team lead). This table contains two column, AssistantManagerEmployeeId, ReportsToEmployeeId.

```<code>AssistantManagerEmployeeId, ReportsToEmployeeId
EMP3                        EMP1
EMP6                        EMP1
</code>```

Consider I am one of the Assistant Manager (EMP3) of a Manager (EMP1). I need to query list of my manager's (EMP1) directs except AssistantManagers (EMP3, EMP6). So the result should contains -

```<code>EmployeeId, ReportsToEmployeeId
EMP2        EMP1
EMP4        EMP1
EMP5        EMP1
EMP7        EMP1
</code>```

I am writing the query as below

```<code>SELECT *
FROM Employee
JOIN AssistantManager ON AssistantManager.ReportsToEmployeeId = Employee.ReportsToEmployeeId
WHERE AssistantManager.AssistantManagerEmployeeId = @MyEmployeeId
AND Employee.EmployeeId NOT IN
(
-- Gives list of Assistant Managers who as under my manager
SELECT OtherRec.AssistantManagerEmployeeId
FROM AssistantManager myRec
JOIN AssistantManager OtherRec ON OtherRec.ReportsToEmployeeId = myRec.ReportsToEmployeeId
Where myRec.AssistantManagerEmployeeId = @MyEmployeeId
)
</code>```

Please let me know a query that more efficient. I am actually looking if possible to write without a sub query.

Many Thanks, Thirumalai M

答:
Your question is not clear.

I understand from your question that you want to get a list of people who are reporting to your manager.

Lets get your manager's Id first.

Write a query to get ManagerID using your EmployeeID.

```<code>SELECT ManagerID
FROM tblEmployee
WHERE EmployeeID=@youremployeeID
</code>```

Use this query as sub query and get a list of all the employees who are reporting to your manager.

```<code>SELECT EmployeeID
FROM tblEmployee
WHERE ManagerID=(SELECT ManagerID
                FROM tblEmployee
                WHERE EmployeeID=@youremployeeID)
</code>```

EDIT 1

Why you  dont want to use a subquery?

Try something like this

```<code> SELECT *
 FROM tblEmployee E
 WHERE E.EmployeeId NOT IN (SELECT AssistantManagerEmployeeId
                        FROM tblAssistantManager
                        WHERE A.ReportsToEmployeeId=@yourManagerID)
 AND E.ReportsToEmployeeId=@yourManagerID
</code>```

Body:
I have an employee table with EmployeeId, ReportsToEmployeeId column, which gives list of employees in an org and whom the employee reports to.

EmployeeId, ReportsToEmployeeId
EMP2        EMP1
EMP3        EMP1
EMP4        EMP1
EMP5        EMP1
EMP6        EMP1
EMP7        EMP1

I also have one more table - AssistantManager. This table specified under a manager, few of the directs act as assistant manager (team lead). This table contains two column, AssistantManagerEmployeeId, ReportsToEmployeeId.

AssistantManagerEmployeeId, ReportsToEmployeeId
EMP3                        EMP1
EMP6                        EMP1

Consider I am one of the Assistant Manager (EMP3) of a Manager (EMP1). I need to query list of my manager's (EMP1) directs except AssistantManagers (EMP3, EMP6). So the result should contains -

EmployeeId, ReportsToEmployeeId
EMP2        EMP1
EMP4        EMP1
EMP5        EMP1
EMP7        EMP1

I am writing the query as below

SELECT *
FROM Employee
JOIN AssistantManager ON AssistantManager.ReportsToEmployeeId = Employee.ReportsToEmployeeId
WHERE AssistantManager.AssistantManagerEmployeeId = @MyEmployeeId
AND Employee.EmployeeId NOT IN
(
-- Gives list of Assistant Managers who as under my manager
SELECT OtherRec.AssistantManagerEmployeeId
FROM AssistantManager myRec
JOIN AssistantManager OtherRec ON OtherRec.ReportsToEmployeeId = myRec.ReportsToEmployeeId
Where myRec.AssistantManagerEmployeeId = @MyEmployeeId
)

Please let me know a query that more efficient. I am actually looking if possible to write without a sub query.

Many Thanks, Thirumalai M

Body:
Your question is not clear.

I understand from your question that you want to get a list of people who are reporting to your manager.

Lets get your manager's Id first.

Write a query to get ManagerID using your EmployeeID.

SELECT ManagerID
FROM tblEmployee
WHERE EmployeeID=@youremployeeID

Use this query as sub query and get a list of all the employees who are reporting to your manager.

SELECT EmployeeID
FROM tblEmployee
WHERE ManagerID=(SELECT ManagerID
                FROM tblEmployee
                WHERE EmployeeID=@youremployeeID)

EDIT 1

Why you  dont want to use a subquery?

Try something like this

 SELECT *
 FROM tblEmployee E
 WHERE E.EmployeeId NOT IN (SELECT AssistantManagerEmployeeId
                        FROM tblAssistantManager
                        WHERE A.ReportsToEmployeeId=@yourManagerID)
 AND E.ReportsToEmployeeId=@yourManagerID


问:
How to run python program on my windows system after installation using notepad++ or dreamviewer
I'm new for python i installed python 3.6.1 on my windows 7 system after that i searched a lot but i cannot understand.please help me how to create a new python program using notepad++ or adobe dream viewer...</p>

答: Take a look at the documentation on https://docs.python.org/3.6/faq/windows.html instead, since that is the version of python have installed.</p>


问:
Storing music ON/OFF state in preference-LibGdx
I have music button like this:

```<code>private void drawMusicButton() {
    musicButton = new ImageButton(new TextureRegionDrawable(musicTexture1),new TextureRegionDrawable(musicTexture2), new TextureRegionDrawable(musicTexture2));
    musicButton.setChecked(!game.menuMusicBool);
    stage.addActor(musicButton);

    musicButton.setPosition(UiConstants.MUSIC_X, UiConstants.MUSIC_Y, Align.bottom);
    musicButton.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            if (!game.buttonClickSoundBool&&game.soundBool)
                buttonClickSound.play();
            if (game.menuMusicBool)
                game.menuMusicBool = false;
            else
                game.menuMusicBool = true;
            musicStateManager.saveMusicState();
        }
    });
}
</code>```

initially menuMusicBool is true.

```<code>public boolean menuMusicBool = true;
</code>```

I want to store the music ON/OFF state in preference so that while relaunching the game,I can get the previously selected state.

My preference class is like this:

```<code>public class MusicStateManager {

  private final Preferences prefs;
  public final Mgame game;

  private static final String MUSIC_STATE = "musicState";

  public MusicStateManager(Mgame game){
      this.game = game;
      prefs = Gdx.app.getPreferences(Mgame.class.getName());
  }

  public void getPreferenceValues(){ }

  public void reset(){ }

  public void saveMusicState() {

    prefs.putBoolean(MUSIC_STATE, game.menuMusicBool);
    prefs.flush();
  }

  public void getMusicState() {
     game.menuMusicBool = prefs.getBoolean(MUSIC_STATE);
  }
</code>```

getMusicState() I am calling inside render().

But in preference,value is not getting stored properly.
I am not able to save the previous state while quitting and relaunching the game.

What I did wrong in the code?

答:
```<code>public class MusicStateManager {

  private final Preferences prefs;
  public final Mgame game;

  private static final String PREF_NAME ="APP_NAME";
  private static final String MUSIC_STATE = "musicState";

  public MusicStateManager(Mgame game){
      this.game = game;
      prefs = Gdx.app.getPreferences(PREF_NAME);
      game.menuMusicBool = prefs.getBoolean(MUSIC_STATE, true); // return true when key not found
  }

  public void saveMusicState(boolean musicState) {
    game.menuMusicBool = musicState;
    prefs.putBoolean(MUSIC_STATE, musicState);
    prefs.flush();

    // music state changed and saved, now need to start or stop music
    if(game.menuMusicBool)    // I supposed game having music object reference
         game.music.play();
    else
         game.music.stop();
  }

  public boolean getMusicState() {
     return prefs.getBoolean(MUSIC_STATE);
  }
</code>```

When you want to play music use game.menuMusicBool as flag

```<code>public void playMusic(Music music){

    if(game.menuMusicBool && !music.isPlaying()){
         music.play();
         music.setLooping(true);
     }
}
</code>```

And Inside listener of musicButton

```<code>musicButton.addListener(new ChangeListener() {
    @Override
    public void changed(ChangeEvent event, Actor actor) {
        if (!game.buttonClickSoundBool&&game.soundBool)
            buttonClickSound.play();
         musicStateManager.saveMusicState(!game.menuMusicBool);  // state inversed and saved in prefs
    }
});
</code>```

Body:
I have music button like this:

private void drawMusicButton() {
    musicButton = new ImageButton(new TextureRegionDrawable(musicTexture1),new TextureRegionDrawable(musicTexture2), new TextureRegionDrawable(musicTexture2));
    musicButton.setChecked(!game.menuMusicBool);
    stage.addActor(musicButton);

    musicButton.setPosition(UiConstants.MUSIC_X, UiConstants.MUSIC_Y, Align.bottom);
    musicButton.addListener(new ChangeListener() {
        @Override
        public void changed(ChangeEvent event, Actor actor) {
            if (!game.buttonClickSoundBool&&game.soundBool)
                buttonClickSound.play();
            if (game.menuMusicBool)
                game.menuMusicBool = false;
            else
                game.menuMusicBool = true;
            musicStateManager.saveMusicState();
        }
    });
}

initially menuMusicBool is true.

public boolean menuMusicBool = true;

I want to store the music ON/OFF state in preference so that while relaunching the game,I can get the previously selected state.

My preference class is like this:

public class MusicStateManager {

  private final Preferences prefs;
  public final Mgame game;

  private static final String MUSIC_STATE = "musicState";

  public MusicStateManager(Mgame game){
      this.game = game;
      prefs = Gdx.app.getPreferences(Mgame.class.getName());
  }

  public void getPreferenceValues(){ }

  public void reset(){ }

  public void saveMusicState() {

    prefs.putBoolean(MUSIC_STATE, game.menuMusicBool);
    prefs.flush();
  }

  public void getMusicState() {
     game.menuMusicBool = prefs.getBoolean(MUSIC_STATE);
  }

getMusicState() I am calling inside render().

But in preference,value is not getting stored properly.
I am not able to save the previous state while quitting and relaunching the game.

What I did wrong in the code?

Body:
public class MusicStateManager {

  private final Preferences prefs;
  public final Mgame game;

  private static final String PREF_NAME ="APP_NAME";
  private static final String MUSIC_STATE = "musicState";

  public MusicStateManager(Mgame game){
      this.game = game;
      prefs = Gdx.app.getPreferences(PREF_NAME);
      game.menuMusicBool = prefs.getBoolean(MUSIC_STATE, true); // return true when key not found
  }

  public void saveMusicState(boolean musicState) {
    game.menuMusicBool = musicState;
    prefs.putBoolean(MUSIC_STATE, musicState);
    prefs.flush();

    // music state changed and saved, now need to start or stop music
    if(game.menuMusicBool)    // I supposed game having music object reference
         game.music.play();
    else
         game.music.stop();
  }

  public boolean getMusicState() {
     return prefs.getBoolean(MUSIC_STATE);
  }

When you want to play music use game.menuMusicBool as flag

public void playMusic(Music music){

    if(game.menuMusicBool && !music.isPlaying()){
         music.play();
         music.setLooping(true);
     }
}

And Inside listener of musicButton

musicButton.addListener(new ChangeListener() {
    @Override
    public void changed(ChangeEvent event, Actor actor) {
        if (!game.buttonClickSoundBool&&game.soundBool)
            buttonClickSound.play();
         musicStateManager.saveMusicState(!game.menuMusicBool);  // state inversed and saved in prefs
    }
});


问:
Is Azure Service Fabric Stateful Service State shared across partitions?
I'm working on a Stateful Service that manages inventory for a bunch of products for our customers. Each customer belongs to a tenant group which may have an instance of this stateful service in his own partition. So a tenant with Id 10 and a tenant with Id 11 may be in a same partition (let's assume).

Each tenant has access to Inventory for an Item with Id = 100 (for example). Each time a person wants to purchase this item, I check if the Inventory exists for this tenant, if not, I notify the calling application (a Reliable Actor in this case) and let him know.

However, I've noticed that I was storing a reliable dictionary with the Key of the Item Id and the inventory counts. I noticed that even though the services belong to separate partitions, they still accessed the same object. Is this true that even though these services reside under different partitions, that they still have the same underlying state?

If so, would it make more sense to store this information directly at the Actor level? I didn't see reliable collections at the actor level and thus I built a Stateful Service that would be invoked by an Actor but in my prior Akka implementations, I would store this state at the Actor level.

I'm curious if anyone has implemented something similar and could shed light on this.

Thank You in advance for your responses!

Anup Marwadi

答:
No, state is not shared between different partitions. That would defeat the purpose; keeping a large dataset manageable by dividing it.

Consider implementing multi-tenancy by creating an Application instance per tenant. This way there will never be any sharing of data between tenants, and you can backup/on-/off-board tenants easily.

This article explains service partitions very well.


问:
NASM matrix-vector multiplication
I was writing an AVX matrix-vector multiplication function in C but realized an instruction I needed was not implemented in GCC, so I saw that as a golden opportunity to learn some x86 assembly. I first wrote a routine in MIPS assembly and then tried translating it. My code is not working, I get segfault and I have no idea why. If I remove the two jnz in the code, it works, but I don't understand why they would have any impact. Does this type of jump destroy registers that I'm using?

EDIT: It appears that the first two instructions in main don't set rdi to 2, but rather to 0x1000000002, which causes trouble later. Why isn't 2 loaded?

EDIT2: Got it. As @rkhb pointed out, using rXX registers loads more data than I intended. I changed the registers to the 32-bit ones (where applicable), which solved the segfault problem. However, now the program printed 0,0. This was because the loop advances eax by 8 (in the below example), but doesn't subtract that amount before returning. Thus, the values are in addr and addr+4, but the pointer returned is addr+8.

```<code>; nasm -felf64 filename.asm
; gcc filename.o

    global  main
    extern  printf

    section .data
N:  dd 2            ; dimension
a:  dd 1, 2, 3, 4       ; matrix
b:  dd 1, 2         ; vector
format: db "%d", 10, 0

    section .bss
c:  resb 8          ; reserve 8B

    section .text
main:
    ; set up arguments
    lea rdi, [N]    ; fix: change regs to edi, etc
    mov rdi, [rdi]
    lea rsi, [a]
    lea rdx, [b]
    lea rcx, [c]

    call    matvec      ; c = a*b

    ; print results
    mov rsi, [rax]
    mov rdi, format
    push    rax
    mov rax, 0
    call    printf      ; print c[0], should be 5
    pop rax
    add rax, 4
    mov rsi, [rax]
    mov rdi, format
    mov rax, 0
    call    printf      ; print c[1], should be 11

    ret

; rdi = N, rsi = int*, rdx = int*, rcx = int*
matvec:
    mov rax, rcx    ; rax = c
    mov R14, rdi    ; r14 = N
    mov R15, R14
    shl R15, 2      ; r15 = 4*N
    xor R8, R8      ; i = 0
    xor R9, R9      ; j = 0
    xor R10, R10    ; sum = 0

loop:
    mov R11, [rsi]  ; r11 = *a
    mov R12, [rdx]  ; r12 = *b
    imul    R11, R12    ; r11 *= r12
    add R10, R11    ; r10 += r11
    add rsi, 4      ; a++
    add rdx, 4      ; b++
    add R9, 1       ; j++
    cmp R14, R9
    jnz loop        ; loop while r14-r9 = N-j != 0

    mov [rax], R10  ; *c = sum
    xor R10, R10    ; sum = 0
    xor R9, R9      ; j = 0 on every i loop
    sub rdx, R15    ; b -= 4*N
    add rax, 4      ; c++
    add R8, 1       ; i++
    cmp R14, R8
    jnz loop        ; loop while r14-r8 = N-i != 0

    sub rax, R15    ; fix: subtract 4*N from return pointer
    ret
</code>```

答:
The data is declared as 4 bytes, but 8-byte registers (rax etc) are used for holding the data. When loading the data into these registers you will then your data in the low 4 bytes and garbage in the high 4 bytes. To avoid this, either change the declarations so that 8-byte data is declared (using dq), or use the 4-byte registers instead (eax etc).

Fixing that will take care of the problem with segmentation fault, but the program will return the wrong result. The result is intended to be stored at memory address c, whose value is held in rax. In the above code, that address is incremented by 4 bytes twice; while the calculated values are stored in c[0] and c[1], the address returned in rax is actually &c[2]. Thus, before returning to main you need to decrement rax by 8, or by 4*N in general.

EDIT: You can inspect registers using the GNU debugger, read this guide.

Title: NASM matrix-vector multiplication

Body:
I was writing an AVX matrix-vector multiplication function in C but realized an instruction I needed was not implemented in GCC, so I saw that as a golden opportunity to learn some x86 assembly. I first wrote a routine in MIPS assembly and then tried translating it. My code is not working, I get segfault and I have no idea why. If I remove the two jnz in the code, it works, but I don't understand why they would have any impact. Does this type of jump destroy registers that I'm using?

EDIT: It appears that the first two instructions in main don't set rdi to 2, but rather to 0x1000000002, which causes trouble later. Why isn't 2 loaded?

EDIT2: Got it. As @rkhb pointed out, using rXX registers loads more data than I intended. I changed the registers to the 32-bit ones (where applicable), which solved the segfault problem. However, now the program printed 0,0. This was because the loop advances eax by 8 (in the below example), but doesn't subtract that amount before returning. Thus, the values are in addr and addr+4, but the pointer returned is addr+8.

; nasm -felf64 filename.asm
; gcc filename.o

    global  main
    extern  printf

    section .data
N:  dd 2            ; dimension
a:  dd 1, 2, 3, 4       ; matrix
b:  dd 1, 2         ; vector
format: db "%d", 10, 0

    section .bss
c:  resb 8          ; reserve 8B

    section .text
main:
    ; set up arguments
    lea rdi, [N]    ; fix: change regs to edi, etc
    mov rdi, [rdi]
    lea rsi, [a]
    lea rdx, [b]
    lea rcx, [c]

    call    matvec      ; c = a*b

    ; print results
    mov rsi, [rax]
    mov rdi, format
    push    rax
    mov rax, 0
    call    printf      ; print c[0], should be 5
    pop rax
    add rax, 4
    mov rsi, [rax]
    mov rdi, format
    mov rax, 0
    call    printf      ; print c[1], should be 11

    ret

; rdi = N, rsi = int*, rdx = int*, rcx = int*
matvec:
    mov rax, rcx    ; rax = c
    mov R14, rdi    ; r14 = N
    mov R15, R14
    shl R15, 2      ; r15 = 4*N
    xor R8, R8      ; i = 0
    xor R9, R9      ; j = 0
    xor R10, R10    ; sum = 0

loop:
    mov R11, [rsi]  ; r11 = *a
    mov R12, [rdx]  ; r12 = *b
    imul    R11, R12    ; r11 *= r12
    add R10, R11    ; r10 += r11
    add rsi, 4      ; a++
    add rdx, 4      ; b++
    add R9, 1       ; j++
    cmp R14, R9
    jnz loop        ; loop while r14-r9 = N-j != 0

    mov [rax], R10  ; *c = sum
    xor R10, R10    ; sum = 0
    xor R9, R9      ; j = 0 on every i loop
    sub rdx, R15    ; b -= 4*N
    add rax, 4      ; c++
    add R8, 1       ; i++
    cmp R14, R8
    jnz loop        ; loop while r14-r8 = N-i != 0

    sub rax, R15    ; fix: subtract 4*N from return pointer
    ret


问:
Delete php is not working
My database does not have unique id.

```<code>include('php_connect.php');

// check if the 'Userid' variable is set in URL, and check that it is valid
if (isset($_GET['ServerName']))
{
// get id value
    $userid = $_GET['ServerName'];
// delete the entry
    $strSQL = "DELETE from server WHERE ServerName = (?)";
    $params = array($userid);
    $stmt = sqlsrv_query( $conn, $strSQL, $params);
    if( $stmt ){
        sqlsrv_commit( $conn );
        echo "Record Deleted";
        }
    else
    {
        echo $params[0];
        echo "statement error.<br />";
        die( print_r( sqlsrv_errors(), true));
    }
    sqlsrv_close( $conn );
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
    echo "WTH Something happened to the ServerName!.<br />";
    echo "Better start over.<br />";
}

?>
</code>```

and the results is this:

```<code>WTH Something happened to the ServerName!
Better start over
</code>```

答:
Change $_GET['ServerName'] to $_GET['Userid']:

```<code>if (isset($_GET['Userid']))
{
    //rest of codes
</code>```

Title: Delete php is not working

Body:
My database does not have unique id.

include('php_connect.php');

// check if the 'Userid' variable is set in URL, and check that it is valid
if (isset($_GET['ServerName']))
{
// get id value
    $userid = $_GET['ServerName'];
// delete the entry
    $strSQL = "DELETE from server WHERE ServerName = (?)";
    $params = array($userid);
    $stmt = sqlsrv_query( $conn, $strSQL, $params);
    if( $stmt ){
        sqlsrv_commit( $conn );
        echo "Record Deleted";
        }
    else
    {
        echo $params[0];
        echo "statement error.
";
        die( print_r( sqlsrv_errors(), true));
    }
    sqlsrv_close( $conn );
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
    echo "WTH Something happened to the ServerName!.
";
    echo "Better start over.
";
}

?>

and the results is this:

WTH Something happened to the ServerName!
Better start over

Body:
Change $_GET['ServerName'] to $_GET['Userid']:

if (isset($_GET['Userid']))
{
    //rest of codes


问:
How to combine javascript objects and then convert into JSON?
I have two javascript objects.Find below the two objects:

```<code>var tableRespondent = [{Id: 1, name: "abc", mail: "abc@gmail.com"}];
var tableQuestionnaire = [{Id: 1, externalId: "Q1", text: "Food Questionnaire"}, {Id: 2, externalId: "Q2", text: "Pet Questionnaire"}];
</code>```

Now I need to combine them in below format:

```<code>var output = {Respondent: [{Id: 1, name: "abc", mail: "abc@gmail.com"}], Questionnaire: [{Id: 1, externalId: "Q1", text: "Food Questionnaire"},{Id: 2, externalId: "Q2", text: "Pet Questionnaire"}] };
</code>```

And then I need to convert it into JSON as follows:

```<code>var outputJson = var output = {"Respondent": [{"Id": 1, "name": "abc", "mail": "abc@gmail.com"}], Questionnaire: [{"Id": 1, "externalId": "Q1", "text": "Food Questionnaire"}, {"Id": 2, "externalId": "Q2", "text": "Pet Questionnaire"}] };
</code>```

How should this be achieved? I am fairly new to javascript.

答:
The below code will help you

var output = {};
var tableRespondent = [{Id: 1, name: "abc", mail: "abc@gmail.com"}];
var tableQuestionnaire = [{Id: 1, externalId: "Q1", text: "Food Questionnaire"}, {Id: 2, externalId: "Q2", text: "Pet Questionnaire"}];

output['tableRespondent'] = tableRespondent;
output['tableQuestionnaire'] = tableQuestionnaire;

output = JSON.stringify(output);

console.log(output);

//Json string
console.log(typeof output);```

Body:
I have two javascript objects.Find below the two objects:

var tableRespondent = [{Id: 1, name: "abc", mail: "abc@gmail.com"}];
var tableQuestionnaire = [{Id: 1, externalId: "Q1", text: "Food Questionnaire"}, {Id: 2, externalId: "Q2", text: "Pet Questionnaire"}];

Now I need to combine them in below format:

var output = {Respondent: [{Id: 1, name: "abc", mail: "abc@gmail.com"}], Questionnaire: [{Id: 1, externalId: "Q1", text: "Food Questionnaire"},{Id: 2, externalId: "Q2", text: "Pet Questionnaire"}] };

And then I need to convert it into JSON as follows:

var outputJson = var output = {"Respondent": [{"Id": 1, "name": "abc", "mail": "abc@gmail.com"}], Questionnaire: [{"Id": 1, "externalId": "Q1", "text": "Food Questionnaire"}, {"Id": 2, "externalId": "Q2", "text": "Pet Questionnaire"}] };

How should this be achieved? I am fairly new to javascript.


问:
Datatable refresh not working if page state is true
I have data table which is saving current page state.

```<code>var tbl = $('#datatable').dataTable({
  "bStateSave": true,
  "fnStateSave": function(oSettings, oData) {
    localStorage.setItem('datatable', JSON.stringify(oData));
  },
  "fnStateLoad": function(oSettings) {
    return JSON.parse(localStorage.getItem('datatable'));
  },
  "order": [
    [6, "desc"]
  ],
  "columnDefs": [{
    "targets": [6],
    "visible": false,
    "searchable": false
  }]
});
</code>```

I refreshed my page.It's not refreshing because I saved page state.
I searched by using search box and refreshed it.Still not working.

I have 10 pages. for each raw I have inner page. If I want to see some data from 4th page's inner page, and coming back to the list page I need to save the page state.

Please suggest to solve this.

答:
I have done similar implementation in one of my projects.

I used Datatable ajax reload with

```<code>resetPaging=true & resetPaging=false
</code>```

options as per my requirements. Here is the link for the same.

https://datatables.net/reference/api/ajax.reload()

Hope this helps!

Body:
I have data table which is saving current page state.

var tbl = $('#datatable').dataTable({
  "bStateSave": true,
  "fnStateSave": function(oSettings, oData) {
    localStorage.setItem('datatable', JSON.stringify(oData));
  },
  "fnStateLoad": function(oSettings) {
    return JSON.parse(localStorage.getItem('datatable'));
  },
  "order": [
    [6, "desc"]
  ],
  "columnDefs": [{
    "targets": [6],
    "visible": false,
    "searchable": false
  }]
});

I refreshed my page.It's not refreshing because I saved page state.
I searched by using search box and refreshed it.Still not working.

I have 10 pages. for each raw I have inner page. If I want to see some data from 4th page's inner page, and coming back to the list page I need to save the page state.

Please suggest to solve this.

Body:
I have done similar implementation in one of my projects.

I used Datatable ajax reload with

resetPaging=true & resetPaging=false

options as per my requirements. Here is the link for the same.

https://datatables.net/reference/api/ajax.reload()

Hope this helps!


问:
c# Unit Testing errors
im trying to get familiar with unit testing , but I keep getting this annoying error and I have no idea why. I made a class that just divides 2 numbers.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DivideNum
{
    class Program
    {
        public static int doStuff(int num1, int num2)
        {
            int result = num1 / num2;
            return result;

        }
        static void Main(string[] args)
        {

        }
    }
}
</code>```

I then made my unit test

```<code>using DivideNum;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {

            //arrange
            int a = 10;
            int b = 2;
            int result = 5;

            //act

        }
    }
}
</code>```

i added a reference to my DivideNum namespace and added using DivideNum , but i still cant get a reference to the DivideNum class in my testing class. It wont show up at all in my testing code. why cant i use my DivideNum class in my Test class?

答:
You need to mark your class as public if you want to access it from another assembly (Your unit test project). Like this:</p>

```<code>public class Program
{
    public static int doStuff(int num1, int num2)
    {
        int result = num1 / num2;
        return result;

    }
    static void Main(string[] args)
    {

    }
}
</code>```

Title: c# Unit Testing errors

Body:
im trying to get familiar with unit testing , but I keep getting this annoying error and I have no idea why. I made a class that just divides 2 numbers.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DivideNum
{
    class Program
    {
        public static int doStuff(int num1, int num2)
        {
            int result = num1 / num2;
            return result;

        }
        static void Main(string[] args)
        {

        }
    }
}

I then made my unit test

using DivideNum;
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {

            //arrange
            int a = 10;
            int b = 2;
            int result = 5;

            //act

        }
    }
}

i added a reference to my DivideNum namespace and added using DivideNum , but i still cant get a reference to the DivideNum class in my testing class. It wont show up at all in my testing code. why cant i use my DivideNum class in my Test class?

Body:
You need to mark your class as public if you want to access it from another assembly (Your unit test project). Like this:

public class Program
{
    public static int doStuff(int num1, int num2)
    {
        int result = num1 / num2;
        return result;

    }
    static void Main(string[] args)
    {

    }
}


问:
Pymongo: How to access the field value of an object in a nested array in a Projection?
I'm trying to code a projection in pymongo (3.3.0, Python 3.6.0, MongoDB 3.2).

The original data is approximately of the form:

```<code>{
    "_id" : ObjectId("592fd5ac1aee05abb6104912"),
    "Results" : {
            "SomeData" : 1234,
            "ResultAllPoints" : {
                "MyArray" : [
                     {
                         "Value" : 0.5,
                         "Result" : 1,
                     },
                     {
                          "Value" : 1.5,
                          "Result" : 1,
                     }
                     {
                          "Value" : 1.7,
                          "Result" : 1,
                     }
                ]
            }
    }
}
</code>```

I want to access the value stored in the field "Value" the second array entry of "MyArray" and use it as the value of a new field.

Using the MongoDB Shell, the command

```<code>db.my_collection.findOne().Results.ResultAllPoints.myArray[1].Value
</code>```

gives me exactly the value I want to have in my resulting collection.

However, in my projection code, neither

```<code>{"newName" : "$Results.ResultAllPoints.myArray[1].Value"}
</code>```

nor

```<code>{"newName" : "$Results.ResultAllPoints.myArray.1.Value"}
</code>```

are working. In the first case, "newName" does not appear in the result at all the second case results in an empty array as the content of "newName".

I already know that I can use

```<code>{"$arrayElemAt": [ "$Results.ResultAllPoints.MyArray", 1]}
</code>```

to access the Object containing the required information. But how can I access the content of "Value" afterwards?

Any help would be greatly appreciated! :)

EDIT: This is not a duplicate of Retrieve only the queried element in an object array in MongoDB collection, as I don't know the content of "Value" beforehand and therefore cannot use '$elemMatch'.

答:
While I wish there was a simpler solution, I found a workaround by adding a second projection in the pipeline. The first one contains all my other projection items with their new names and projects the containing array "myArray":

```<code>"newName_temp" : {"$arrayElemAt": [ "$Results.ResultAllPoints.MyArray", 1 ]}
</code>```

The second projection copies all items in the first one to keep them and then accesses the "Value" content via

```<code>"newName" : "$newName_temp.Value"
</code>```

This is quite lengthy, so I am always open to better solutions!

Body:
I'm trying to code a projection in pymongo (3.3.0, Python 3.6.0, MongoDB 3.2).

The original data is approximately of the form:

{
    "_id" : ObjectId("592fd5ac1aee05abb6104912"),
    "Results" : {
            "SomeData" : 1234,
            "ResultAllPoints" : {
                "MyArray" : [
                     {
                         "Value" : 0.5,
                         "Result" : 1,
                     },
                     {
                          "Value" : 1.5,
                          "Result" : 1,
                     }
                     {
                          "Value" : 1.7,
                          "Result" : 1,
                     }
                ]
            }
    }
}

I want to access the value stored in the field "Value" the second array entry of "MyArray" and use it as the value of a new field.

Using the MongoDB Shell, the command

db.my_collection.findOne().Results.ResultAllPoints.myArray[1].Value

gives me exactly the value I want to have in my resulting collection.

However, in my projection code, neither

{"newName" : "$Results.ResultAllPoints.myArray[1].Value"}

nor

{"newName" : "$Results.ResultAllPoints.myArray.1.Value"}

are working. In the first case, "newName" does not appear in the result at all the second case results in an empty array as the content of "newName".

I already know that I can use

{"$arrayElemAt": [ "$Results.ResultAllPoints.MyArray", 1]}

to access the Object containing the required information. But how can I access the content of "Value" afterwards?

Any help would be greatly appreciated! :)

EDIT: This is not a duplicate of Retrieve only the queried element in an object array in MongoDB collection, as I don't know the content of "Value" beforehand and therefore cannot use '$elemMatch'.

Body:
While I wish there was a simpler solution, I found a workaround by adding a second projection in the pipeline. The first one contains all my other projection items with their new names and projects the containing array "myArray":

"newName_temp" : {"$arrayElemAt": [ "$Results.ResultAllPoints.MyArray", 1 ]}

The second projection copies all items in the first one to keep them and then accesses the "Value" content via

"newName" : "$newName_temp.Value"

This is quite lengthy, so I am always open to better solutions!


问:
Join where is not working
Given Below code is not working. we have received ajax for $servid,$appid and

when we $query to print this will us array value but with where it is not give me value.

please check it

```<code>public function editable($servid,$appid) {

        $result = array();
        $this->db->select('s1.*,t4.service_id,t4.appt_id');
        $this->db->from('service s1');
        $this->db->join('appointment_animal_services t4','s1.id=t4.service_id');
        $this->db->where('t4.appt_id', $appid);
        $this->db->where('t4.service_id' ! = 's1.id');
        $this->db->where('t4.service_id' ! = $servid);
        $query = $this->db->get()->result_array();
        e($query);

    }
</code>```

答:
you are joining your table through

's1.id' and 't4.service_id'

and your where clause is

't4.service_id' != 's1.id'

so result will be null,
Remove the 2nd where clause.

Title: Join where is not working

Body:
Given Below code is not working. we have received ajax for $servid,$appid and

when we $query to print this will us array value but with where it is not give me value.

please check it

public function editable($servid,$appid) {

        $result = array();
        $this->db->select('s1.*,t4.service_id,t4.appt_id');
        $this->db->from('service s1');
        $this->db->join('appointment_animal_services t4','s1.id=t4.service_id');
        $this->db->where('t4.appt_id', $appid);
        $this->db->where('t4.service_id' ! = 's1.id');
        $this->db->where('t4.service_id' ! = $servid);
        $query = $this->db->get()->result_array();
        e($query);

    }


问:
Oracle SQL match string with left zeros padding
I have to find strings which can or cannot starts with zeros.
For instance, if I have in my db the values '00563', '563', '43563', '0563', I have to find the rows '00563', '563', '0563'.

I've tryed this:

```<code>select distinct val
from table_one
where val = '00563' OR
      val = ltrim('00563', '0');
</code>```

but doesn't work.
val is a CHAR(5 BYTE) column.

Can you help me?

EDIT:
To be precise, if I execute the query:

```<code>select distinct val
from table_one;
</code>```

the result is:

```<code>5034
(null)
4dsfd
01005
03030
03075
05034
</code>```

To me, 05034 and 5034 are the same value.

答:
Looking at the values you have provided. I guess your values will have maximum 3 numbers before it gets padded. Keeping that in mind you can try this out -</p>

```<code>select distinct val from table_one where regexp_like(val,'^0*[0-9]{1,4}$');
</code>```

Body:
I have to find strings which can or cannot starts with zeros.
For instance, if I have in my db the values '00563', '563', '43563', '0563', I have to find the rows '00563', '563', '0563'.

I've tryed this:

select distinct val
from table_one
where val = '00563' OR
      val = ltrim('00563', '0');

but doesn't work.
val is a CHAR(5 BYTE) column.

Can you help me?

EDIT:
To be precise, if I execute the query:

select distinct val
from table_one;

the result is:

5034
(null)
4dsfd
01005
03030
03075
05034

To me, 05034 and 5034 are the same value.

Body:
Looking at the values you have provided. I guess your values will have maximum 3 numbers before it gets padded. Keeping that in mind you can try this out -

select distinct val from table_one where regexp_like(val,'^0*[0-9]{1,4}$');


问:
Is it possible to override ResolveUrl?
I use the following my .net applications to resolve the path to an image or css file or javascript file.

```<code><%=ResolveUrl("~/Scripts/myscript.js")%>

<%=ResolveUrl("~/images/myimage.jpg")%>
</code>```

All my pages and controls inherit from a base page or base user control.

I have tried but didnt succeed in overriding the ResolveUrl method so that I could include some custom logic in the files path.

Any ideas how I might override the ResolveUrl method? Alternative is to create my own custom method that does similar but would prefer to work with ResolveUrl.

答: I would create your own ResolveCustomUrl method so that future developers don't go crazy

ContentLicense: CC BY-SA 2.5

Title: Is it possible to override ResolveUrl?

Body:
I use the following my .net applications to resolve the path to an image or css file or javascript file.

<%=ResolveUrl("~/Scripts/myscript.js")%>

<%=ResolveUrl("~/images/myimage.jpg")%>

All my pages and controls inherit from a base page or base user control.

I have tried but didnt succeed in overriding the ResolveUrl method so that I could include some custom logic in the files path.

Any ideas how I might override the ResolveUrl method? Alternative is to create my own custom method that does similar but would prefer to work with ResolveUrl.


问:
Graph API request returning "One or more properties contains invalid values"
I am trying to execute B2C user creation on our company's Azure Directory.  As reference, I use this site from Microsoft, and the .DotNet example in it.

https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/

I thoroughly follow the example, and I get to the point where I get
authenticated, and I am able to extract  the AD users in the directory. Here is the sample request I generated.

GET https ://graph.windows.net/mycompany/users?api-version=beta

But when I get to the part of creating a sample user in the directory, I get the error response "One or more properties contains invalid values".

POST https ://graph.windows.net/mycompany/users?api-version=beta

Here is the payload, I used, which is the exact same payload used in the site's example for user creation. This is in JSON format.

{"accountEnabled": true,"alternativeSignInNamesInfo": [{"type": "emailAddress", "value": "joeconsumer@gmail.com"}],"creationType": "NameCoexistence", "displayName": "Joe Consumer", "mailNickname": "joec","passwordProfile": {"password": "P@ssword!","forceChangePasswordNextLogin": false},"passwordPolicies": "DisablePasswordExpiration"}

This payload conforms with the requirements based on the User Creation requirements from Microsoft, also, it is the exact same payload in the site's example, which is why it is strange that I am receiving the a message that one of the properties has invalid values.  The worse thing is, the response does not explicitly state which value is the source of the problem.

Any help would be appreciated.

答:
Do you have B2C tenant created and it has application that is created in Azure AD. </p>

<p>Can you please try this payload, it works fine for me. </p>

```<code>{
  "accountEnabled": true,
  "signInNames": [
    {
      "type": "emailAddress",
      "value": "joeconsumers6@gmail.com"
    }
  ],
  "creationType": "LocalAccount",
  "displayName": "karthikeyan",
  "mailNickname": "karthikeyan",
  "passwordProfile": {
    "password": "cads2016!",
    "forceChangePasswordNextLogin": false
  },
  "passwordPolicies": "DisablePasswordExpiration",
  "city": "San Diego",
  "country": null,
  "facsimileTelephoneNumber": null,
  "givenName": "Joe",
  "mail": null,
  "mobile": null,
  "otherMails": [],
  "postalCode": "92130",
  "preferredLanguage": null,
  "state": "California",
  "streetAddress": null,
  "surname": "Consumer",
  "telephoneNumber": null,

}
</code>```

Body:
Do you have B2C tenant created and it has application that is created in Azure AD.

Can you please try this payload, it works fine for me.

{
  "accountEnabled": true,
  "signInNames": [
    {
      "type": "emailAddress",
      "value": "joeconsumers6@gmail.com"
    }
  ],
  "creationType": "LocalAccount",
  "displayName": "karthikeyan",
  "mailNickname": "karthikeyan",
  "passwordProfile": {
    "password": "cads2016!",
    "forceChangePasswordNextLogin": false
  },
  "passwordPolicies": "DisablePasswordExpiration",
  "city": "San Diego",
  "country": null,
  "facsimileTelephoneNumber": null,
  "givenName": "Joe",
  "mail": null,
  "mobile": null,
  "otherMails": [],
  "postalCode": "92130",
  "preferredLanguage": null,
  "state": "California",
  "streetAddress": null,
  "surname": "Consumer",
  "telephoneNumber": null,

}


问:
Unable to perform click on the "PrestaShop" link in an IFrame like picture shown below
Am having an issue where I need to perform a click using Selenium Java on the link "PrestaShop" shown below. It's in an IFrame and my code is also below the picture.

Link to be clicked

When inspect the link using FireBug, it shows like below

Inspect using FireBug

And below is my code

```<code>try {
                List<WebElement> frames = getAllFrames();
                for (int i = 0; i < frames.size(); i++) {

                    WebElement frame = frames.get(i);
                    driver.switchTo().frame(frame);

                    if (driver.findElement(By.xpath(".//*[@classname='_1drp _5lv6']/a")).getSize() != null) {
                        driver.findElement(By.className(".//*[@classname='_1drp _5lv6']/a")).click();
                    } else {
                        driver.switchTo().defaultContent();
                    }

                }
            } catch (NoSuchElementException ex) {
                System.out.println(ex.getMessage());
            }
</code>```

The code is getting all frames on the page and verify if the link "PrestaShop" is presence on the frame. If yes then it needs to fire a click on the link. Now, instead it returns error message - Unable to locate element: .//*[@classname='_1drp _5lv6']/a

Can please help to advise how can I fire the click successfully on the link?

答:
You can use following updated code:

```<code> List<WebElement> frames = getAllFrames();
                for (int i = 0; i < frames.size(); i++) {

                    WebElement frame = frames.get(i);
                    driver.switchTo().frame(frame);

                    if (driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).getSize() != null) {
                        driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).click();
                    } else {
                        driver.switchTo().defaultContent();
                    }

                }
            } catch (NoSuchElementException ex) {
                System.out.println(ex.getMessage());
            }
</code>```

Hope it will work for you.

Body:
Am having an issue where I need to perform a click using Selenium Java on the link "PrestaShop" shown below. It's in an IFrame and my code is also below the picture.

Link to be clicked

When inspect the link using FireBug, it shows like below

Inspect using FireBug

And below is my code

try {
                List<WebElement> frames = getAllFrames();
                for (int i = 0; i < frames.size(); i++) {

                    WebElement frame = frames.get(i);
                    driver.switchTo().frame(frame);

                    if (driver.findElement(By.xpath(".//*[@classname='_1drp _5lv6']/a")).getSize() != null) {
                        driver.findElement(By.className(".//*[@classname='_1drp _5lv6']/a")).click();
                    } else {
                        driver.switchTo().defaultContent();
                    }

                }
            } catch (NoSuchElementException ex) {
                System.out.println(ex.getMessage());
            }

The code is getting all frames on the page and verify if the link "PrestaShop" is presence on the frame. If yes then it needs to fire a click on the link. Now, instead it returns error message - Unable to locate element: .//*[@classname='_1drp _5lv6']/a

Can please help to advise how can I fire the click successfully on the link?

Body:
You can use following updated code:

 List<WebElement> frames = getAllFrames();
                for (int i = 0; i < frames.size(); i++) {

                    WebElement frame = frames.get(i);
                    driver.switchTo().frame(frame);

                    if (driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).getSize() != null) {
                        driver.findElement(By.xpath("//*[contains(text(),'PrestaShop')]")).click();
                    } else {
                        driver.switchTo().defaultContent();
                    }

                }
            } catch (NoSuchElementException ex) {
                System.out.println(ex.getMessage());
            }

Hope it will work for you.


问:
(AngularJS) Most efficient way to replace values in array globally
I want to replace all values in my array, here's the code:

```<code>var jsonImg = [
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 01.jpg"},
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 02.jpg"},
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 03.jpg"}
];

var imgUrl = JSON.stringify(jsonImg);
var oldString = imgUrl;
var newString = oldString.replace(/https:\/\/example.amazonaws.com\/images-lib\//g,"cordova.url/");

$scope.Images = JSON.parse(newString);
</code>```

But I think JSON.Stringfly and JSON.Parse are a bit redundant here, Do you think this is the most efficient way to replace all of the value JSON.Stringfly and JSON.Parse? are there some other alternative to do this? Please check the fiddle here:
https://jsfiddle.net/dedenbangkit/zu7utr6a/3/

答:
```<code>var jsonImg = [
  { 'url': 'https://example.amazonaws.com/images-lib/1496846856-Retina 01.jpg' },
  { 'url': 'https://example.amazonaws.com/images-lib/1496846856-Retina 02.jpg' },
  { 'url': 'https://example.amazonaws.com/images-lib/1496846856-Retina 03.jpg' },
];

jsonImg.map(function(image) {
  var split = image.url.split('/');
  var fileName = split[split.length - 1];
  image.url = 'cordova.url/' + fileName;
});
</code>```

This will mutate all strings in your jsonImg array, replacing the https://example.amazonaws.com/images-lib/ URL's with cordova.url/.

Body:
I want to replace all values in my array, here's the code:

var jsonImg = [
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 01.jpg"},
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 02.jpg"},
{"url":"https://example.amazonaws.com/images-lib/1496846856-Retina 03.jpg"}
];

var imgUrl = JSON.stringify(jsonImg);
var oldString = imgUrl;
var newString = oldString.replace(/https:\/\/example.amazonaws.com\/images-lib\//g,"cordova.url/");

$scope.Images = JSON.parse(newString);

But I think JSON.Stringfly and JSON.Parse are a bit redundant here, Do you think this is the most efficient way to replace all of the value JSON.Stringfly and JSON.Parse? are there some other alternative to do this? Please check the fiddle here:
https://jsfiddle.net/dedenbangkit/zu7utr6a/3/

Body:
var jsonImg = [
  { 'url': 'https://example.amazonaws.com/images-lib/1496846856-Retina 01.jpg' },
  { 'url': 'https://example.amazonaws.com/images-lib/1496846856-Retina 02.jpg' },
  { 'url': 'https://example.amazonaws.com/images-lib/1496846856-Retina 03.jpg' },
];

jsonImg.map(function(image) {
  var split = image.url.split('/');
  var fileName = split[split.length - 1];
  image.url = 'cordova.url/' + fileName;
});

This will mutate all strings in your jsonImg array, replacing the https://example.amazonaws.com/images-lib/ URL's with cordova.url/.


问:
Unity3D - How to Remove Delay in Button Click to Animation
i am making a simple game that need fast response. so in GUI, there will be some buttons. if i press button X then do Animation X, then if i press button Y then do Animation Y. Currently, i just create one button to test.

But There's a problem. Whenever i click button X, there's a delay around 1-2 seconds until animation play.

Animator Scheme:

Button onClick Target:

TalkingButtonScript.cs :

```<code> using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;

 public class TalkingButtonScript : MonoBehaviour {

     public Button Text;
     public AudioClip sound;
     public Animator ani;
     public Canvas yourcanvas;
     Animator myAnimator;
     public PlayerAnimatorControllerScript cas;

     void Start ()
     {
         Text = Text.GetComponent<Button> ();
         ani.enabled = true;
         yourcanvas.enabled = true;
     }

     public void Press()
     {
         PlayerAnimatorControllerScript.instance.talking_btn_clicked = true;
     }
 }
</code>```

PlayerAnimatorControllerScript.cs :

```<code> using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;

 public class PlayerAnimatorControllerScript : MonoBehaviour {

     public static PlayerAnimatorControllerScript instance;
     public float speed = 10.0f;
     public float jumpSpeed = 8.0f;
     public float gravity = 20.0f;
     private float total =0.0f;
     private Vector3 moveDirection = Vector3.zero;
     CharacterController controller;
     public Animator myAnimator;
     float currSpeed, Param1;
     bool Param2, Param3;
     public bool talking_btn_clicked = false;

     // Use this for initialization
     void Start () {
         instance = this;
         controller = GetComponent<CharacterController> ();
         myAnimator = GetComponent<Animator> ();
         //myAnimator.SetBool ("TalkingStatus", true);
     }

     public void talkingActive()
     {
         Debug.Log ("set talking button = active");
         talking_btn_clicked = true;
     }

     // Update is called once per frame
     void Update ()
     {
         Param1 = 0;
         Param2 = false;
         Param3 = false;
         if (controller.isGrounded) {

             if (talking_btn_clicked == true) {
                 myAnimator.SetBool ("TalkingStatus", true);
             }

             currSpeed = speed;
             if (Input.GetKey (KeyCode.LeftShift)) {
                 Debug.Log ("ShiftLeft Pressed");
                 Param2 = true;
                 currSpeed = speed / 2;
             }

             if (Input.GetKey (KeyCode.LeftControl)) {
                 Param3 = true;
             }

             Param1 = Mathf.Abs (Input.GetAxis ("Vertical"));
             transform.Rotate (0, Input.GetAxis ("Horizontal"), 0);
             myAnimator.SetFloat ("Speed", Param1);
             myAnimator.SetBool ("Shift", Param2);
             myAnimator.SetBool ("Attack", Param3);
             moveDirection = new Vector3 (0, 0, Input.GetAxis ("Vertical"));
             moveDirection = transform.TransformDirection (moveDirection);
             moveDirection *= currSpeed;

             if (Input.GetButton ("Jump")) {
                 moveDirection.y = jumpSpeed;
                 Param1 = 0.2f;
             }

         }//==controller.isGrounded
         if (!myAnimator.IsInTransition(0)) {
             //Debug.Log("Animation is in Transition");
             total = gravity * Time.deltaTime;
             moveDirection.y -= gravity * Time.deltaTime;
             controller.Move (moveDirection * Time.deltaTime);
             //Debug.Log("total = "+total);
         }
     }//==update
 }//==class
</code>```

Any Idea ?

Thanks in advance

答: This happens not because of your code. It's the transitions you need to fix (the white arrows between the animation states in Animator window). Select the one you need to trigger with TalkingStatus, in inspector uncheck Has Exit Time. Has Exit Time is waiting for your animation to finish before transition.

Body:
i am making a simple game that need fast response. so in GUI, there will be some buttons. if i press button X then do Animation X, then if i press button Y then do Animation Y. Currently, i just create one button to test.

But There's a problem. Whenever i click button X, there's a delay around 1-2 seconds until animation play.

Animator Scheme:

Button onClick Target:

TalkingButtonScript.cs :

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.UI;

 public class TalkingButtonScript : MonoBehaviour {

     public Button Text;
     public AudioClip sound;
     public Animator ani;
     public Canvas yourcanvas;
     Animator myAnimator;
     public PlayerAnimatorControllerScript cas;

     void Start ()
     {
         Text = Text.GetComponent<Button> ();
         ani.enabled = true;
         yourcanvas.enabled = true;
     }

     public void Press()
     {
         PlayerAnimatorControllerScript.instance.talking_btn_clicked = true;
     }
 }

PlayerAnimatorControllerScript.cs :

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;

 public class PlayerAnimatorControllerScript : MonoBehaviour {

     public static PlayerAnimatorControllerScript instance;
     public float speed = 10.0f;
     public float jumpSpeed = 8.0f;
     public float gravity = 20.0f;
     private float total =0.0f;
     private Vector3 moveDirection = Vector3.zero;
     CharacterController controller;
     public Animator myAnimator;
     float currSpeed, Param1;
     bool Param2, Param3;
     public bool talking_btn_clicked = false;

     // Use this for initialization
     void Start () {
         instance = this;
         controller = GetComponent<CharacterController> ();
         myAnimator = GetComponent<Animator> ();
         //myAnimator.SetBool ("TalkingStatus", true);
     }

     public void talkingActive()
     {
         Debug.Log ("set talking button = active");
         talking_btn_clicked = true;
     }

     // Update is called once per frame
     void Update ()
     {
         Param1 = 0;
         Param2 = false;
         Param3 = false;
         if (controller.isGrounded) {

             if (talking_btn_clicked == true) {
                 myAnimator.SetBool ("TalkingStatus", true);
             }

             currSpeed = speed;
             if (Input.GetKey (KeyCode.LeftShift)) {
                 Debug.Log ("ShiftLeft Pressed");
                 Param2 = true;
                 currSpeed = speed / 2;
             }

             if (Input.GetKey (KeyCode.LeftControl)) {
                 Param3 = true;
             }

             Param1 = Mathf.Abs (Input.GetAxis ("Vertical"));
             transform.Rotate (0, Input.GetAxis ("Horizontal"), 0);
             myAnimator.SetFloat ("Speed", Param1);
             myAnimator.SetBool ("Shift", Param2);
             myAnimator.SetBool ("Attack", Param3);
             moveDirection = new Vector3 (0, 0, Input.GetAxis ("Vertical"));
             moveDirection = transform.TransformDirection (moveDirection);
             moveDirection *= currSpeed;

             if (Input.GetButton ("Jump")) {
                 moveDirection.y = jumpSpeed;
                 Param1 = 0.2f;
             }

         }//==controller.isGrounded
         if (!myAnimator.IsInTransition(0)) {
             //Debug.Log("Animation is in Transition");
             total = gravity * Time.deltaTime;
             moveDirection.y -= gravity * Time.deltaTime;
             controller.Move (moveDirection * Time.deltaTime);
             //Debug.Log("total = "+total);
         }
     }//==update
 }//==class

Any Idea ?

Thanks in advance


问:
Implement the removeProperty function that takes an object and a property name
Implement the removeProperty function that takes an object and a property name and does the following:

If object obj has property prop, it removes the property from the object.
If the property has been removed, it returns true; otherwise it returns false.

What is wrong with this code?

```<code>function removeProperty(obj,prop) {
if(obj.hasOwnProperty('prop'))
  {
    console.log(obj);
    delete obj.prop;
    return true;
  }
  else
    {
      return false;
    }
}

var obj= {
  name:"John"
};

removeProperty({obj,'name'});
</code>```

答:
The expected code would be :

```<code>function removeProperty(obj, prop) {
if(prop in obj){
  delete obj[prop];
  return true;
}else{
  return false;
 }
}
</code>```

Explanation:

The hasOwnProperty() method returns a Boolean indicating whether the object has the specified property as own (not inherited) property.So to verify own and inherited properties as well use in.

Bracket notation will be the better option than obj.prop.
Since Square bracket notation allows use of characters that can't be used with dot notation(like numbers) and it also allows selection of properties using variables.
In current scenario bracket notation should be used.

Body:
Implement the removeProperty function that takes an object and a property name and does the following:

If object obj has property prop, it removes the property from the object.
If the property has been removed, it returns true; otherwise it returns false.

What is wrong with this code?

function removeProperty(obj,prop) {
if(obj.hasOwnProperty('prop'))
  {
    console.log(obj);
    delete obj.prop;
    return true;
  }
  else
    {
      return false;
    }
}

var obj= {
  name:"John"
};

removeProperty({obj,'name'});

Body:
The expected code would be :

function removeProperty(obj, prop) {
if(prop in obj){
  delete obj[prop];
  return true;
}else{
  return false;
 }
}

Explanation:

The hasOwnProperty() method returns a Boolean indicating whether the object has the specified property as own (not inherited) property.So to verify own and inherited properties as well use in.

Bracket notation will be the better option than obj.prop.
Since Square bracket notation allows use of characters that can't be used with dot notation(like numbers) and it also allows selection of properties using variables.
In current scenario bracket notation should be used.


问:
How can I quickly check if a xpath is valid in IE?
I am evaluating using Selenium to perform automated testing of my company's Asp.net Webforms application.  Since most of the html ids are auto-generated I am trying to rely on xpaths to be able to interact with my page.

As I am knew to xpaths, I am having issues trying to pinpoint the exact xpath I need to click on this element.  The process of changing my coded xpath, compiling my C# app, loading the app, running the app, then having Selenium exception out is getting pretty annoying.  I need to find some way to quickly determine if an xpath is valid (i.e. exists) or not.

Unfortunately, they coded this site to only work in IE, so that is all i have access to.

If someone has a good quick way for me to test an xpath out in IE, I would be very grateful!

答:
Use the XPath Visualizer.

This is a popular tool that through the years has taught XPath the fun way to thousands of developers.

You first load an XML file and then can enter any XPath expressions and see the selected nodes immediately hi-lighted in the XML document. There are many more features, even for experienced developers.

The XPath Visualizer can be downloaded here.


问:
Why doesn't it work when I hover on the image?
I'm sure this is incredibly stupid once I get a hint, but I can't see why the hover doesn't work. I added the jQuery just to check whether or not it works with a click.

$(document).on("click", ".figure", function() {
  $(".popover").css("opacity", "1");
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  position: relative;
}

.popover {
  background-color: blue;
  position: absolute;
  top: 0;
  left: 200px;
  opacity: 0;
  transition: opacity 0.5s ease-in-out 0s;
}

.figure:hover .popover {
  opacity: 1;
}</code>```

      Bla bla

```

答:
Because your .popover div is not a  child of .figure div.

Used + selector for this

$(document).on("click", ".figure", function() {
  $(".popover").css("opacity", "1");
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  position: relative;
}

.popover {
  background-color: blue;
  position: absolute;
  top: 0;
  left: 200px;
  opacity: 0;
  transition: opacity 0.5s ease-in-out 0s;
}

.figure:hover + .popover {
  opacity: 1;
}</code>```

      Bla bla

```

Body:
I'm sure this is incredibly stupid once I get a hint, but I can't see why the hover doesn't work. I added the jQuery just to check whether or not it works with a click.

$(document).on("click", ".figure", function() {
  $(".popover").css("opacity", "1");
})

.container {
  position: relative;
}

.popover {
  background-color: blue;
  position: absolute;
  top: 0;
  left: 200px;
  opacity: 0;
  transition: opacity 0.5s ease-in-out 0s;
}

.figure:hover .popover {
  opacity: 1;
}

      Bla bla

Body:
Because your .popover div is not a  child of .figure div.

Used + selector for this

$(document).on("click", ".figure", function() {
  $(".popover").css("opacity", "1");
})

.container {
  position: relative;
}

.popover {
  background-color: blue;
  position: absolute;
  top: 0;
  left: 200px;
  opacity: 0;
  transition: opacity 0.5s ease-in-out 0s;
}

.figure:hover + .popover {
  opacity: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='container'>
  <div class='figure'>
    <img src='https://placehold.it/100' />
  </div>
  <div class='popover'>
    <p>
      Bla bla
    </p>
  </div>
</div>


问:
Filtering files of specific folder using QFileSystemModel and QSortFilterProxyModel subclass
I am trying to filter files of QFileSystemModel using QSortFilterProxyModel. The problem is, I want to only show the contents of a specific folder while filtering. Normally, if I wanted to only show the contents of a specific folder using QFileSystemModel, I would do something like this:

```<code>view = new QTreeView(this);
fSystemModel = new QFileSystemModel(this);

view->setModel(fSystemModel);

fSystemModel->setRootPath("C:/Qt");
QModelIndex idx = fSystemModel->index("C:/Qt");

view->setRootIndex(idx);
</code>```

But when I use the QSortFilterProxyModel, the index has to be the QSortFilterProxyModel's. Since I could not find much information in Qt Documentation regarding this issue, I looked around and found this thread. Using this as a base, I created the following:

MainWindow.cpp

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    layout = new QVBoxLayout();
    ui->centralWidget->setLayout(layout);

    view = new QTreeView(this);
    fSystemModel = new QFileSystemModel(this);
    filter = new FilterModel();

    filter->setSourceModel(fSystemModel);

    layout->addWidget(view);
    view->setModel(filter);

    fSystemModel->setRootPath("C:/Qt");
    QModelIndex idx = fSystemModel->index("C:/Qt");
    QModelIndex filterIdx = filter->mapFromSource(idx);

    qDebug() << filterIdx.isValid();

    view->setRootIndex(filterIdx);
}
</code>```

FilterModel.cpp (QSortFilterProxyModel subclass)

```<code>#include "filtermodel.h"

bool FilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
    QModelIndex zIndex = sourceModel()->index(source_row, 0, source_parent);
    QFileSystemModel* fileModel = qobject_cast<QFileSystemModel*>(sourceModel());
    return fileModel->fileName(zIndex).contains("C"); //This line will have custom
                                                      //filtering behaviour in the future,
                                                      //instead of the name searching one.
}
</code>```

However, when I run the program, it does not use the specified root index. Moreover, when I use qDebug() to see if the filterIdx is valid, it prints false. What am I doing wrong?

答:
Try to see the result of the next line

```<code>qDebug() << idx << " " << fSystemModel->fileName(idx) << " " << filterIdx.isValid();
</code>```

You can notice that fSystemModel->fileName(idx) is "Qt" (not full path "C:/Qt"). So it doesn't contain "C" from your filter (FilterModel::filterAcceptsRow).

Body:
I am trying to filter files of QFileSystemModel using QSortFilterProxyModel. The problem is, I want to only show the contents of a specific folder while filtering. Normally, if I wanted to only show the contents of a specific folder using QFileSystemModel, I would do something like this:

view = new QTreeView(this);
fSystemModel = new QFileSystemModel(this);

view->setModel(fSystemModel);

fSystemModel->setRootPath("C:/Qt");
QModelIndex idx = fSystemModel->index("C:/Qt");

view->setRootIndex(idx);

But when I use the QSortFilterProxyModel, the index has to be the QSortFilterProxyModel's. Since I could not find much information in Qt Documentation regarding this issue, I looked around and found this thread. Using this as a base, I created the following:

MainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    layout = new QVBoxLayout();
    ui->centralWidget->setLayout(layout);

    view = new QTreeView(this);
    fSystemModel = new QFileSystemModel(this);
    filter = new FilterModel();

    filter->setSourceModel(fSystemModel);

    layout->addWidget(view);
    view->setModel(filter);

    fSystemModel->setRootPath("C:/Qt");
    QModelIndex idx = fSystemModel->index("C:/Qt");
    QModelIndex filterIdx = filter->mapFromSource(idx);

    qDebug() << filterIdx.isValid();

    view->setRootIndex(filterIdx);
}

FilterModel.cpp (QSortFilterProxyModel subclass)

#include "filtermodel.h"

bool FilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
    QModelIndex zIndex = sourceModel()->index(source_row, 0, source_parent);
    QFileSystemModel* fileModel = qobject_cast<QFileSystemModel*>(sourceModel());
    return fileModel->fileName(zIndex).contains("C"); //This line will have custom
                                                      //filtering behaviour in the future,
                                                      //instead of the name searching one.
}

However, when I run the program, it does not use the specified root index. Moreover, when I use qDebug() to see if the filterIdx is valid, it prints false. What am I doing wrong?

Body:
Try to see the result of the next line

qDebug() << idx << " " << fSystemModel->fileName(idx) << " " << filterIdx.isValid();

You can notice that fSystemModel->fileName(idx) is "Qt" (not full path "C:/Qt"). So it doesn't contain "C" from your filter (FilterModel::filterAcceptsRow).


问:
Why do I get an exception loop
I tried following expression in prelude:

```<code>let x = x in x
</code>```

and I've got following exception

```<code>Exception: <<loop>>
</code>```

Why is the expression recursive?

答:
let bindings in Haskell are (mutually) recursive, meaning that you can refer to any of the defined variables/functions (things to the left of the = signs) in any of their definitions (the stuff to the right of the = sign). For the case where you have arguments (functions), this is pretty much always the intuitive expected behaviour.

```<code>let fact n = if n == 0 then 1 else n * fact (n - 1) in fact 5
</code>```

In the above, you probably are not surprised that fact (n - 1) can be used in the definition of fact n. In your example, you are using x in its own definition.

When Haskell tries to evaluate let x = x in x, it keeps trying to expand x (into the RHS x) hence the loop.

Title: Why do I get an exception loop

Body:
I tried following expression in prelude:

let x = x in x

and I've got following exception

Exception: <<loop>>

Why is the expression recursive?

Body:
let bindings in Haskell are (mutually) recursive, meaning that you can refer to any of the defined variables/functions (things to the left of the = signs) in any of their definitions (the stuff to the right of the = sign). For the case where you have arguments (functions), this is pretty much always the intuitive expected behaviour.

let fact n = if n == 0 then 1 else n * fact (n - 1) in fact 5

In the above, you probably are not surprised that fact (n - 1) can be used in the definition of fact n. In your example, you are using x in its own definition.

When Haskell tries to evaluate let x = x in x, it keeps trying to expand x (into the RHS x) hence the loop.


问:
Searchable dropdown list
I want to make a search input box above the dropdown list in my site, mind to tell me how to make a searchable dropdown list ?</p>

```<code>echo "<td>";
echo "<select name='customer_name' style='width: 300px;'>";
$sql = mysql_query("select * from master_add where tipe = 'customer'");
while ($r = mysql_fetch_array($sql))
{
    echo "<option value='$r[desc1]'>$r[desc2]</option>";
}
echo "</select>";
echo "</td>";
</code>```

答:
You can try silviomoreto/bootstrap-select to build your searchable dropdown list.

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>

<select class="selectpicker" data-live-search="true">
  <option>Mustard</option>
  <option>Ketchup</option>
  <option>Barbecue</option>
</select>
</code>```

JSFiddle Demo

See https://silviomoreto.github.io/bootstrap-select/examples/#live-search

Title: Searchable dropdown list

Body:
I want to make a search input box above the dropdown list in my site, mind to tell me how to make a searchable dropdown list ?

echo "";
echo "<select name='customer_name' style='width: 300px;'>";
$sql = mysql_query("select * from master_add where tipe = 'customer'");
while ($r = mysql_fetch_array($sql))
{
    echo "<option value='$r[desc1]'>$r[desc2]</option>";
}
echo "</select>";
echo "	";

Body:
You can try silviomoreto/bootstrap-select to build your searchable dropdown list.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>

<select class="selectpicker" data-live-search="true">
  <option>Mustard</option>
  <option>Ketchup</option>
  <option>Barbecue</option>
</select>

JSFiddle Demo

See https://silviomoreto.github.io/bootstrap-select/examples/#live-search


问:
Best way of CSS override?
Could you please provide the best way of override and what is the advantages of this. For example.

1. example :

```<code>.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}

.custom .ex1{
  font-size: 14px;
}
</code>```

2. example

```<code>.custom .ex1{
  font-size: 14px;
}
.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}
</code>```

Which is one best way overriding, example 1 or example 2. if any advantages?

答:
on css more you define an element more powerfull its css decleration for example in the exapmle you gave it is not the order gives override. It is .custom class, which defines .ex1 more specifically since order does not change anything in this case you can do both. But personally I like starting from general classes and continue to specifics. I dont know but it feels more natural. therefore I would use following. However as I said there are no functional difference in this case.

```<code>.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}

.custom .ex1{
  font-size: 14px;
}
</code>```

Title: Best way of CSS override?

Body:
Could you please provide the best way of override and what is the advantages of this. For example.

1. example :

.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}

.custom .ex1{
  font-size: 14px;
}

2. example

.custom .ex1{
  font-size: 14px;
}
.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}

Which is one best way overriding, example 1 or example 2. if any advantages?

Body:
on css more you define an element more powerfull its css decleration for example in the exapmle you gave it is not the order gives override. It is .custom class, which defines .ex1 more specifically since order does not change anything in this case you can do both. But personally I like starting from general classes and continue to specifics. I dont know but it feels more natural. therefore I would use following. However as I said there are no functional difference in this case.

.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}

.custom .ex1{
  font-size: 14px;
}


问:
What is the runtime complexity of a switch statement?
I'd like to know what the worst-case runtime complexity of a switch statement is, assuming you have n cases.

I always assumed it was O(n). I don't know if compilers do anything clever, though. If the answer is implementation-specific, I'd like to know for the following languages:

Java

C/C++

C#

PHP

Javascript

答:
It is at worst O(n). Sometimes (and this is language and compiler dependent), it translates to a jump table lookup (for "nice" switches that don't have too large a case range). Then that is O(1).

If the compiler wants to be funky, I can think of ways that the complexity can be implemented to be anything in between (e.g. perform binary search on the cases, for logn). But in practice, you're going to get eiher linear time or constant time.


问:
How to open and close the same div in JQuery
Hey guys how can I close a div which is opend with show().
For Example:
I have a "div a" which includes a "div b" which is hidden at first and when I click on "div a" the "div b" (children) should show up. When I click on an [x] inside the "div b" exactly this div should close.

In my minimal example of this I already find out how to open the right div which is the children of the parent div. But how can I close the parent again? In my example I only can close the "hide Button" but not the whole div "Tag-Cloud". I also tried to implement the parent() function and the parentUntil() function but it failed.

Can you guys help me?

$(document).ready(function() {

  $(".film").click(function() {
    $(this).children(".tag-cloud").show(function() {
      $(".fa-close").click(function() {
        $(this).parent().hide();
      });
    });
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tag-cloud {
  display: none;
}</code>```

Open the div here

tag1

tag2

      [Close Button]

```

答:
simply show the div $(".tag-cloud") on $(".film-title").click and hide on   $(".fa-close").click

$(document).ready(function() {

  $(".film-title").click(function() {
    $(".tag-cloud").show();
  });

  $(".fa-close").click(function() {
    $(".tag-cloud").hide();
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.tag-cloud {
  display: none;
}</code>```

Open the div here

tag1

tag2

      [Close Button]

```

Body:
Hey guys how can I close a div which is opend with show().
For Example:
I have a "div a" which includes a "div b" which is hidden at first and when I click on "div a" the "div b" (children) should show up. When I click on an [x] inside the "div b" exactly this div should close.

In my minimal example of this I already find out how to open the right div which is the children of the parent div. But how can I close the parent again? In my example I only can close the "hide Button" but not the whole div "Tag-Cloud". I also tried to implement the parent() function and the parentUntil() function but it failed.

Can you guys help me?

$(document).ready(function() {

  $(".film").click(function() {
    $(this).children(".tag-cloud").show(function() {
      $(".fa-close").click(function() {
        $(this).parent().hide();
      });
    });
  });

});

.tag-cloud {
  display: none;
}

Open the div here

tag1

tag2

      [Close Button]

Body:
simply show the div $(".tag-cloud") on $(".film-title").click and hide on   $(".fa-close").click

$(document).ready(function() {

  $(".film-title").click(function() {
    $(".tag-cloud").show();
  });

  $(".fa-close").click(function() {
    $(".tag-cloud").hide();
  });

});

.tag-cloud {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="film">

  <h4 class="film-title">Open the div here</h4>

  <div class="tag-cloud">
    <!-- tag-cloud -->
    <i class="fa fa-2x fa-close"></i>
    <ul>
      <li><a href="">tag1</a></li>
      <li><a href="">tag2</a></li>
    </ul>
    <div class="exit-tags">
      <i class="fa fa-2x fa-close">[Close Button]</i>
      <!-- The close button for the tag-cloud -->
    </div>
  </div>

</div>


问:
Issue with nnstart in matlab tool
I'm doing a character recognition project using feature extraction and nueral network. I use matlab. I created a feature vector with 30 features.I have labeled the numbers as well using another variable. Using nntool I get the correct result. But when I use nnstart to generate the code I don't get a drop down list to select for the target. Input is ok. The input is with 48 columns with 30 rows each. ( 30 are the features and I have 48 samples) The target is 48 columns with 1 row( There I labeled the numbers) Can someone help me with this issue.
Thanks in advance.The scree shot is here </p>

答:
You can also use command line codes instead of GUI. Here, code is given. you can manually assign inputs and outputs.</p>

```<code>% cancerInputs - input data.`
% cancerTargets - target data.
inputs =cancerInputs;
targets = cancerTargets;
% Create a Pattern Recognition Network
hiddenLayerSize = 30;
net = patternnet(hiddenLayerSize);
% Set up Division of Da
net.divideParam.trainRatio = 70/100;
net.divideParam.valRatio = 15/100;
net.divideParam.testRatio = 15/100;
% Train the Network
[net,tr] = train(net,inputs,targets);
% Test the Network
outputs = net(inputs);
</code>```

Title: Issue with nnstart in matlab tool

Body:
You can also use command line codes instead of GUI. Here, code is given. you can manually assign inputs and outputs.

% cancerInputs - input data.`
% cancerTargets - target data.
inputs =cancerInputs;
targets = cancerTargets;
% Create a Pattern Recognition Network
hiddenLayerSize = 30;
net = patternnet(hiddenLayerSize);
% Set up Division of Da
net.divideParam.trainRatio = 70/100;
net.divideParam.valRatio = 15/100;
net.divideParam.testRatio = 15/100;
% Train the Network
[net,tr] = train(net,inputs,targets);
% Test the Network
outputs = net(inputs);


问:
Delete php is not working
My database does not have unique id.

```<code>include('php_connect.php');

// check if the 'Userid' variable is set in URL, and check that it is valid
if (isset($_GET['ServerName']))
{
// get id value
    $userid = $_GET['ServerName'];
// delete the entry
    $strSQL = "DELETE from server WHERE ServerName = (?)";
    $params = array($userid);
    $stmt = sqlsrv_query( $conn, $strSQL, $params);
    if( $stmt ){
        sqlsrv_commit( $conn );
        echo "Record Deleted";
        }
    else
    {
        echo $params[0];
        echo "statement error.<br />";
        die( print_r( sqlsrv_errors(), true));
    }
    sqlsrv_close( $conn );
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
    echo "WTH Something happened to the ServerName!.<br />";
    echo "Better start over.<br />";
}

?>
</code>```

and the results is this:

```<code>WTH Something happened to the ServerName!
Better start over
</code>```

答:
As per your comment on code you should check userid insted of servername :

check if the 'Userid' variable is set in URL, and check that it is valid

```<code>if (isset($_GET['ServerName']))
{
</code>```

To

```<code>if (isset($_GET['Userid']))
{
</code>```

Title: Delete php is not working

Body:
My database does not have unique id.

include('php_connect.php');

// check if the 'Userid' variable is set in URL, and check that it is valid
if (isset($_GET['ServerName']))
{
// get id value
    $userid = $_GET['ServerName'];
// delete the entry
    $strSQL = "DELETE from server WHERE ServerName = (?)";
    $params = array($userid);
    $stmt = sqlsrv_query( $conn, $strSQL, $params);
    if( $stmt ){
        sqlsrv_commit( $conn );
        echo "Record Deleted";
        }
    else
    {
        echo $params[0];
        echo "statement error.
";
        die( print_r( sqlsrv_errors(), true));
    }
    sqlsrv_close( $conn );
}
else
// if id isn't set, or isn't valid, redirect back to view page
{
    echo "WTH Something happened to the ServerName!.
";
    echo "Better start over.
";
}

?>

and the results is this:

WTH Something happened to the ServerName!
Better start over

Body:
As per your comment on code you should check userid insted of servername :

check if the 'Userid' variable is set in URL, and check that it is valid

if (isset($_GET['ServerName']))
{

To

if (isset($_GET['Userid']))
{