问:
batch not_if guard says "action run" rather than "skipped"
I have a PS script in recipe that causes chef-run to fail if a certain Security Policy is enabled (basically this problem).

So I have added a not_if guard

```<code>  powershell_script 'scheduled-tasks' do
    guard_interpreter :powershell_script
    cwd 'C:\Temp'
    code <<-EOH
      schtasks.exe /create ...
      schtasks.exe /create ...
    EOH
    not_if "(get-itemproperty 'HKLM:\\System\\CurrentControlSet\\Control\\Lsa').DisableDomainCreds -eq '1'"
  end
</code>```

I am using Test-Kitchin, VirtualBox and Windows VMs. Running the powershell command 'getitemproperty...' returns True meaning it is Enabled and thus I do not want the script run and expect Chef to say 'skipped due to not_if'.

However, in the terminal output it says "action run".

The chef run doesn't fail so the script cannot have run, but why does it not say "skipped"?

Regards

答:
This is because you are using double quotes for your not_if statement. Try using curly braces or single quotes instead. Beware of the Powershell logical operator that is using single quotes likewise:</p>

```<code>not_if '(Get-ItemProperty HKLM:\\System\\CurrentControlSet\\Control\\Lsa).DisableDomainCreds -eq "1"'
</code>```

Body:
I have a PS script in recipe that causes chef-run to fail if a certain Security Policy is enabled (basically this problem).

So I have added a not_if guard

  powershell_script 'scheduled-tasks' do
    guard_interpreter :powershell_script
    cwd 'C:\Temp'
    code <<-EOH
      schtasks.exe /create ...
      schtasks.exe /create ...
    EOH
    not_if "(get-itemproperty 'HKLM:\\System\\CurrentControlSet\\Control\\Lsa').DisableDomainCreds -eq '1'"
  end

I am using Test-Kitchin, VirtualBox and Windows VMs. Running the powershell command 'getitemproperty...' returns True meaning it is Enabled and thus I do not want the script run and expect Chef to say 'skipped due to not_if'.

However, in the terminal output it says "action run".

The chef run doesn't fail so the script cannot have run, but why does it not say "skipped"?

Regards

Body:
This is because you are using double quotes for your not_if statement. Try using curly braces or single quotes instead. Beware of the Powershell logical operator that is using single quotes likewise:

not_if '(Get-ItemProperty HKLM:\\System\\CurrentControlSet\\Control\\Lsa).DisableDomainCreds -eq "1"'


来源: stackexchange

问:
Use map() for functions that does not return a value
I have a quick question:

If I have a function:

```<code>a = [1,2,3,4,5,6,7]
def f(x):
    return (x**2)
result = list(map(f, a))
print(result)
>>> [1, 4, 9, 16, 25, 36, 49]
</code>```

but if I:

```<code>result = []
a = [1,2,3,4,5,6,7]
def f(x):
    result.append(x**2)
map(f, a)
print(result)
>>> []
</code>```

it won't work.

However, it will work if I write the function this way:

```<code>result = []
a = [1,2,3,4,5,6,7]
def f(x):
    result.append(x**2)
for i in a:
    f(i)
print(result)
>>> [1, 4, 9, 16, 25, 36, 49]
</code>```

even if I include a return value for it:

```<code>result = []
a = [1,2,3,4,5,6,7]
def f(x):
    result.append(x**2)
    return x**2
map(f, a)
print(result)           # >>> []
print(list(map(f,a)))   # >>> [1,2,3,4,5,6,7]
</code>```

Should I understand it as the map() must be applied on a function with a return value and return value only.

ContentLicense: CC BY-SA 3.0

Body:
I have a quick question:

If I have a function:

a = [1,2,3,4,5,6,7]
def f(x):
    return (x**2)
result = list(map(f, a))
print(result)
>>> [1, 4, 9, 16, 25, 36, 49]

but if I:

result = []
a = [1,2,3,4,5,6,7]
def f(x):
    result.append(x**2)
map(f, a)
print(result)
>>> []

it won't work.

However, it will work if I write the function this way:

result = []
a = [1,2,3,4,5,6,7]
def f(x):
    result.append(x**2)
for i in a:
    f(i)
print(result)
>>> [1, 4, 9, 16, 25, 36, 49]

even if I include a return value for it:

result = []
a = [1,2,3,4,5,6,7]
def f(x):
    result.append(x**2)
    return x**2
map(f, a)
print(result)           # >>> []
print(list(map(f,a)))   # >>> [1,2,3,4,5,6,7]

Should I understand it as the map() must be applied on a function with a return value and return value only.

Body:
With Python 2 it will work...

I tried all of them and this is my result set:

[1, 4, 9, 16, 25, 36, 49]
[1, 4, 9, 16, 25, 36, 49]
[1, 4, 9, 16, 25, 36, 49]
[1, 4, 9, 16, 25, 36, 49]
[1, 4, 9, 16, 25, 36, 49]


问:
PHP Regular expression tag matching
Been beating my head against a wall trying to get this to work - help from any regex gurus would be greatly appreciated!

The text that has to be matched

```<code>[template option="whatever"]

<p>any amount of html would go here</p>

[/template]
</code>```

I need to pull the 'option' value (i.e. 'whatever') and the html between the template tags.

So far I have:

```<code>> /\[template\s*option=["\']([^"\']+)["\']\]((?!\[\/template\]))/
</code>```

Which gets me everything except the html between the template tags.

Any ideas?

Thanks, Chris

答:
The assertion ?! method is unneeded. Just match with .*? to get the minimum giblets.

```<code>/\[template\s*option=\pP([\h\w]+)\pP\]  (.*?)  [\/template\]/x
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP Regular expression tag matching

Body:
Been beating my head against a wall trying to get this to work - help from any regex gurus would be greatly appreciated!

The text that has to be matched

[template option="whatever"]

any amount of html would go here

[/template]

I need to pull the 'option' value (i.e. 'whatever') and the html between the template tags.

So far I have:

> /\[template\s*option=["\']([^"\']+)["\']\]((?!\[\/template\]))/

Which gets me everything except the html between the template tags.

Any ideas?

Thanks, Chris

Body:
The assertion ?! method is unneeded. Just match with .*? to get the minimum giblets.

/\[template\s*option=\pP([\h\w]+)\pP\]  (.*?)  [\/template\]/x


问:
JavaFX: Formatting a TabPane with Vertical Tabs and Horizontal Tab Labels
I'm attempting to format a TabPane, where the Tabs are vertical on the left-side of the TabPane.  The tab text needs to be horizontal.
The problem occurs when the text is rotated to the horizontal position.  It appears that the tab is auto-sized for vertical text; THEN, it becomes horizontal without resizing the tab.  The result is varying heights of tabs (depending on the length of the text label BEFORE rotating).
I've tried 3 different solutions that I've found in other questions, but none work. Is there a working solution? (Java 1.8u144)</p>

```<code>----- Attempt #1 - CSS and Text Attribute -----

CSS

.tab .tab-label {
    -fx-rotate: 90;  /*PROBLEM: it sizes height using vertical text before rotating, messes up H. */
}

FXML

<TabPane side="LEFT" rotateGraphic="true" >
    <tabs>
        <Tab fx:id="tab1" closable="false" text="Select">
            <Label text="Select"/>
        </Tab>
        <Tab fx:id="tab2" closable="false" text="Log">
            <Label text="Log"/>
        </Tab>
        <Tab fx:id="tab3" closable="false" text="Schedules">
            <Label text="Schedules"/>
        </Tab>
    </tabs>
</TabPane>

----- Attempt #2 - Java replace tab-label with Graphic -----

CSS

.tab .tab-label {
    -fx-rotate: 90;  /*PROBLEM: it sizes height using vertical text before rotating, messes up H. */
}

Java Controller

@FXML private Tab tab1;
@FXML private Tab tab2;
@FXML private Tab tab3;

@Override
public void initialize(URL url, ResourceBundle rb) {
    tab1.setGraphic(new Label("Select"));
    tab2.setGraphic(new Label("Log"));
    tab3.setGraphic(new Label("Schedules"));
}

FXML

<TabPane side="LEFT" rotateGraphic="true" >
    <tabs>
        <Tab fx:id="tab1" closable="false" >
            <Label text="Select" />
        </Tab>
        <Tab fx:id="tab2" closable="false">
            <Label text="Log" />
        </Tab>
        <Tab fx:id="tab3" closable="false">
            <Label text="Schedules" />
        </Tab>
    </tabs>
</TabPane>

----- Attempt #3 - FXML replace tab-label with Graphic -----

FXML

<TabPane side="LEFT" rotateGraphic="true" >
    <tabs>
        <Tab fx:id="tab1" closable="false" >
            <graphic>
                <Group >
                    <Label text="Select" rotate="90"/>
                </Group>
            </graphic>
            <Label text="Select" />
        </Tab>
        ...
</code>```

答:
I'll answer my own question since I found a solution, and to provide an example.
Using the FXML approach from the question...

```<code><TabPane side="LEFT" rotateGraphic="true" >
<tabs>
    <Tab fx:id="tab1" closable="false" >
        <graphic>
            <Group >
                <Label text="Select" rotate="90"/>
            </Group>
        </graphic>
        <Label text="Select" />
    </Tab>
    ...
</code>```

The additional step needed for the solution was to add CSS ....

```<code>.tab-pane .tab-header-area .tab {
-fx-pref-height: 150;
-fx-pref-width: 50;}
</code>```

...which re-sizes the tab label to fit with the 90 degree tab rotate.

Body:
I'm attempting to format a TabPane, where the Tabs are vertical on the left-side of the TabPane.  The tab text needs to be horizontal.
The problem occurs when the text is rotated to the horizontal position.  It appears that the tab is auto-sized for vertical text; THEN, it becomes horizontal without resizing the tab.  The result is varying heights of tabs (depending on the length of the text label BEFORE rotating).
I've tried 3 different solutions that I've found in other questions, but none work. Is there a working solution? (Java 1.8u144)

----- Attempt #1 - CSS and Text Attribute -----

CSS

.tab .tab-label {
    -fx-rotate: 90;  /*PROBLEM: it sizes height using vertical text before rotating, messes up H. */
}

FXML

<TabPane side="LEFT" rotateGraphic="true" >
    <tabs>
        <Tab fx:id="tab1" closable="false" text="Select">

        </Tab>
        <Tab fx:id="tab2" closable="false" text="Log">

        </Tab>
        <Tab fx:id="tab3" closable="false" text="Schedules">

        </Tab>
    </tabs>
</TabPane>

----- Attempt #2 - Java replace tab-label with Graphic -----

CSS

.tab .tab-label {
    -fx-rotate: 90;  /*PROBLEM: it sizes height using vertical text before rotating, messes up H. */
}

Java Controller

@FXML private Tab tab1;
@FXML private Tab tab2;
@FXML private Tab tab3;

@Override
public void initialize(URL url, ResourceBundle rb) {
    tab1.setGraphic(new Label("Select"));
    tab2.setGraphic(new Label("Log"));
    tab3.setGraphic(new Label("Schedules"));
}

FXML

<TabPane side="LEFT" rotateGraphic="true" >
    <tabs>
        <Tab fx:id="tab1" closable="false" >

        </Tab>
        <Tab fx:id="tab2" closable="false">

        </Tab>
        <Tab fx:id="tab3" closable="false">

        </Tab>
    </tabs>
</TabPane>

----- Attempt #3 - FXML replace tab-label with Graphic -----

FXML

<TabPane side="LEFT" rotateGraphic="true" >
    <tabs>
        <Tab fx:id="tab1" closable="false" >
            <graphic>
                <Group >

                </Group>
            </graphic>

        </Tab>
        ...

Body:
I'll answer my own question since I found a solution, and to provide an example.
Using the FXML approach from the question...

<TabPane side="LEFT" rotateGraphic="true" >
<tabs>
    <Tab fx:id="tab1" closable="false" >
        <graphic>
            <Group >
                <Label text="Select" rotate="90"/>
            </Group>
        </graphic>
        <Label text="Select" />
    </Tab>
    ...

The additional step needed for the solution was to add CSS ....

.tab-pane .tab-header-area .tab {
-fx-pref-height: 150;
-fx-pref-width: 50;}

...which re-sizes the tab label to fit with the 90 degree tab rotate.


问:
Read strings in C from txt file
I'm trying to read some strings from a txt file.
Each line has a 5 digit number, a full name that occupies 51 characters (including spaces), 2 city names, each one occupyng 11 characters including spaces, and one number. Example:

```<code>12345António Manuel Silva Mendes                        Frankfurt  Varsovia    1
</code>```

I can now scan the first 2 strings, but I can't scan the city names, nor the last number.

Here's the struct:

```<code>typedef struct bilhete{

    int BI;
    char nome[51];
    char partida[11];
    char chegada[11];
    int data[2];

}BILHETE;
</code>```

here's the way I'm reading the file

```<code>while(!feof(fp)){

        fscanf(fp,"%d%51[^\n]s%11c%11c%d\n", &bilhete.BI, bilhete.nome, bilhete.partida, bilhete.chegada, &bilhete.data);
</code>```

What am I doing wrong? when I print the city names, nothing appears!

答:
Since you have fixed columns, I would consider just reading in the data and doing my own scanning with something like:

```<code>char linein[200];
char *p;

while (fgets(linein, sizeof(linein), fp))
{
    char biBuf[10]={0};
    char dataBuf[10]={0};

    p=linein;
    memcpy(biBuf,linein,5);
    bilhete.BI=atoi(biBuf);
    p+=5;
    memcpy(bilhete.nome,p,51);
    p+=51;
    memcpy(bilhete.partida,p,11);
    p+=11;
    memcpy(bilhete.chegada,p, 11);
    p+=11;
    memcpy(dataBuf,p,2);
    bilhete.data[0]=atoi(dataBuf);
    printf("%.51s %d\n",bilhete.nome, bilhete.data[0]);
}
</code>```

I am not sure what you wanted to do with the data variable but this will give you an integer. Observe, the biBuf and dataBuf variables are allocated in the loop so they get set to zeros each time.

Title: Read strings in C from txt file

Body:
I'm trying to read some strings from a txt file.
Each line has a 5 digit number, a full name that occupies 51 characters (including spaces), 2 city names, each one occupyng 11 characters including spaces, and one number. Example:

12345António Manuel Silva Mendes                        Frankfurt  Varsovia    1

I can now scan the first 2 strings, but I can't scan the city names, nor the last number.

Here's the struct:

typedef struct bilhete{

    int BI;
    char nome[51];
    char partida[11];
    char chegada[11];
    int data[2];

}BILHETE;

here's the way I'm reading the file

while(!feof(fp)){

        fscanf(fp,"%d%51[^\n]s%11c%11c%d\n", &bilhete.BI, bilhete.nome, bilhete.partida, bilhete.chegada, &bilhete.data);

What am I doing wrong? when I print the city names, nothing appears!

Body:
Since you have fixed columns, I would consider just reading in the data and doing my own scanning with something like:

char linein[200];
char *p;

while (fgets(linein, sizeof(linein), fp))
{
    char biBuf[10]={0};
    char dataBuf[10]={0};

    p=linein;
    memcpy(biBuf,linein,5);
    bilhete.BI=atoi(biBuf);
    p+=5;
    memcpy(bilhete.nome,p,51);
    p+=51;
    memcpy(bilhete.partida,p,11);
    p+=11;
    memcpy(bilhete.chegada,p, 11);
    p+=11;
    memcpy(dataBuf,p,2);
    bilhete.data[0]=atoi(dataBuf);
    printf("%.51s %d\n",bilhete.nome, bilhete.data[0]);
}

I am not sure what you wanted to do with the data variable but this will give you an integer. Observe, the biBuf and dataBuf variables are allocated in the loop so they get set to zeros each time.


问:
Why is git not working in Visual Studio Code?
I have installed husky in my project. Then I ran the precommit command. Now, when I run the git command, it is not working and it's instead asking me how do you want to open the file. So, I removed husky using npm prune and then removed the hooks folder from /.git of the project directory, but still didn't help. I am using Windows 10.

答: After reading the other posts with their answers of deleting and reinstalling Git and Github, I discovered that I had the Atom GitHub package installed from prior experiments. I deleted Atom and restarted VSCode and it now works with the Git repo.</p>

ContentLicense: CC BY-SA 4.0


问:
Update one value in parent activity from a child activity while retaining all remaining original values on the parent
I have an input form where I collect 4 values in a text field that are tied to the FirstActivity. The user enters 4 values and clicks a button which will present the user with 2 options that are tied to SecondActivity.

Upon clicking one of the options in SecondActivity, he is presented with a 3rd screen with a search option. Upon searching, he is presented with search results as a list.

When the user clicks on one of the results, I want to update one field in FirstActivity while retaining all the values that the user selected initially. I used the Intent flags to retain the state and it works except for one problem - I dont see the updated value in the first screen.

PROBLEM: While this code helps me retain the initial state in FirstActivity, it doesn't update the CopiesValue when I return to FirstActivity. I want the copies value to be updated with the value that was selected in ThirdActivity. All original values on FirstActivity are retained though...

I want the updated value from ThirdActivity to reflect on the first screen once a value is selected on the third screen.

Here is my code within the onClickListener in ThirdActivity:

```<code>lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = lv.getItemAtPosition(position);
        String str = (String) o;
        Globals g = Globals.getInstance();
        ((FirstActivity)g.getFirstContext()).getSettingHolder().setSelectedCopiesValue(5);
        Intent intent = new Intent(g.getFirstContext(), FirstActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivityForResult(intent, 1);
        finish();
    }
});
</code>```

Here is my AndroidManifest.xml entry:

```<code><activity
        android:name=".activity.FirstActivity"
        android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|layoutDirection|fontScale"
        android:label="@string/app_name"
        android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".activity.SecondActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.FirstActivity" />
    </activity>
    <activity android:name=".activity.ThirdActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.FirstActivity" />
    </activity>
</code>```

答:
In addition to the answer above from @Wizard, I had to do a few more changes to get my app working.I can now see the updated value from third activity on the first activity screen, while all other initial values are retained.

In the Broadcast.onReceive method, I had to call the intent on the same activity (FirstActivity).

I am not sure if this is a good practice to call an intent on itself while in the same activity. Will this cause any performance issues ?Can anyone please comment on the best practices here ??

In FirstActivity

```<code>private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String selectedCopies = intent.getStringExtra("selectedCopies");
        Intent intent1 = new Intent(getApplicationContext(), FirstActivity.class);
        intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent1);
    }
};
</code>```

In ThirdActivity (on click of list item)

```<code>    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Object o = lv.getItemAtPosition(position);
            String selectedCopies = (String) o; //As you are using Default String Adapter

            Intent intent = new Intent("custom-event-name");
            intent.putExtra("selectedCopies", selectedCopies);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
            LocalBroadcastManager.getInstance(g.getMainContext()).sendBroadcast(intent);
        }
    });
</code>```

Body:
I have an input form where I collect 4 values in a text field that are tied to the FirstActivity. The user enters 4 values and clicks a button which will present the user with 2 options that are tied to SecondActivity.

Upon clicking one of the options in SecondActivity, he is presented with a 3rd screen with a search option. Upon searching, he is presented with search results as a list.

When the user clicks on one of the results, I want to update one field in FirstActivity while retaining all the values that the user selected initially. I used the Intent flags to retain the state and it works except for one problem - I dont see the updated value in the first screen.

PROBLEM: While this code helps me retain the initial state in FirstActivity, it doesn't update the CopiesValue when I return to FirstActivity. I want the copies value to be updated with the value that was selected in ThirdActivity. All original values on FirstActivity are retained though...

I want the updated value from ThirdActivity to reflect on the first screen once a value is selected on the third screen.

Here is my code within the onClickListener in ThirdActivity:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = lv.getItemAtPosition(position);
        String str = (String) o;
        Globals g = Globals.getInstance();
        ((FirstActivity)g.getFirstContext()).getSettingHolder().setSelectedCopiesValue(5);
        Intent intent = new Intent(g.getFirstContext(), FirstActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivityForResult(intent, 1);
        finish();
    }
});

Here is my AndroidManifest.xml entry:

<activity
        android:name=".activity.FirstActivity"
        android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|layoutDirection|fontScale"
        android:label="@string/app_name"
        android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".activity.SecondActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.FirstActivity" />
    </activity>
    <activity android:name=".activity.ThirdActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".activity.FirstActivity" />
    </activity>

Body:
In addition to the answer above from @Wizard, I had to do a few more changes to get my app working.I can now see the updated value from third activity on the first activity screen, while all other initial values are retained.

In the Broadcast.onReceive method, I had to call the intent on the same activity (FirstActivity).

I am not sure if this is a good practice to call an intent on itself while in the same activity. Will this cause any performance issues ?Can anyone please comment on the best practices here ??

In FirstActivity

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String selectedCopies = intent.getStringExtra("selectedCopies");
        Intent intent1 = new Intent(getApplicationContext(), FirstActivity.class);
        intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent1);
    }
};

In ThirdActivity (on click of list item)

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Object o = lv.getItemAtPosition(position);
            String selectedCopies = (String) o; //As you are using Default String Adapter

            Intent intent = new Intent("custom-event-name");
            intent.putExtra("selectedCopies", selectedCopies);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
            LocalBroadcastManager.getInstance(g.getMainContext()).sendBroadcast(intent);
        }
    });


问:
mysql only returning results with numeric values

I am creating a random alphanumeric for a public access category that can only be found by using this alphanumeric post id in the url link. Weird thing is that I am only getting results from the query when numeric values are used.

```<code> $sql = "SELECT *
 FROM $a
 WHERE access_key = $category_id
</code>```

I get an "unknown column" error containing the alphnumeric data as the column, which I find a little strange. I think this maybe something simple like escaping that needs to be done, but I am not really sure.

Any suggestions would be appriciated. Thanks in advance.

答:
This is the proper way to do it, and also fix the error you are seeing.

MYSQLI:

```<code>// assuming $a is already safe
$stmt = $mysqli->prepare('SELECT * FROM '. $a .' WHERE access_key = ?');
$stmt->bind_param('s', $category_id);
$stmt->execute();
</code>```

PDO:

```<code>// assuming $a is already safe
$stmt = $pdo->prepare('SELECT * FROM '. $a .' WHERE access_key = :category_id');
$stmt->execute(array(':category_id'=>$category_id));
</code>```

As for whitelisting... this is a basic example (do it BEFORE any sql actions):

```<code>$safe = array('categorytable','usertable');
if (!in_array($a,$safe)) { return; exit; die(); /*lol*/ }
</code>```

ORRRRR.... if you just want toquickly fix your current sql line of code (but please do look into doing prepared in the future):

```<code>$sql = "SELECT *
        FROM $a
        WHERE access_key = '$category_id'";
</code>```

Body:
I am creating a random alphanumeric for a public access category that can only be found by using this alphanumeric post id in the url link. Weird thing is that I am only getting results from the query when numeric values are used.

 $sql = "SELECT *
 FROM $a
 WHERE access_key = $category_id

I get an "unknown column" error containing the alphnumeric data as the column, which I find a little strange. I think this maybe something simple like escaping that needs to be done, but I am not really sure.

Any suggestions would be appriciated. Thanks in advance.

Body:
This is the proper way to do it, and also fix the error you are seeing.

MYSQLI:

// assuming $a is already safe
$stmt = $mysqli->prepare('SELECT * FROM '. $a .' WHERE access_key = ?');
$stmt->bind_param('s', $category_id);
$stmt->execute();

PDO:

// assuming $a is already safe
$stmt = $pdo->prepare('SELECT * FROM '. $a .' WHERE access_key = :category_id');
$stmt->execute(array(':category_id'=>$category_id));

As for whitelisting... this is a basic example (do it BEFORE any sql actions):

$safe = array('categorytable','usertable');
if (!in_array($a,$safe)) { return; exit; die(); /*lol*/ }

ORRRRR.... if you just want toquickly fix your current sql line of code (but please do look into doing prepared in the future):

$sql = "SELECT *
        FROM $a
        WHERE access_key = '$category_id'";


答:
What you are seeing here is the effect of lazy-evaluation. Python 3 made most functions like this (map, filter, zip etc) work lazily where they used to work eagerly in Python 2, that is, instead of immediately returning and materializing a data-structure when you call map(f, some_iterable), instead, map returns a map-object, which can then be iterated over to either materialize a data structure or work with the elements one-by-one (letting you work in a memory-efficient way).

```<code>>>> result = []
>>> m = map(lambda x: result.append(x), range(10))
>>> m
<map object at 0x10a0b7278>
>>> result
[]
>>> next(m)
>>> result
[0]
>>> next(m)
>>> result
[0, 1]
>>> list(m)
[None, None, None, None, None, None, None, None]
>>> result
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

However!

You should not be using map or filter or list-comprehensions for their side-effects. These are all functional constructs, and you should avoid mutating state when using them. It is simply bad style, and also, as you noticed when I called list on my map object, it creates and immediately discards a useless list of None (because functions that don't return anything implicitely return None).

So, to answer your question, yes you can use "map() for functions that does not return a value" but you shouldn't. Just use a for-loop.

Title: Use map() for functions that does not return a value

Body:
What you are seeing here is the effect of lazy-evaluation. Python 3 made most functions like this (map, filter, zip etc) work lazily where they used to work eagerly in Python 2, that is, instead of immediately returning and materializing a data-structure when you call map(f, some_iterable), instead, map returns a map-object, which can then be iterated over to either materialize a data structure or work with the elements one-by-one (letting you work in a memory-efficient way).

>>> result = []
>>> m = map(lambda x: result.append(x), range(10))
>>> m
<map object at 0x10a0b7278>
>>> result
[]
>>> next(m)
>>> result
[0]
>>> next(m)
>>> result
[0, 1]
>>> list(m)
[None, None, None, None, None, None, None, None]
>>> result
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

However!

You should not be using map or filter or list-comprehensions for their side-effects. These are all functional constructs, and you should avoid mutating state when using them. It is simply bad style, and also, as you noticed when I called list on my map object, it creates and immediately discards a useless list of None (because functions that don't return anything implicitely return None).

So, to answer your question, yes you can use "map() for functions that does not return a value" but you shouldn't. Just use a for-loop.


问:
IIS looking bootstrap fonts under wrong location
I have ASP.NET MVC 5 application. The application has fonts folder at its root location. (It was created by default by VS 2017 when you create new application)

When i run application locally in visual studio everything works fine. But when i deploy it to IIS and browse any page where glyphicons been used, i see error below (in Fiddler)

I don't know why the path is changed? instead of looking font under /fonts folder it is looking under /Content/fonts folder.

答:
Keeping in mind that paths in a CSS file are relative, using the built-it bundling mechanism could be causing your paths to resolve to an incorrect location.  In order to resolve this issue, you can pass an additional parameter to each of your CSS files in your bundle that will rewrite the paths in the compressed CSS so that it still ultimately points to the correct paths for your files such as images and fonts.

Example (from one of my current projects)

```<code>var siteCss = new StyleBundle("~/Css/Site")
           .Include("~/Content/PickDateThemes/default.css", new CssRewriteUrlTransform())
           .Include("~/Content/PickDateThemes/default.date.css", new CssRewriteUrlTransform())
           .Include("~/Content/PickDateThemes/default.time.css", new CssRewriteUrlTransform())
           .Include("~/Content/app.css", new CssRewriteUrlTransform())
           .Include("~/Content/DataTables/css/dataTables.foundation.css", new CssRewriteUrlTransform());
</code>```

Body:
Keeping in mind that paths in a CSS file are relative, using the built-it bundling mechanism could be causing your paths to resolve to an incorrect location.  In order to resolve this issue, you can pass an additional parameter to each of your CSS files in your bundle that will rewrite the paths in the compressed CSS so that it still ultimately points to the correct paths for your files such as images and fonts.

Example (from one of my current projects)

var siteCss = new StyleBundle("~/Css/Site")
           .Include("~/Content/PickDateThemes/default.css", new CssRewriteUrlTransform())
           .Include("~/Content/PickDateThemes/default.date.css", new CssRewriteUrlTransform())
           .Include("~/Content/PickDateThemes/default.time.css", new CssRewriteUrlTransform())
           .Include("~/Content/app.css", new CssRewriteUrlTransform())
           .Include("~/Content/DataTables/css/dataTables.foundation.css", new CssRewriteUrlTransform());


问:
Storing more users in a ranking table
I want to store more users on my rankings table, and display their first name and last name on the table. But every-time a new user registers, its replaces the first user on the table. How do I fix this? I've created a JSFiddle Here </p>

```<code>/* Register */
function storeUserDetail() {
    var fNameInput = document.getElementById("firstNameInput").value;
    var lNameInput = document.getElementById("lastNameInput").value;
    var uNameInput = document.getElementById("userNameInput").value;
    var pWordInput = document.getElementById("passWordInput").value;
    var storeDetails = {};
    storeDetails.FirstName = fNameInput
    storeDetails.LastName = lNameInput
    storeDetails.Username = uNameInput
    storeDetails.Password = pWordInput
    localStorage[storeDetails.Username] = JSON.stringify(storeDetails);
}

/* Log In */
function loginUser() {
    var Username = document.getElementById("uNameInput").value;
    var Password = document.getElementById("pWordInput").value;
    var storeDetails = JSON.parse(localStorage[Username]);
    storeDetails.Username = document.getElementById("uNameInput").value;
    storeDetails.Password = document.getElementById("pWordInput").value;
    localStorage.loggedInUser = Username;
}

/* Rankings Table */
function displayTable() {
    var getData = JSON.parse(localStorage[localStorage.loggedInUser]);
    var highScoreTable = "<tr><th>First Name</th><th>Last Name</th></tr>\n";
    for(var key in localStorage) {
        if(key !== localStorage.loggedInUser) {
            highScoreTable += "<tr><td>" + getData.FirstName + "</td><td>" + getData.LastName + "</td></tr>";
        }
    }
    document.getElementById('rankTable').innerHTML = highScoreTable;
}
</code>```

答:
I think getData should be a function. It works for me when dispalyTable is

```<code>/* Rankings Table */
function displayTable() {
    var getData = function(key) { return JSON.parse(localStorage[key]); }
    var highScoreTable = "<tr><th>First Name</th><th>Last Name</th></tr>\n";
    for (var key in localStorage) {
        if (key !== 'loggedInUser') {
            var data = getData(key);
            highScoreTable += "<tr><td>" + data.FirstName + "</td><td>" + data.LastName + "</td></tr>";
        }
    }
    document.getElementById('rankTable').innerHTML = highScoreTable;
}
</code>```

I updated getData and also checking key against local storage key 'loggedInUser' instead of value. Or it can be if(localStorage[key] !== localStorage.loggedInUser)

https://jsfiddle.net/wapapzyd/

Title: Storing more users in a ranking table

Body:
I want to store more users on my rankings table, and display their first name and last name on the table. But every-time a new user registers, its replaces the first user on the table. How do I fix this? I've created a JSFiddle Here

/* Register */
function storeUserDetail() {
    var fNameInput = document.getElementById("firstNameInput").value;
    var lNameInput = document.getElementById("lastNameInput").value;
    var uNameInput = document.getElementById("userNameInput").value;
    var pWordInput = document.getElementById("passWordInput").value;
    var storeDetails = {};
    storeDetails.FirstName = fNameInput
    storeDetails.LastName = lNameInput
    storeDetails.Username = uNameInput
    storeDetails.Password = pWordInput
    localStorage[storeDetails.Username] = JSON.stringify(storeDetails);
}

/* Log In */
function loginUser() {
    var Username = document.getElementById("uNameInput").value;
    var Password = document.getElementById("pWordInput").value;
    var storeDetails = JSON.parse(localStorage[Username]);
    storeDetails.Username = document.getElementById("uNameInput").value;
    storeDetails.Password = document.getElementById("pWordInput").value;
    localStorage.loggedInUser = Username;
}

/* Rankings Table */
function displayTable() {
    var getData = JSON.parse(localStorage[localStorage.loggedInUser]);
    var highScoreTable = "
First Name	Last Name
\n";
    for(var key in localStorage) {
        if(key !== localStorage.loggedInUser) {
            highScoreTable += "
" + getData.FirstName + "	" + getData.LastName + "
";
        }
    }
    document.getElementById('rankTable').innerHTML = highScoreTable;
}

Body:
I think getData should be a function. It works for me when dispalyTable is

/* Rankings Table */
function displayTable() {
    var getData = function(key) { return JSON.parse(localStorage[key]); }
    var highScoreTable = "<tr><th>First Name</th><th>Last Name</th></tr>\n";
    for (var key in localStorage) {
        if (key !== 'loggedInUser') {
            var data = getData(key);
            highScoreTable += "<tr><td>" + data.FirstName + "</td><td>" + data.LastName + "</td></tr>";
        }
    }
    document.getElementById('rankTable').innerHTML = highScoreTable;
}

I updated getData and also checking key against local storage key 'loggedInUser' instead of value. Or it can be if(localStorage[key] !== localStorage.loggedInUser)

https://jsfiddle.net/wapapzyd/


问:
How to change reset password email subject in laravel?
I am beginner in Laravel. Currently I am learning this framework. My curent Laravel version is 5.3.

I am scaffolding my auth by using php artisan make:auth All are working fine. Also I configured gmail smtp in my .env file and mail.php in config directgory. All are perfectly working. But I saw by-default the forgot password email subject is going Reset Password. I want to change that.

I saw some blog. I found some blog. I have implement that in my site. But same output coming.

I followed these links -

https://laracasts.com/discuss/channels/general-discussion/laravel-5-password-reset-link-subject

https://laracasts.com/discuss/channels/general-discussion/reset-password-email-subject

https://laracasts.com/discuss/channels/laravel/how-to-override-message-in-sendresetlinkemail-in-forgotpasswordcontroller

答:
Just add the line:

->subject('New Subjetc')

in the the method toMail of the file Illuminate\Auth\Notifications\ResetPassword
like this:

```<code>public function toMail($notifiable)
{
    return (new MailMessage)
        ->subject('New Subjetc')
        ->line('You are receiving this email because we received a password reset request for your account.')
        ->action('Restaurar Contraseña', url(config('app.url').route('password.reset', $this->token, false)))
        ->line('If you did not request a password reset, no further action is required.');
}
</code>```

Body:
Just add the line:

->subject('New Subjetc')

in the the method toMail of the file Illuminate\Auth\Notifications\ResetPassword
like this:

public function toMail($notifiable)
{
    return (new MailMessage)
        ->subject('New Subjetc')
        ->line('You are receiving this email because we received a password reset request for your account.')
        ->action('Restaurar Contraseña', url(config('app.url').route('password.reset', $this->token, false)))
        ->line('If you did not request a password reset, no further action is required.');
}


问:
UIGesture failing for unknown reason in IOS
I have a UITextField that is the subview of UIScrollView
I have there exist a single tap gesture (or perhaps the older touch) as part of UITextField that makes it the first responder.  I wanted to add a double tap Gesture to the UITextField.  In order to make the two Gesture's mutually exclusive I needed to overload (though this is not quite the right word because I'm not using the same name) the single tap Gesture.  When I do it works fine so long as the function that it calls doesn't make the UITextField the first responder.  If it does make the textfield the first responder it fails the second time it's called.... wtf. So stack, a little help would go a long way.

this is where I add the gesture

```<code> UITapGestureRecognizer * singleTextTap = [[UITapGestureRecognizer alloc]
             initWithTarget:self action:@selector(handleSingleTextTap:)];
 singleTextTap.numberOfTapsRequired = 1;
 [aTextField addGestureRecognizer:singleTextTap];
</code>```

and this is where it is called

```<code>//single tap text
- (void) handleSingleTextTap:(UITapGestureRecognizer *)gestureRecognizer{
    NSLog(@"handling single tap");
    NSLog(@"textField gestures %@",
          [gestureRecognizer.view.gestureRecognizers descriptionWithLocale:nil]);
    [(UITextField *)gestureRecognizer.view becomeFirstResponder];
}
</code>```

you may notice the NSLog that out puts the gestuers registered to the textField this was to check the state of my singleTextTap gesture. which is 'ended' the first time and all next times this code is never reached

答:
What you're doing seems really strange, but whatever.  I'll assume you know what you're doing.

You might try the following:

```<code>UITapGestureRecognizer *doubleTap = ...;
UITapGestureRecognizer *singleTap = ...;
[singleTap requireGestureRecognizerToFail:doubleTap];
</code>```

This means that the single tap recognizer will only fire if the double tap one doesn't fire, effectively making them mutually exclusive.

Body:
I have a UITextField that is the subview of UIScrollView
I have there exist a single tap gesture (or perhaps the older touch) as part of UITextField that makes it the first responder.  I wanted to add a double tap Gesture to the UITextField.  In order to make the two Gesture's mutually exclusive I needed to overload (though this is not quite the right word because I'm not using the same name) the single tap Gesture.  When I do it works fine so long as the function that it calls doesn't make the UITextField the first responder.  If it does make the textfield the first responder it fails the second time it's called.... wtf. So stack, a little help would go a long way.

this is where I add the gesture

 UITapGestureRecognizer * singleTextTap = [[UITapGestureRecognizer alloc]
             initWithTarget:self action:@selector(handleSingleTextTap:)];
 singleTextTap.numberOfTapsRequired = 1;
 [aTextField addGestureRecognizer:singleTextTap];

and this is where it is called

//single tap text
- (void) handleSingleTextTap:(UITapGestureRecognizer *)gestureRecognizer{
    NSLog(@"handling single tap");
    NSLog(@"textField gestures %@",
          [gestureRecognizer.view.gestureRecognizers descriptionWithLocale:nil]);
    [(UITextField *)gestureRecognizer.view becomeFirstResponder];
}

you may notice the NSLog that out puts the gestuers registered to the textField this was to check the state of my singleTextTap gesture. which is 'ended' the first time and all next times this code is never reached

Body:
What you're doing seems really strange, but whatever.  I'll assume you know what you're doing.

You might try the following:

UITapGestureRecognizer *doubleTap = ...;
UITapGestureRecognizer *singleTap = ...;
[singleTap requireGestureRecognizerToFail:doubleTap];

This means that the single tap recognizer will only fire if the double tap one doesn't fire, effectively making them mutually exclusive.


问:
How can I make the backgorund image cover all of the screen?
I have an page with a header and a footer. The footer is pushed to the bottom of the page if no content is available to push it down. The problem is that a div with a background image isn't filling up the space from the header to the footer. Also it's parent main isn't resizing to fill the page. What can I do?

html {
  height: 100%;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
  position: relative;
  min-height: 100%;
}

#in {
  width: 1000px;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
}

header {
  background-color: #131b23;
  border-bottom: 6px solid #0f151a;
  text-align: center;
  left: 0;
  top: 0;
  width: 100%;
  height: 160px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
  z-index: 99;
}

#heading {
  font-family: "titlefont";
  color: #c03221;
  font-size: 55px;
  display: inline-block;
  margin-bottom: -7px;
  margin-top: 15px;
}

#subheading {
  font-family: "slogantextfont";
  font-size: 25px;
  margin-top: 0px;
  color: #f6ae2d;
  margin-bottom: 30px;
}

main {
  text-align: center;
  background: #f5f5f5 url("https://images.unsplash.com/photo-1510940725340-44c002560b46?dpr=1&auto=format&fit=crop&w=1000&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D") no-repeat center center;
  background-size: cover;
}

#title {
  margin: 0px;
  padding: 0px;
}

footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #25211e;
  border-top: 6px solid #1d1a18;
  text-align: center;
  height: 80px;
  z-index: 98;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
}

#credit {
  font-family: "Helvetica";
  font-size: 14px;
  color: #c1b497;
  font-weight: 600;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>My Page</title>
</head>

<body>
  <header>
    <h1 id="heading">My Page</h1>
    <h2 id="subheading">BLABLA BLA BLA BLA BLA BLA</h2>
  </header>
  <main>
    <h2 id="title">PICTURE</h2>
    <h2 id="title">PICTURE</h2>
    <h2 id="title">PICTURE</h2>
  </main>
  <footer>
    <p id="credit">BLABLA BLA BLA BLA BLA BLA</p>
  </footer>
</body>

</html></code>```

答: Set height:100% on the body and height:100% on main.</p>

Body:
I have an page with a header and a footer. The footer is pushed to the bottom of the page if no content is available to push it down. The problem is that a div with a background image isn't filling up the space from the header to the footer. Also it's parent main isn't resizing to fill the page. What can I do?

html {
  height: 100%;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
  position: relative;
  min-height: 100%;
}

#in {
  width: 1000px;
  margin-left: auto;
  margin-right: auto;
  height: 100%;
}

header {
  background-color: #131b23;
  border-bottom: 6px solid #0f151a;
  text-align: center;
  left: 0;
  top: 0;
  width: 100%;
  height: 160px;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
  z-index: 99;
}

#heading {
  font-family: "titlefont";
  color: #c03221;
  font-size: 55px;
  display: inline-block;
  margin-bottom: -7px;
  margin-top: 15px;
}

#subheading {
  font-family: "slogantextfont";
  font-size: 25px;
  margin-top: 0px;
  color: #f6ae2d;
  margin-bottom: 30px;
}

main {
  text-align: center;
  background: #f5f5f5 url("https://images.unsplash.com/photo-1510940725340-44c002560b46?dpr=1&auto=format&fit=crop&w=1000&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D") no-repeat center center;
  background-size: cover;
}

#title {
  margin: 0px;
  padding: 0px;
}

footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #25211e;
  border-top: 6px solid #1d1a18;
  text-align: center;
  height: 80px;
  z-index: 98;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23);
}

#credit {
  font-family: "Helvetica";
  font-size: 14px;
  color: #c1b497;
  font-weight: 600;
}

<!DOCTYPE html>

  <title>My Page</title>

My Page

BLABLA BLA BLA BLA BLA BLA

PICTURE

PICTURE

PICTURE

BLABLA BLA BLA BLA BLA BLA


问:
How to tell HSQLDB to allow identity definition for SERIAL?
I'm currently writing tests for a spring boot application which is using a postgreSQL database. During test I want to replace the database by some in-memory variant like H2 or HSQLDB. Sadly both do not behave the same as the postgreSQL database.

I have migrations that look like

```<code>CREATE TABLE foo(id BIGSERIAL PRIMARY KEY, ...)
</code>```

This results in hsqldb telling me

```<code>SQL State  : 42525
Error Code : -5525
Message    : identity definition not allowed: FOO_ID
</code>```

So apparently creating the matching sequence for the primary key is forbidden. Is there a way to tell hsqldb to accept this?

答:
You need to set PostgreSQL compatibility mode in HSQLDB.

```<code>SET DATABASE SQL SYNTAX PGS TRUE
</code>```

Your table definition is then accepted and converted internally to the SQL Standard equivalent.

```<code>CREATE TABLE FOO(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL PRIMARY KEY, ..
</code>```

Body:
I'm currently writing tests for a spring boot application which is using a postgreSQL database. During test I want to replace the database by some in-memory variant like H2 or HSQLDB. Sadly both do not behave the same as the postgreSQL database.

I have migrations that look like

CREATE TABLE foo(id BIGSERIAL PRIMARY KEY, ...)

This results in hsqldb telling me

SQL State  : 42525
Error Code : -5525
Message    : identity definition not allowed: FOO_ID

So apparently creating the matching sequence for the primary key is forbidden. Is there a way to tell hsqldb to accept this?

Body:
You need to set PostgreSQL compatibility mode in HSQLDB.

SET DATABASE SQL SYNTAX PGS TRUE

Your table definition is then accepted and converted internally to the SQL Standard equivalent.

CREATE TABLE FOO(ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL PRIMARY KEY, ..


问:
Owl carousel - TypeError: this.$element.attr(...) is undefined
On my wordpress site i use jQuery 1.12.4 together with owl carousel 2.2. When i load an carousel i get the following error:

```<code>TypeError: this.$element.attr(...) is undefined
</code>```

The carousel is not working. jQuery is loadad in the header and owl carousel in the footer. I call owl carousel in a js file which is loadad after the owl carousel js:

```<code>jQuery(document).ready(function($) {
    $("#services-slider").owlCarousel();
});
</code>```

答:
Just minute ago have the same problem on Wordpress...

Look:

id="services-slider" - must be only ONE element with id="services-slider" on page

the element id="services-slider" must have class="owl-carousel"

Body:
On my wordpress site i use jQuery 1.12.4 together with owl carousel 2.2. When i load an carousel i get the following error:

TypeError: this.$element.attr(...) is undefined

The carousel is not working. jQuery is loadad in the header and owl carousel in the footer. I call owl carousel in a js file which is loadad after the owl carousel js:

jQuery(document).ready(function($) {
    $("#services-slider").owlCarousel();
});


问:
chr(n) failed when n exceeds 256
I am using chr and int to convert a binary representation string to real binary value.

What I did is

```<code>   n=int('0101011',2)
   binary=chr(n)
</code>```

Then binary is the real binary value of the representation string.

But what if the string I gave to int is larger than 256 in decimal?

Any solution?

PS:
The reason I use chr is I want to convert n to a string so that I can write it to a file, using f.write().

And this question is originated from this question

答:
When trying to convert unicode values you can run into a multitude of problems. So using unichr is not always possible either, for example:

```<code>>>> n = int('0001f600', 16)
>>> unichr(n)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: unichr() arg not in range(0x10000) (narrow Python build)
</code>```

Notice the narrow Python build message in the error, this means Python was built without wide unicode characters support, but even narrow Python can get around this limitation (without having to be recompiled with the --enable-unicode=ucs4 flag):

```<code>>>> n = int('0001f600', 16)
>>> s = '\\U{:0>8X}'.format(n)
>>> s
'\\U0001F600'
>>> binary = s.decode('unicode-escape')
>>> print(binary)

</code>```

Title: chr(n) failed when n exceeds 256

Body:
I am using chr and int to convert a binary representation string to real binary value.

What I did is

   n=int('0101011',2)
   binary=chr(n)

Then binary is the real binary value of the representation string.

But what if the string I gave to int is larger than 256 in decimal?

Any solution?

PS:
The reason I use chr is I want to convert n to a string so that I can write it to a file, using f.write().

And this question is originated from this question

Body:
When trying to convert unicode values you can run into a multitude of problems. So using unichr is not always possible either, for example:

>>> n = int('0001f600', 16)
>>> unichr(n)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: unichr() arg not in range(0x10000) (narrow Python build)

Notice the narrow Python build message in the error, this means Python was built without wide unicode characters support, but even narrow Python can get around this limitation (without having to be recompiled with the --enable-unicode=ucs4 flag):

>>> n = int('0001f600', 16)
>>> s = '\\U{:0>8X}'.format(n)
>>> s
'\\U0001F600'
>>> binary = s.decode('unicode-escape')
>>> print(binary)


问:
app is not deploying if <context> defined outside of server.xml in tomcat
<context> works just fine if I define it within <host> in server.xml but if I create a file called manager.xml in conf/Catalina/localhost, the application is not getting deployed. Am I missing anything ?

Here is the manager.xml

```<code><Context path="/manager" docBase="/var/tomcat/webapps/manager" privileged="true">
  </Context>
</code>```

答: Found the issue. It was due to deployonStartup is set to false. I have changed this to true and I'm able to use context.xml outside of war file now.</p>

Body:
<context> works just fine if I define it within <host> in server.xml but if I create a file called manager.xml in conf/Catalina/localhost, the application is not getting deployed. Am I missing anything ?

Here is the manager.xml

<Context path="/manager" docBase="/var/tomcat/webapps/manager" privileged="true">
  </Context>


问:
rails - display partial in another controllers view
I'm not sure why i can't get my index action to pass to my view.  Basically i have a controller called "jobs" with a partial called "recent jobs" and i want to display that "recent jobs" partial in another contollers view called "static_pages".

I thought that all i would have to do is call the below in my static_pages/home.html.erb:

```<code>    <%= render partial: "jobs/recent_jobs" %>
</code>```

but here's the error i get.  apparently @jobs is nil.

```<code>ActionView::Template::Error (undefined method `each' for nil:NilClass):
2: <div class="homepage_recent_jobs">
3:   <div class="container">
4:
5:     <% @jobs.each do |job| %>
6:       <% job.title %>
7:     <% end %>
8:
</code>```

here's my partial in the jobs controller

```<code>    <div class="homepage_recent_jobs">
      <div class="container">

        <% @jobs.each do |job| %>
          <% job.title %>
        <% end %>
     </div>
   </div>
</code>```

jobs index action

```<code>def index

  set_link_order_and_counters

  @jobs = Job.all

  # calls scopes
  if params[:experience].present?
    @jobs = @jobs.by_experience(params[:experience])
  end

  if params[:num_days_past].present?
    @jobs = @jobs.by_num_days_past(params[:num_days_past].to_i)
  end

  @jobs = @jobs.paginate(page: params[:page], per_page: 5)
end
</code>```

答:
As you're working with @jobs, and rendering static_pages#home you need to define it first, you've defined it only in jobs#index, and that's why when the view is rendered the value is nil.

Adding @jobs in the proper controller should work:

```<code>class StaticPagesController < ApplicationController
  def home
    @jobs = Job.all
  end
end
</code>```

And note with <%= render 'jobs/recent_jobs' %> Rails infers is a partial file, no need to use the partial option. Also to print the job's title you would need to use <%= %>.

Body:
I'm not sure why i can't get my index action to pass to my view.  Basically i have a controller called "jobs" with a partial called "recent jobs" and i want to display that "recent jobs" partial in another contollers view called "static_pages".

I thought that all i would have to do is call the below in my static_pages/home.html.erb:

    <%= render partial: "jobs/recent_jobs" %>

but here's the error i get.  apparently @jobs is nil.

ActionView::Template::Error (undefined method `each' for nil:NilClass):
2:

3:

4:
5:     <% @jobs.each do |job| %>
6:       <% job.title %>
7:     <% end %>
8:

here's my partial in the jobs controller

        <% @jobs.each do |job| %>
          <% job.title %>
        <% end %>

jobs index action

def index

  set_link_order_and_counters

  @jobs = Job.all

  # calls scopes
  if params[:experience].present?
    @jobs = @jobs.by_experience(params[:experience])
  end

  if params[:num_days_past].present?
    @jobs = @jobs.by_num_days_past(params[:num_days_past].to_i)
  end

  @jobs = @jobs.paginate(page: params[:page], per_page: 5)
end

Body:
As you're working with @jobs, and rendering static_pages#home you need to define it first, you've defined it only in jobs#index, and that's why when the view is rendered the value is nil.

Adding @jobs in the proper controller should work:

class StaticPagesController < ApplicationController
  def home
    @jobs = Job.all
  end
end

And note with <%= render 'jobs/recent_jobs' %> Rails infers is a partial file, no need to use the partial option. Also to print the job's title you would need to use <%= %>.


问:
the way of writing constructor, deconstructor and copy constructor for matrix class
I am trying to create a constructor, destructor, and copy constructor for  a matrix class, and I am not so sure if I am doing it well.

In particular, I am not sure about 2 things:

Is the destructor suppose to free memory also for the memory that is allocated in the copy-constructor?

As to the line Mat[i][j]=other[i][j] (see in the code below), I wonder if I should write Mat[i][j]=other.Mat[i][j] instead?

```<code>class Matrix
{
private:
    int rows;
    int cols;
    int **Mat;

public:
    Matrix (const int &rows,const int &cols);
    Matrix (const Matrix &other);
    ~Matrix ();
};

Matrix::Matrix(const int &n_rows,const int &n_cols) //constructor of class Matrix
{
    rows=n_rows;
    cols=n_cols;
    Mat=new int* [cols];

    for(int i =0;i<rows;i++)
       Mat[i]=new int[cols];

    for(int i=0;i<rows;i++)
      for(int j=0;j<cols;j++)
        Mat[i][j]=0;
}

Matrix::~Matrix () //destructor
{
    for(int i =0;i<rows;i++)
        delete Mat[i];

    delete[] Mat;
}

Matrix::Matrix(const Matrix &other)  //copy constructor
{
    cols=other.cols;
    rows=other.rows;
    Mat=new int* [other.rows];

    for(int i =0;i<other.rows;i++)
       Mat[i]=new int[other.cols];

    for(int i=0;i<other.rows;i++)
      for(int j=0;j<other.cols;j++)
            Mat[i][j]=other[i][j];
}
</code>```

答:
Yes. Anything the object still has allocated should be freed in the destructor.  It doesn't matter which constructor allocated it.

Yes, you need to use Mat[i][j]=other.Mat[i][j], especially since you haven't defined any operator[] for your class.

You also need to add a copy assignment operator, per the "Rule of Three", which basically states:

If a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator, it almost certainly requires all three.

Try this:

```<code>class Matrix
{
private:
    int rows;
    int cols;
    int **Mat;

public:
    Matrix (int n_rows, int n_cols);
    Matrix (const Matrix &other);
    ~Matrix ();

    Matrix& operator=(const Matrix &rhs);
    // alternatively:
    // Matrix& operator=(Matrix rhs);
};

Matrix::Matrix(int n_rows, int n_cols)
{
    rows = n _rows;
    cols = n_cols;

    Mat = new int*[rows];
    for(int i = 0; i < rows; ++i)
    {
       Mat[i] = new int[cols];
       for(int j = 0; i < cols; ++j)
           Mat[i][j] = 0;
    }
}

Matrix::Matrix(const Matrix &other)
{
    rows = other.rows;
    cols = other.cols;

    Mat = new int*[rows];
    for(int i = 0; i < rows; ++i)
    {
        Mat[i] = new int[cols];
        for(int j = 0; j < cols; ++j)
            Mat[i][j] = other.Mat[i][j];
    }
}

Matrix::~Matrix()
{
    for(int i = 0; i < rows; ++i)
        delete Mat[i];
    delete[] Mat;
}

Matrix& Matrix::operator=(const Matrix &rhs)
{
    if (&rhs != this)
    {
        Matrix temp(rhs);
        std::swap(Mat, temp.Mat);
        std::swap(rows, temp.rows);
        std::swap(cols, temp.cols);
    }

    return *this;
}

// alternatively:
/*
Matrix& Matrix::operator=(Matrix rhs)
{
    std::swap(Mat, rhs.Mat);
    std::swap(rows, rhs.rows);
    std::swap(cols, rhs.cols);
    return *this;
}
*/
</code>```

A better solution is to not use new[]/delete[] directly at all.  Use std::vector instead, and let it handle everything for you, thus allowing your class to follow the "Rule of Zero":

Classes that have custom destructors, copy/move constructors or copy/move assignment operators should deal exclusively with ownership (which follows from the Single Responsibility Principle). Other classes should not have custom destructors, copy/move constructors or copy/move assignment operators.

```<code>class Matrix
{
private:
    std::vector<std:vector<int> > Mat;

public:
    Matrix (int n_rows, int n_cols);
};

Matrix::Matrix(int n_rows, int n_cols)
{
    Mat.resize(n_rows);
    for(int i = 0; i < n_rows; ++i)
       Mat[i].resize(n_cols, 0);

    /* alternatively:
    Mat.resize(n_rows, std::vector<int>(n_cols, 0));
    */
}
</code>```

Body:
I am trying to create a constructor, destructor, and copy constructor for  a matrix class, and I am not so sure if I am doing it well.

In particular, I am not sure about 2 things:

Is the destructor suppose to free memory also for the memory that is allocated in the copy-constructor?

As to the line Mat[i][j]=other[i][j] (see in the code below), I wonder if I should write Mat[i][j]=other.Mat[i][j] instead?

class Matrix
{
private:
    int rows;
    int cols;
    int **Mat;

public:
    Matrix (const int &rows,const int &cols);
    Matrix (const Matrix &other);
    ~Matrix ();
};

Matrix::Matrix(const int &n_rows,const int &n_cols) //constructor of class Matrix
{
    rows=n_rows;
    cols=n_cols;
    Mat=new int* [cols];

    for(int i =0;i<rows;i++)
       Mat[i]=new int[cols];

    for(int i=0;i<rows;i++)
      for(int j=0;j<cols;j++)
        Mat[i][j]=0;
}

Matrix::~Matrix () //destructor
{
    for(int i =0;i<rows;i++)
        delete Mat[i];

    delete[] Mat;
}

Matrix::Matrix(const Matrix &other)  //copy constructor
{
    cols=other.cols;
    rows=other.rows;
    Mat=new int* [other.rows];

    for(int i =0;i<other.rows;i++)
       Mat[i]=new int[other.cols];

    for(int i=0;i<other.rows;i++)
      for(int j=0;j<other.cols;j++)
            Mat[i][j]=other[i][j];
}

Body:
Yes. Anything the object still has allocated should be freed in the destructor.  It doesn't matter which constructor allocated it.

Yes, you need to use Mat[i][j]=other.Mat[i][j], especially since you haven't defined any operator[] for your class.

You also need to add a copy assignment operator, per the "Rule of Three", which basically states:

If a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator, it almost certainly requires all three.

Try this:

class Matrix
{
private:
    int rows;
    int cols;
    int **Mat;

public:
    Matrix (int n_rows, int n_cols);
    Matrix (const Matrix &other);
    ~Matrix ();

    Matrix& operator=(const Matrix &rhs);
    // alternatively:
    // Matrix& operator=(Matrix rhs);
};

Matrix::Matrix(int n_rows, int n_cols)
{
    rows = n _rows;
    cols = n_cols;

    Mat = new int*[rows];
    for(int i = 0; i < rows; ++i)
    {
       Mat[i] = new int[cols];
       for(int j = 0; i < cols; ++j)
           Mat[i][j] = 0;
    }
}

Matrix::Matrix(const Matrix &other)
{
    rows = other.rows;
    cols = other.cols;

    Mat = new int*[rows];
    for(int i = 0; i < rows; ++i)
    {
        Mat[i] = new int[cols];
        for(int j = 0; j < cols; ++j)
            Mat[i][j] = other.Mat[i][j];
    }
}

Matrix::~Matrix()
{
    for(int i = 0; i < rows; ++i)
        delete Mat[i];
    delete[] Mat;
}

Matrix& Matrix::operator=(const Matrix &rhs)
{
    if (&rhs != this)
    {
        Matrix temp(rhs);
        std::swap(Mat, temp.Mat);
        std::swap(rows, temp.rows);
        std::swap(cols, temp.cols);
    }

    return *this;
}

// alternatively:
/*
Matrix& Matrix::operator=(Matrix rhs)
{
    std::swap(Mat, rhs.Mat);
    std::swap(rows, rhs.rows);
    std::swap(cols, rhs.cols);
    return *this;
}
*/

A better solution is to not use new[]/delete[] directly at all.  Use std::vector instead, and let it handle everything for you, thus allowing your class to follow the "Rule of Zero":

Classes that have custom destructors, copy/move constructors or copy/move assignment operators should deal exclusively with ownership (which follows from the Single Responsibility Principle). Other classes should not have custom destructors, copy/move constructors or copy/move assignment operators.

class Matrix
{
private:
    std::vector<std:vector<int> > Mat;

public:
    Matrix (int n_rows, int n_cols);
};

Matrix::Matrix(int n_rows, int n_cols)
{
    Mat.resize(n_rows);
    for(int i = 0; i < n_rows; ++i)
       Mat[i].resize(n_cols, 0);

    /* alternatively:
    Mat.resize(n_rows, std::vector<int>(n_cols, 0));
    */
}


问:
Python - Getting access to class instance via module property (by string name)
Ok, let me try and explain this to the best of my ability. Lets say I have a class called Foobar:

```<code>class Foobar():
    def __init__(self, foo, bar, choo):
        self.foo = foo
        self.bar = bar
        self.choo = choo

    def doIt(self):
        return self.foo + self.bar
</code>```

and I want to have a set of 10 possibilities of instances of Foobar that I will use in my application. Now my end user does not know or care about the values of foo, bar and choo, but would would like to pick one of the 10 possibilities, which I will label.

So I would like to store their choice in a db (but I only want to store the label, which represents a particular instance of the Foobar class).  So that way i can just grab the instance I need.

So I tried setting up all my instances in a module like so (lets call it "my_instances.py")

```<code>import Foobar

label_one = Foobar("eenie", "meenie", "miney")
label_two = Foobar("teeny", "toony", "tiny")
...
label_ten = Foobar("biggie", "boogie", "baggie")
</code>```

and that way, once I have the string from the db that represents their choice, I can grab that instance like so (I'm ignoring how you would get the string, but showing how I'm obtaining the instance).

```<code>import my_instances

my_object = getattr(my_instances, 'label_one')
result = my_object.doIt()
</code>```

I am getting a TypeError: unbound method doIt() must be called with Foobar instance as first argument.

So it appears I'm getting Foobar, but not a real instance of it.  Any help would be greatly appreciated. I believe I've explained my scenario enough that is you see a simpler workaround for what I am trying to do, please suggest it.

答:
As the comment suggests, you likely have a name collision between Foobar the class and Foobar the module.

However, it might be clearer to explicitly define a lookup table:

```<code>foobars = {
  'label_one': Foobar("eenie", "meenie", "miney"),
  'label_two': Foobar("teeny", "toony", "tiny"),
  ...
  'label_ten': Foobar("biggie", "boogie", "baggie")
}
</code>```

Usage:

```<code>result = foobars['label_one'].do_it()
</code>```

Dynamic symbol lookups can be clever, but aren't necessarily clearer.

Body:
Ok, let me try and explain this to the best of my ability. Lets say I have a class called Foobar:

class Foobar():
    def __init__(self, foo, bar, choo):
        self.foo = foo
        self.bar = bar
        self.choo = choo

    def doIt(self):
        return self.foo + self.bar

and I want to have a set of 10 possibilities of instances of Foobar that I will use in my application. Now my end user does not know or care about the values of foo, bar and choo, but would would like to pick one of the 10 possibilities, which I will label.

So I would like to store their choice in a db (but I only want to store the label, which represents a particular instance of the Foobar class).  So that way i can just grab the instance I need.

So I tried setting up all my instances in a module like so (lets call it "my_instances.py")

import Foobar

label_one = Foobar("eenie", "meenie", "miney")
label_two = Foobar("teeny", "toony", "tiny")
...
label_ten = Foobar("biggie", "boogie", "baggie")

and that way, once I have the string from the db that represents their choice, I can grab that instance like so (I'm ignoring how you would get the string, but showing how I'm obtaining the instance).

import my_instances

my_object = getattr(my_instances, 'label_one')
result = my_object.doIt()

I am getting a TypeError: unbound method doIt() must be called with Foobar instance as first argument.

So it appears I'm getting Foobar, but not a real instance of it.  Any help would be greatly appreciated. I believe I've explained my scenario enough that is you see a simpler workaround for what I am trying to do, please suggest it.

Body:
As the comment suggests, you likely have a name collision between Foobar the class and Foobar the module.

However, it might be clearer to explicitly define a lookup table:

foobars = {
  'label_one': Foobar("eenie", "meenie", "miney"),
  'label_two': Foobar("teeny", "toony", "tiny"),
  ...
  'label_ten': Foobar("biggie", "boogie", "baggie")
}

Usage:

result = foobars['label_one'].do_it()

Dynamic symbol lookups can be clever, but aren't necessarily clearer.


问:
Why do I keep getting NA values for my mean, median, and mode? (R) (10 days of Statistics)
I am trying to read the user input, and then compute the mean, median and mode.  However, I am unable to return any value other than NA.

This is the exercise

```<code>num_elements <- readline(prompt = "")
num_elements <- as.numeric(num_elements)

vec_elements <- readline(prompt = "")
vec_elements <- as.numeric(vec_elements)

mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}

#find the mean
print(mean(vec_elements))

#find the median
print(median(vec_elements))

#find the mode
print(mode(vec_elements))
</code>```

答:
In your code, you are not specifying any numeric values.

Change the code as follows

```<code>num_elements <- scan("stdin", integer(), n = 1)
vec_elements <- scan("stdin", integer(), sep=" ", n = num_elements)
</code>```

The thing is, if you don't use input method as stdin, it reads the next line of code and treats it as the input.

The second line specifies space as a separator. In case you want, you can specify it as a tabspace or a newline character as well.

You don't need as.numeric() in your code.

Body:
I am trying to read the user input, and then compute the mean, median and mode.  However, I am unable to return any value other than NA.

This is the exercise

num_elements <- readline(prompt = "")
num_elements <- as.numeric(num_elements)

vec_elements <- readline(prompt = "")
vec_elements <- as.numeric(vec_elements)

mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}

#find the mean
print(mean(vec_elements))

#find the median
print(median(vec_elements))

#find the mode
print(mode(vec_elements))

Body:
In your code, you are not specifying any numeric values.

Change the code as follows

num_elements <- scan("stdin", integer(), n = 1)
vec_elements <- scan("stdin", integer(), sep=" ", n = num_elements)

The thing is, if you don't use input method as stdin, it reads the next line of code and treats it as the input.

The second line specifies space as a separator. In case you want, you can specify it as a tabspace or a newline character as well.

You don't need as.numeric() in your code.


问:
Connect Bot built with Microsoft Bot Framework to other connectors/Channels too
I have built a bot using Microsoft bot framework. Now I want to connect it to channels which are not supported by the Microsoft bot connector. However, I need to build an interface (or a substitute for bot connector) to connect to those channels. But as I am using Bot framework SDK (NodeJs), I need the best approach to expose the endpoint of my bot engine to other connectors/channels.</p>

答:
The Bot Framework has a mechanism specifically for this scenario, called Direct Line. Essentially, you build the UI interface yourself, but use the Direct Line API to forward events to/from the Bot Connector. You can use the Direct Line REST API, or find an npm package where someone has taken care of the underlying plumbing for you, as in the botframework-directline.js package. Microsoft has some node.js BotBuilder-Samples on their GitHub site too.

Note: The typical way to get the best help on SO is to post code of
  what you've tried and that gives people a better idea of how to help.
  I understand you don't know where to start, so that doesn't help much,
  but maybe it will explain why you're getting Close flags.


问:
Javascript regex: test people's name
From this questions : javascript regex : only english letters allowed

How can I make that expression test for people's name? Currently it doesn't allow spaces between names at all. I need to be able to match something like John Doe

Cheers

答:
```<code>^\s*([A-Za-z]{1,}([\.,] |[-']| ))+[A-Za-z]+\.?\s*$
</code>```

Similar as @Stephen_Wylie's solution, but shorter (better?).

Title: Javascript regex: test people's name

Body:
^\s*([A-Za-z]{1,}([\.,] |[-']| ))+[A-Za-z]+\.?\s*$

Similar as @Stephen_Wylie's solution, but shorter (better?).


问:
AWS API Gateway - log bad requests?
I have logging setup for my api (API Gateway and Lambda).  Where does API Gateway log Apache type HTTPS connection logs?  I would like to see what is hitting the end point that does not map to my API.  For example, my api is domain.com/api/v1/resource, how do I log if a client is trying to hit domain.com/api/v1/some_invalid_resource?  Also API Gateway prevents API abuse (see https://aws.amazon.com/api-gateway/faqs/), how would I know if my API is being attacked if I don't have connect level logs?</p>

答:
You can now Enable Access Logging on a stage of your API Gateway. (See bottom of page here: http://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-logging.html) In my tests so far, it logs correct IP Address, requestTime, and resource path only for valid requests. It logs the attempted access for invalid requests, but does not get IP, requestTime (which you can get from the log entry time anyway), nor attempted path.

I want to enable this to see if someone is trying to probe my API for an attack vector, so so far it isn't incredibly helpful.

Title: AWS API Gateway - log bad requests?


问:
Bootstrap drop down feature is not working
Need help to resolve the bootstrap dropdown navigation issue. I followed all the rules available but I am missing something. Please help.

The service tab has two drop down li which should open when click on the caret. But the website css is not allowing to do so.

```<code> <!-- navbar-header -->
        <div class="header-nav">
<nav class="navbar navbar-default">
                    <div class="navbar-header logo">
                                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                                    <span class="sr-only">Toggle navigation</span>
                                    <span class="icon-bar"></span>
                                    <span class="icon-bar"></span>
                                    <span class="icon-bar"></span>
                                </button>
                                <h1>
                                    <a class="navbar-brand" href="http://www.example.com/">Brand Name</a>
                                </h1>
                    </div>

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1 navis">

                        <ul class="nav navbar-nav navbar-right">
                            <li><a href="http://www.example.com/" class="hvr-bounce-to-bottom active">Home</a></li>
                            <li><a href="http://www.example.com/about-us.php" class="hvr-bounce-to-bottom">About</a></li>

        <li class="dropdown">
          <a href="http://www.example.com/seo-service.php" class="dropdown-toggle" data-toggle="dropdown" >Services <span class="caret"></span></a>
              <ul class="dropdown-menu">
                 <li><a href="http://www.example.com/seo-service.php">SEO Service</a></li>
                 <li><a href="digital-marketing-company.php">Digital Marketing</a></li>
              </ul>
        </li>

<li><a href="#projects" class="hvr-bounce-to-bottom scroll">Projects</a></li>
                            <li><a href="http://www.example.com/timeline.php" class="hvr-bounce-to-bottom">Timeline</a></li>
                            <li><a href="http://www.example.com/contact-us.php" class="hvr-bounce-to-bottom">Contact</a></li>

                        </ul>
                    </div>
                    <div class="contact-bnr-w3-agile">
                                <ul>
                                    <!--<li><i class="fa fa-envelope" aria-hidden="true"></i><a href="mailto:info@example.com">info@example.com</a></li>-->
                                    <li><i class="fa fa-phone" aria-hidden="true"></i>000000000 </li>
                                </ul>
                            </div>
                    <div class="clearfix"> </div>
                </nav>
                            <div class="clearfix"> </div>
        </div>
</code>```

答:
You have a typo in your code:

```<code><button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
</code>```

Here, data-target represents the div that is being targeted for toggling when you click the button. So, it is looking for the div with the ID "bs-example-navbar-collapse-1".  This line is fine, though I'd recommend renaming it to something more useful, like "site-nav" or something.

Now, here is where the problem occurs:

```<code><div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1 navis">
</code>```

This is the div that you are (correctly) trying to expand/collapse. But you have given it the id "bs-example-navbar-collapse-1 navis", which is not the same as "bs-example-navbar-collapse-1". So, you are clicking the button, but no div is being found with a matching ID.

To solve this, set the ID to "bs-example-navbar-collapse-1" instead (remove "navis"):

```<code><div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
</code>```

Now, all should be right in the world.

Also, far as the jQuery warnings mentioned above, it seems you are loading jQuery 2 already, so you don't need to include 1.12 as well. So make sure you are including the jQuery lib that you want.

Body:
Need help to resolve the bootstrap dropdown navigation issue. I followed all the rules available but I am missing something. Please help.

The service tab has two drop down li which should open when click on the caret. But the website css is not allowing to do so.

                                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                                    Toggle navigation

                                </button>

                                    Brand Name

Home

About

          Services

SEO Service

Digital Marketing

Projects

Timeline

Contact

000000000

Body:
You have a typo in your code:

<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">

Here, data-target represents the div that is being targeted for toggling when you click the button. So, it is looking for the div with the ID "bs-example-navbar-collapse-1".  This line is fine, though I'd recommend renaming it to something more useful, like "site-nav" or something.

Now, here is where the problem occurs:

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1 navis">

This is the div that you are (correctly) trying to expand/collapse. But you have given it the id "bs-example-navbar-collapse-1 navis", which is not the same as "bs-example-navbar-collapse-1". So, you are clicking the button, but no div is being found with a matching ID.

To solve this, set the ID to "bs-example-navbar-collapse-1" instead (remove "navis"):

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">

Now, all should be right in the world.

Also, far as the jQuery warnings mentioned above, it seems you are loading jQuery 2 already, so you don't need to include 1.12 as well. So make sure you are including the jQuery lib that you want.


问:
The problem: found a tab character that violate intendation
```<code>./run-bot
Running bot 22496
Error parsing ./shittybot.yml: YAML::XS::Load Error: The problem:

    found a tab character that violate intendation

was found at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 201
        Config::Any::_load('Config::Any', 'HASH(0x8de4708)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 94
        Config::Any::load_files('Config::Any', 'HASH(0x8de4708)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 104
        Config::JFDI::Source::Loader::_load_files('Config::JFDI::Source::Loader=HASH(0x85e1d48)', 'ARRAY(0x8de4f48)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 62
        Config::JFDI::Source::Loader::read('Config::JFDI::Source::Loader=HASH(0x85e1d48)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 153
        Config::JFDI::load('Config::JFDI=HASH(0x85e67c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 140
        Config::JFDI::config('Config::JFDI=HASH(0x85e67c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 131
        Config::JFDI::get('Config::JFDI=HASH(0x85e67c0)') called at bot.pl line 32
</code>```

How do I fix this?

EDIT:  I fixed indentation I think, but now I get this error:

```<code>Error parsing ./shittybot.yml: YAML::XS::Load Error: The problem:

    found character that cannot start any token

was found at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 201
        Config::Any::_load('Config::Any', 'HASH(0xa3da738)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 94
        Config::Any::load_files('Config::Any', 'HASH(0xa3da738)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 104
        Config::JFDI::Source::Loader::_load_files('Config::JFDI::Source::Loader=HASH(0x9bd7d48)', 'ARRAY(0xa3daf78)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 62
        Config::JFDI::Source::Loader::read('Config::JFDI::Source::Loader=HASH(0x9bd7d48)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 153
        Config::JFDI::load('Config::JFDI=HASH(0x9bdc7c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 140
        Config::JFDI::config('Config::JFDI=HASH(0x9bdc7c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 131
        Config::JFDI::get('Config::JFDI=HASH(0x9bdc7c0)') called at bot.pl line 32
</code>```

答:
Replace all spaces with tabs

Ensure everything is properly indented.

Body:
./run-bot
Running bot 22496
Error parsing ./shittybot.yml: YAML::XS::Load Error: The problem:

    found a tab character that violate intendation

was found at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 201
        Config::Any::_load('Config::Any', 'HASH(0x8de4708)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 94
        Config::Any::load_files('Config::Any', 'HASH(0x8de4708)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 104
        Config::JFDI::Source::Loader::_load_files('Config::JFDI::Source::Loader=HASH(0x85e1d48)', 'ARRAY(0x8de4f48)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 62
        Config::JFDI::Source::Loader::read('Config::JFDI::Source::Loader=HASH(0x85e1d48)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 153
        Config::JFDI::load('Config::JFDI=HASH(0x85e67c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 140
        Config::JFDI::config('Config::JFDI=HASH(0x85e67c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 131
        Config::JFDI::get('Config::JFDI=HASH(0x85e67c0)') called at bot.pl line 32

How do I fix this?

EDIT:  I fixed indentation I think, but now I get this error:

Error parsing ./shittybot.yml: YAML::XS::Load Error: The problem:

    found character that cannot start any token

was found at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 201
        Config::Any::_load('Config::Any', 'HASH(0xa3da738)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 94
        Config::Any::load_files('Config::Any', 'HASH(0xa3da738)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 104
        Config::JFDI::Source::Loader::_load_files('Config::JFDI::Source::Loader=HASH(0x9bd7d48)', 'ARRAY(0xa3daf78)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 62
        Config::JFDI::Source::Loader::read('Config::JFDI::Source::Loader=HASH(0x9bd7d48)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 153
        Config::JFDI::load('Config::JFDI=HASH(0x9bdc7c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 140
        Config::JFDI::config('Config::JFDI=HASH(0x9bdc7c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 131
        Config::JFDI::get('Config::JFDI=HASH(0x9bdc7c0)') called at bot.pl line 32