问:
LINQ to SQL query fails using two Contains statements
I have two tables, DH_MASTER and DH_ALIAS.  DH_MASTER contains information about a person, including their name.  DH_ALIAS contains AKA records about the person.  The tables are linked by the Operator field which is a primary key in DH_MASTER.

The users want to search by the name stored in DH_MASTER as well as search through all of their known aliases.  If any matches are found in either DH_MASTER or DH_ALIAS then the DH_MASTER entity should be returned.

I created the query below which should give the results I described (return any DH_MASTER rows where the DH_MASTER.Name == name or DH_MASTER.DH_ALIAs(n).Name == name).

It works fine if I use only ONE of the .Contains lines.  It doesn't matter which one I use.  But the execution fails when I try to use BOTH at the same time.

```<code>
    qry = From m In Context.DH_MASTERs _
          Where (m.Name.Contains(name)) _
              OrElse ((From a In m.DH_ALIAs _
                       Where a.Name.Contains(name)).Count() > 0) _
          Select m
</code>```

The LinqToSQL Query evaluates to the following SQL code (as displayed in the SQL Server Query Visualizer)

```<code>
SELECT [t0].[Operator], [t0].[Name], [t0].[Version]
FROM [DHOWNER].[DH_MASTER] AS [t0]
WHERE ([t0].[Name] LIKE %smith%) OR (((
    SELECT COUNT(*)
    FROM [DHOWNER].[DH_ALIAS] AS [t1]
    WHERE ([t1].[Name] LIKE %smith%) AND ([t1].[Operator] = [t0].[Operator])
    )) > 0)
</code>```

EDIT:  Checking the "Show Original" box in the Query Visualizer reveals the parameterized query as expected so this block of text below should be ignored.

I don't know if this is a problem or not but the `.Contains` evaluates to a `LIKE` expression (which is what I expect to happen) but the parameter is not encapsulated in apostrophes.

The interesting thing is that if I copy/paste the SQL Query into SQL 2005 Query Analyzer and add the apostrophes around the LIKE parameters, it runs just fine.  In fact, it's lightning quick (blink of an eye) even with more than 2 million rows.

But when the LINQ query runs, the web app locks up for about 31 seconds before it finally fails with this error on gv.DataBind:  Exception has been thrown by the target of an invocation.

With this innerException:  Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

Does anyone know why this happens and how the behavior can be worked around?  It's driving me nuts because the LinqToSql-generated SQL runs fine in query analyzer!

Update:

I have refactored my code based on the techniques in the answer.  This works!

```<code>qry = From m In qry _
 Where m.Name.Contains(name) OrElse _
 m.DH_ALIAs.Any(Function(aliasRec) aliasRec.Name.Contains(name)) _
Select m
</code>```

答:
Linq to sql doesn't specify values directly into the query, it uses parameters. Are you sure it had the contains parameter value directly in the sql?

Anyway, the timeout is likely caused by a deadlock: the query wants to read from a row in a table which is locked by another (insert/update) query /transaction and that query apparently takes longer to complete.

Body:
I have two tables, DH_MASTER and DH_ALIAS.  DH_MASTER contains information about a person, including their name.  DH_ALIAS contains AKA records about the person.  The tables are linked by the Operator field which is a primary key in DH_MASTER.

The users want to search by the name stored in DH_MASTER as well as search through all of their known aliases.  If any matches are found in either DH_MASTER or DH_ALIAS then the DH_MASTER entity should be returned.

I created the query below which should give the results I described (return any DH_MASTER rows where the DH_MASTER.Name == name or DH_MASTER.DH_ALIAs(n).Name == name).

It works fine if I use only ONE of the .Contains lines.  It doesn't matter which one I use.  But the execution fails when I try to use BOTH at the same time.

    qry = From m In Context.DH_MASTERs _
          Where (m.Name.Contains(name)) _
              OrElse ((From a In m.DH_ALIAs _
                       Where a.Name.Contains(name)).Count() > 0) _
          Select m

The LinqToSQL Query evaluates to the following SQL code (as displayed in the SQL Server Query Visualizer)

SELECT [t0].[Operator], [t0].[Name], [t0].[Version]
FROM [DHOWNER].[DH_MASTER] AS [t0]
WHERE ([t0].[Name] LIKE %smith%) OR (((
    SELECT COUNT(*)
    FROM [DHOWNER].[DH_ALIAS] AS [t1]
    WHERE ([t1].[Name] LIKE %smith%) AND ([t1].[Operator] = [t0].[Operator])
    )) > 0)

EDIT:  Checking the "Show Original" box in the Query Visualizer reveals the parameterized query as expected so this block of text below should be ignored.

I don't know if this is a problem or not but the `.Contains` evaluates to a `LIKE` expression (which is what I expect to happen) but the parameter is not encapsulated in apostrophes.

The interesting thing is that if I copy/paste the SQL Query into SQL 2005 Query Analyzer and add the apostrophes around the LIKE parameters, it runs just fine.  In fact, it's lightning quick (blink of an eye) even with more than 2 million rows.

But when the LINQ query runs, the web app locks up for about 31 seconds before it finally fails with this error on gv.DataBind:  Exception has been thrown by the target of an invocation.

With this innerException:  Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

Does anyone know why this happens and how the behavior can be worked around?  It's driving me nuts because the LinqToSql-generated SQL runs fine in query analyzer!

Update:

I have refactored my code based on the techniques in the answer.  This works!

qry = From m In qry _
 Where m.Name.Contains(name) OrElse _
 m.DH_ALIAs.Any(Function(aliasRec) aliasRec.Name.Contains(name)) _
Select m

OwnerDisplayName: Frans Bouma


来源: stackexchange

问:
Which is faster in mysql ? Multiple update queries in the same transaction, or a single query?
Which is faster? Multiple update queries in the same transaction, or a single query?

For example, in this case, which is faster?

```<code>UPDATE product p, productPrice pp
SET
p.name = newName,
pp.price = pp.price * 0.8
WHERE
p.productId = pp.productId
AND
p.productId = 1;
</code>```

Or this:

```<code>Update product set p.name = newName where productId = 1;
Update productPrice set price = price * 0.8 where productId = 1;
</code>```

Written in

```<code>a single transaction
</code>```

Should a lock be taken into consideration?

Any difference with their lock in mysql?

And

Any difference between the select queries and update queries situation ?

Thanks!

答:
Every query will have an overhead that MySQL spends e.g. allocating and freeing memory and resources, planning the execution and so on.

So while your queries will "do" the same thing, namely locate and update a row in the first table and then locate and update some rows in the second table, you will have more overhead.

The overhead will usually take only a few milliseconds. But for a query like "update a row using an index", which usually takes only a few milliseconds, the overhead is often responsible for nearly the complete execution time of the query, since the "action" itself (finding the row and writing the new value) is incredible fast.

So even if not every part of the overhead will be required twice if you split up your queries (e.g. "checking permissions if you are allowed to update the first table" will only be required once in both cases), your 2nd scenario will probably take about exactly twice as long as the first query because of the relatively big chunk of time the overhead requires here.

You should always check if combining your query actually saves time though (e.g. by looking at the execution plan or just measuring it, e.g. executing it 20 times in a row to get a measurable time). Sometimes MySQL will execute queries differently than you would expect. Also your code might become less readable if you overdo it.

The situation will basically be the same for any type of query, e.g. select.

Since the overhead can be very relevant, MySQL has a feature to get rid of it in some situation. If you are executing the same query several times (e.g. using your update for several products by just replacing the product id and maybe the price factor), you can use prepared statements, e.g. from php. This allows MySQL to do some of that overhead only once (e.g. planning how to execute your query), and the following basically identical queries can reuse this.

This has not much to do with transactions though (although your 2nd scenario increases the chances for a deadlock if you would e.g. have a different transaction that first updates the price and then tries to update the product, which would arguably influence execution speed too since you would have to repeat the transaction).

ContentLicense: CC BY-SA 3.0

Body:
Which is faster? Multiple update queries in the same transaction, or a single query?

For example, in this case, which is faster?

UPDATE product p, productPrice pp
SET
p.name = newName,
pp.price = pp.price * 0.8
WHERE
p.productId = pp.productId
AND
p.productId = 1;

Or this:

Update product set p.name = newName where productId = 1;
Update productPrice set price = price * 0.8 where productId = 1;

Written in

a single transaction

Should a lock be taken into consideration?

Any difference with their lock in mysql?

And

Any difference between the select queries and update queries situation ?

Thanks!


问:
I'm Unable to set value of textbox using php variable
I'm trying to set value of html input type text textboxes to empty when user clicks Search button and empID is not matched, but its giving error:

mysqli_num_rows() expects parameter 1 to be mysqli_result

Here is code:

```<code><html>
<body>
<form action="" method="post">
<h2>Employee Form</h2>

<input type="text" name="empID">
<input type="submit" name="searchRec" value="Search" />
<hr>

  Employee ID: <input type="text" name="empIDC" value="<?php echo htmlentities($employeeID); ?>">
  <br><br>

  Name: <input type="text" name="name" value="<?php echo htmlentities($Name); ?>">
  <br><br>

  Address: <input type="text" name="address" value="<?php echo htmlentities($Address); ?>">
  <br><br>
</form>
<?php
if( isset( $_REQUEST['searchRec'] ))
{
$employeeID = ($_POST["empID"]);

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bc140_DB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT empID, Name, Address, Dateofbirth, Salary, Timein from Employee where empID == $employeeID";
$result = mysqli_query($conn, $sql);

if(mysqli_num_rows($result > 0)){   while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {   $employeeID = $row['empID'];   $Name = $row['Name'];   $Address = $row['Address'];   $Dateofbirth = $row['Dateofbirth'];   $Salary = $row['Salary'];   $timestamp = $row['timeIn']; } }else{     $employeeID = "";   $Name = ""; $Address = "";   $Dateofbirth = "";   $Salary = "";   $timestamp = ""; }

}
?>
</body>
</html>
</code>```

答:
1st : Change your code order otherwise you will get undefined error  . your trying the embed the variable with html before creating the variable .

2nd :  should be use single =  not ==  empID = $employeeID

3rd : your mixing mysql with mysqli here  mysql_fetch_array($result, MYSQL_ASSOC)

Change to

```<code>mysqli_fetch_array($result,MYSQLI_ASSOC);
</code>```

4th: And also use isset() to confirm that variable exists or not if exists echo it otherwise echo the empty string .

5th: change your if like this if(mysqli_num_rows($result)>0){ }

file.php

```<code><?php
if( isset( $_REQUEST['searchRec'] ))
{
   ......
  $employeeID = $row['empID'];
  $Name = $row['Name'];
  $Address = $row['Address'];
  $Dateofbirth = $row['Dateofbirth'];
  $Salary = $row['Salary'];
  $timestamp = $row['timeIn'];
   ......
}
?>

<html>
<body>
.....
  Employee ID: <input type="text" name="empIDC" value="<?php  if(isset($employeeID)){ echo htmlentities($employeeID); } else { echo ""; }  ?>">
.....

</body>
</html>
</code>```

Body:
I'm trying to set value of html input type text textboxes to empty when user clicks Search button and empID is not matched, but its giving error:

mysqli_num_rows() expects parameter 1 to be mysqli_result

Here is code:

<form action="" method="post">

Employee Form

<input type="text" name="empID">
<input type="submit" name="searchRec" value="Search" />

  Employee ID: <input type="text" name="empIDC" value="<?php echo htmlentities($employeeID); ?>">

  Name: <input type="text" name="name" value="<?php echo htmlentities($Name); ?>">

  Address: <input type="text" name="address" value="<?php echo htmlentities($Address); ?>">

</form>
<?php
if( isset( $_REQUEST['searchRec'] ))
{
$employeeID = ($_POST["empID"]);

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bc140_DB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT empID, Name, Address, Dateofbirth, Salary, Timein from Employee where empID == $employeeID";
$result = mysqli_query($conn, $sql);

if(mysqli_num_rows($result > 0)){   while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {   $employeeID = $row['empID'];   $Name = $row['Name'];   $Address = $row['Address'];   $Dateofbirth = $row['Dateofbirth'];   $Salary = $row['Salary'];   $timestamp = $row['timeIn']; } }else{     $employeeID = "";   $Name = ""; $Address = "";   $Dateofbirth = "";   $Salary = "";   $timestamp = ""; }

}
?>

Body:
1st : Change your code order otherwise you will get undefined error  . your trying the embed the variable with html before creating the variable .

2nd :  should be use single =  not ==  empID = $employeeID

3rd : your mixing mysql with mysqli here  mysql_fetch_array($result, MYSQL_ASSOC)

Change to

mysqli_fetch_array($result,MYSQLI_ASSOC);

4th: And also use isset() to confirm that variable exists or not if exists echo it otherwise echo the empty string .

5th: change your if like this if(mysqli_num_rows($result)>0){ }

file.php

<?php
if( isset( $_REQUEST['searchRec'] ))
{
   ......
  $employeeID = $row['empID'];
  $Name = $row['Name'];
  $Address = $row['Address'];
  $Dateofbirth = $row['Dateofbirth'];
  $Salary = $row['Salary'];
  $timestamp = $row['timeIn'];
   ......
}
?>

<html>
<body>
.....
  Employee ID: <input type="text" name="empIDC" value="<?php  if(isset($employeeID)){ echo htmlentities($employeeID); } else { echo ""; }  ?>">
.....

</body>
</html>


问:
Android Studio: Flashlight crashes when turning off
Im trying to develop a flashlight app as my first "real" app, and almost everything worked. But everytime I want to turn my flashlight off, my app just crashes. Code and Logcat log follows:

```<code>package com.leuchtstein.flashlight;

import android.hardware.Camera;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text;
Camera camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.textView);
    }

public void triggerlight(View view) {

    if (stat == false) {
        camera = Camera.open();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(parameters);
        camera.startPreview();

        text.setText("ON");
        stat = true;

    } else {
        camera = Camera.open();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        camera.setParameters(parameters);
        camera.stopPreview();
        camera.release();

        text.setText("OFF");
        stat = false;

    }

}

}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.leuchtstein.flashlight.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/desc_textview"
        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large"
        app:layout_constraintHorizontal_bias="0.95"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="triggerlight"
        android:text="Turn on/off"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.387" />
</android.support.constraint.ConstraintLayout>
</code>```

Logcat:

```<code>https://pastebin.com/tNyF6GvX
</code>```

Thanks in advance, leuchtstein.

EDIT: Yes, I have the uses-permission function:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.leuchtstein.flashlight">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.FLASHLIGHT" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
Use the following permission in

AndroidManifest.xml

file

```<code><uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
</code>```

And follow this thread for more information
fail-to-connect-to-camera-service

Body:
Im trying to develop a flashlight app as my first "real" app, and almost everything worked. But everytime I want to turn my flashlight off, my app just crashes. Code and Logcat log follows:

package com.leuchtstein.flashlight;

import android.hardware.Camera;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text;
Camera camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.textView);
    }

public void triggerlight(View view) {

    if (stat == false) {
        camera = Camera.open();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(parameters);
        camera.startPreview();

        text.setText("ON");
        stat = true;

    } else {
        camera = Camera.open();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        camera.setParameters(parameters);
        camera.stopPreview();
        camera.release();

        text.setText("OFF");
        stat = false;

    }

}

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.leuchtstein.flashlight.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/desc_textview"
        android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large"
        app:layout_constraintHorizontal_bias="0.95"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="triggerlight"
        android:text="Turn on/off"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.387" />
</android.support.constraint.ConstraintLayout>

Logcat:

https://pastebin.com/tNyF6GvX

Thanks in advance, leuchtstein.

EDIT: Yes, I have the uses-permission function:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.leuchtstein.flashlight">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.FLASHLIGHT" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Body:
Use the following permission in

AndroidManifest.xml

file

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />

And follow this thread for more information
fail-to-connect-to-camera-service


问:
How to run a method from a class of another package in java
I am new to java ! I am sorry if the question is dumb ! Package is like this

myapp (folder)

print (folder)

printer.java

main.java

manifest.txt

So myapp is a package that contains another package (subpackage) print.

Code in main.java

```<code>package myapp;
import myapp.print;
class app{
    public static void main(String[] args) {
        printer po = new printer();
        po.printthis("Worked");
    }
}
</code>```

Code in printer.java

```<code>package myapp.print;
public class printer{
    public void printthis(String text){
        System.out.println(text);
    }
}
</code>```

Now I cannot make it to run , the error says what is printer word in main.java.
What I do is first compile the printer.java and then compile main.java but while compiling main.java the error comes up and it cannot be compiled.I am using CLI, Please help.

答:
Read Documentation first,
stackoverflow is not a tutorial

https://docs.oracle.com/javase/tutorial/

by the way
import whole package or specific class

```<code>import myapp.print.printer;
import myapp.print.*;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to java ! I am sorry if the question is dumb ! Package is like this

myapp (folder)

print (folder)

printer.java

main.java

manifest.txt

So myapp is a package that contains another package (subpackage) print.

Code in main.java

package myapp;
import myapp.print;
class app{
    public static void main(String[] args) {
        printer po = new printer();
        po.printthis("Worked");
    }
}

Code in printer.java

package myapp.print;
public class printer{
    public void printthis(String text){
        System.out.println(text);
    }
}

Now I cannot make it to run , the error says what is printer word in main.java.
What I do is first compile the printer.java and then compile main.java but while compiling main.java the error comes up and it cannot be compiled.I am using CLI, Please help.

Body:
Read Documentation first,
stackoverflow is not a tutorial

https://docs.oracle.com/javase/tutorial/

by the way
import whole package or specific class

import myapp.print.printer;
import myapp.print.*;


问:
Text on the top not center in the button
I have button with text on top

Here is code

.settings-button-new {
    width: 150px;
    height: 150px;
    text-decoration: none;
    line-height: 14px;
    text-align: center;
    position: relative;
    margin-left: 20px;
    margin-bottom: 20px;
    border: solid 4px #d3dbde;
    -webkit-border-radius: 13px;
    -moz-border-radius: 13px;
    border-radius: 13px;
    font: 15px Arial, Helvetica, sans-serif;
    color: #1c559b;
    background-color: #ffffff;
    background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -ms-linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc',GradientType=0 );
    background-image: linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
    display: block;
    position: absolute;
    top:0;
    left:0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <button class="settings-button-new"><span>Home</span></button></code>```

It on the top, but not centered as you can see.

I try to use text-align: center; but seems it not works.

How can i center it in button?

Thank's for help

答:
Just add below css code for center, if don't need to vertically center then the top:0 or as your need; and transform: translate(-50%, 0);.

```<code>.settings-button-new span {
      display: block;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
</code>```

.settings-button-new {
  width: 150px;
  height: 150px;
  text-decoration: none;
  line-height: 14px;
  position: relative;
  margin-left: 20px;
  margin-bottom: 20px;
  border: solid 4px #d3dbde;
  -webkit-border-radius: 13px;
  -moz-border-radius: 13px;
  border-radius: 13px;
  font: 15px Arial, Helvetica, sans-serif;
  color: #1c559b;
  background-color: #ffffff;
  background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  background-image: -ms-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc', GradientType=0);
  background-image: linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
  -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
  box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="settings-button-new"><span>Home</span></button></code>```

Only center.

```<code>.settings-button-new span {
          display: block;
          position: absolute;
          top: 5px;
          left: 50%;
          transform: translate(-50%, 0);
        }
</code>```

.settings-button-new {
  width: 150px;
  height: 150px;
  text-decoration: none;
  line-height: 14px;
  position: relative;
  margin-left: 20px;
  margin-bottom: 20px;
  border: solid 4px #d3dbde;
  -webkit-border-radius: 13px;
  -moz-border-radius: 13px;
  border-radius: 13px;
  font: 15px Arial, Helvetica, sans-serif;
  color: #1c559b;
  background-color: #ffffff;
  background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  background-image: -ms-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc', GradientType=0);
  background-image: linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
  -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
  box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
  display: block;
  position: absolute;
  top: 5px;
  left: 50%;
  transform: translate(-50%, 0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="settings-button-new"><span>Home</span></button></code>```

Body:
I have button with text on top

Here is code

.settings-button-new {
    width: 150px;
    height: 150px;
    text-decoration: none;
    line-height: 14px;
    text-align: center;
    position: relative;
    margin-left: 20px;
    margin-bottom: 20px;
    border: solid 4px #d3dbde;
    -webkit-border-radius: 13px;
    -moz-border-radius: 13px;
    border-radius: 13px;
    font: 15px Arial, Helvetica, sans-serif;
    color: #1c559b;
    background-color: #ffffff;
    background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -ms-linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc',GradientType=0 );
    background-image: linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
    display: block;
    position: absolute;
    top:0;
    left:0;
}

 <button class="settings-button-new">Home</button>

It on the top, but not centered as you can see.

I try to use text-align: center; but seems it not works.

How can i center it in button?

Thank's for help

Body:
Just add below css code for center, if don't need to vertically center then the top:0 or as your need; and transform: translate(-50%, 0);.

.settings-button-new span {
      display: block;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

.settings-button-new {
  width: 150px;
  height: 150px;
  text-decoration: none;
  line-height: 14px;
  position: relative;
  margin-left: 20px;
  margin-bottom: 20px;
  border: solid 4px #d3dbde;
  -webkit-border-radius: 13px;
  -moz-border-radius: 13px;
  border-radius: 13px;
  font: 15px Arial, Helvetica, sans-serif;
  color: #1c559b;
  background-color: #ffffff;
  background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  background-image: -ms-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc', GradientType=0);
  background-image: linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
  -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
  box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

<button class="settings-button-new"><span>Home</span></button>

Only center.

.settings-button-new span {
          display: block;
          position: absolute;
          top: 5px;
          left: 50%;
          transform: translate(-50%, 0);
        }

.settings-button-new {
  width: 150px;
  height: 150px;
  text-decoration: none;
  line-height: 14px;
  position: relative;
  margin-left: 20px;
  margin-bottom: 20px;
  border: solid 4px #d3dbde;
  -webkit-border-radius: 13px;
  -moz-border-radius: 13px;
  border-radius: 13px;
  font: 15px Arial, Helvetica, sans-serif;
  color: #1c559b;
  background-color: #ffffff;
  background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  background-image: -ms-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc', GradientType=0);
  background-image: linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
  -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
  -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
  box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
  display: block;
  position: absolute;
  top: 5px;
  left: 50%;
  transform: translate(-50%, 0);
}

<button class="settings-button-new"><span>Home</span></button>


问:
WCF Custom Header does not Appear in Service
I was wondering if somebody came across this issue and has an answer or pointer. I implemented IClientMessageInspector to add a header to my soap message on the client. So, inside BeforeSendREquest I call MessageHeader.CreateHeader. This seems to work because i see the message in Fiddler with the header in the collection. On the service side, i have a custom authenticationManager. When the service call enters the implementation I dont see the header i inserted. I have a feeling the ServiceModel stack is skipping my header during deserialization but not sure. Also, not sure on how to fix this if its truly what is happening. Maybe implement the equivalent of IClientMessageInspector on the service side?

Any idea/pointers would be helpful.

答: In server-side WCF code, to act upon a SOAP header from the client (inserted by IClientMessageInspector), I have used an implementation of IDispatchMessageInspector. In its AfterReceiveRequest() method, I use request.Headers.FindHeader() to see if the expected header is present.</p>

ContentLicense: CC BY-SA 2.5


答:
```<code>.settings-button-new span {
margin: 0px;
text-align: center;
</code>```

<p>}</p>

Title: Text on the top not center in the button

Body:
.settings-button-new span {
margin: 0px;
text-align: center;

}


问:
Does Qt slots run in parallel with other code?
On this function example:

```<code>void MyClass::myFunction()
  {
    emit MySignal1();
    emit MySignal2();
  }
</code>```

If I have slot1 listening for MySignal1, and slot2 listening for MySignal2:

1) Is slot1 going to be always executed before slot2?

2) Will one slot be executed until the other one finishes? Or can both slots run in parallel?

答:
The answer entirely depends on how the signals are connected to their respective slots: Assuming both signals are connected once to the same object's slot, then: The invocations are always in order (assuming you don't do something weird.. but then you would know already.. like if you filter out QEvent::MetaCall events.. which is definitely not recommended).

If they are connected with Qt::QueuedConnection, the emissions always immediately return and don't wait for the invocations to finish.

You can use Qt::BlockingQueuedConnection, and then the emissions wait for the invocations to return (this can only be used if the destination object is in a different thread than the currently running thread and the destination object's thread has a running event loop - otherwise a deadlock occurs!).

For a Qt::DirectConnection, both emissions will become simple function calls, so the sequencing follows trivially for that case.

If you have different objects, then if you use Qt::DirectConnection, you still have sequenced executions.

Otherwise, for Qt::QueuedConnection or Qt::BlockingQueuedConnection and the destination objects live in the same thread, the same thing applies as above for the same-object case. If they live in different threads, for non-blocking queued connections, you have no order guarantees.. the slots may execute concurrently. For blocking queued connection, you again have ordered execution.

Body:
On this function example:

void MyClass::myFunction()
  {
    emit MySignal1();
    emit MySignal2();
  }

If I have slot1 listening for MySignal1, and slot2 listening for MySignal2:

1) Is slot1 going to be always executed before slot2?

2) Will one slot be executed until the other one finishes? Or can both slots run in parallel?


答:
Maybe this code can help you

.settings-button-new {
    width: 150px;
    height: 150px;
    text-decoration: none;
    line-height: 14px;
    text-align: center;
    position: relative;
    margin-left: 20px;
    margin-bottom: 20px;
    border: solid 4px #d3dbde;
    -webkit-border-radius: 13px;
    -moz-border-radius: 13px;
    border-radius: 13px;
    font: 15px Arial, Helvetica, sans-serif;
    color: #1c559b;
    background-color: #ffffff;
    background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -ms-linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc',GradientType=0 );
    background-image: linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
    display: block;
    position: absolute;
    top:0;
    left: 50%;
    transform: translateX(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <button class="settings-button-new"><span>Home</span></button></code>```

Body:
Maybe this code can help you

.settings-button-new {
    width: 150px;
    height: 150px;
    text-decoration: none;
    line-height: 14px;
    text-align: center;
    position: relative;
    margin-left: 20px;
    margin-bottom: 20px;
    border: solid 4px #d3dbde;
    -webkit-border-radius: 13px;
    -moz-border-radius: 13px;
    border-radius: 13px;
    font: 15px Arial, Helvetica, sans-serif;
    color: #1c559b;
    background-color: #ffffff;
    background-image: -moz-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -webkit-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -o-linear-gradient(top, #ffffff 0%, #fcfcfc 100%);
    background-image: -ms-linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fcfcfc', endColorstr='#fcfcfc',GradientType=0 );
    background-image: linear-gradient(top, #ffffff 0%,#fcfcfc 100%);
    -webkit-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    -moz-box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
    box-shadow: 0px 0px 2px #bababa, inset 0px 0px 1px #ffffff;
}

.settings-button-new span {
    display: block;
    position: absolute;
    top:0;
    left: 50%;
    transform: translateX(-50%);
}

 <button class="settings-button-new"><span>Home</span></button>


问:
jQgrid 100% width
I have tried following code for 100% width of my jQgrid.

```<code>height: "100%",
autowidth: true,
</code>```

And I have changed css - from fixed layout to auto (reference from another thread) to avoid unnecessary horizontal bar.

```<code>.ui-jqgrid .ui-jqgrid-htable {
   table-layout: auto;
   margin: 0em;
}
</code>```

and

```<code>.ui-jqgrid .ui-jqgrid-btable {
   table-layout: auto;
   margin: 0em;
   outline-style: none;
}
</code>```

Now issue of horizontal bar is solved but I'm facing new issue in layout which is highlighted in the attached image.

What can I do to avoid this header width mismatch?

Click here for image.

答:
Changing of table-layout to auto is absolutely wrong and it could be the origin of your problem. jqGrid hold column headers and the data in separate tables table.ui-jqgrid-htable and table.ui-jqgrid-btable. Setting table-layout: auto; will break column width in case of having long content in the grid. Nevertheless I think you have another problem, because the picture, which you included, has no long string.

One can solve your problem only if you would provide the demo, which reproduce the problem. I guess that real origin of your problem is not described in your question. I suppose that you increased the font-size and pagging and did it not full correctly. Typical error which I seen before was increasing of pagging of inside of main data (.ui-jqgrid tr.jqgrow > td) without making the same changes in the first hidden row .ui-jqgrid tr.jqgfirstrow > td or without changing the settings in the column headers .ui-jqgrid .ui-jqgrid-htable th.

I recommend you to examine the pagging and font-size of the first row of the column header (table.ui-jqgrid-htable) and the grid data (table.ui-jqgrid-btable). I guess that you directly of indirectly changes the setting holding the settings asynchronously (not the same in the column header and the the first row of the grid data).

Title: jQgrid 100% width

Body:
I have tried following code for 100% width of my jQgrid.

height: "100%",
autowidth: true,

And I have changed css - from fixed layout to auto (reference from another thread) to avoid unnecessary horizontal bar.

.ui-jqgrid .ui-jqgrid-htable {
   table-layout: auto;
   margin: 0em;
}

and

.ui-jqgrid .ui-jqgrid-btable {
   table-layout: auto;
   margin: 0em;
   outline-style: none;
}

Now issue of horizontal bar is solved but I'm facing new issue in layout which is highlighted in the attached image.

What can I do to avoid this header width mismatch?

Click here for image.


问:
ASP.Net Core Access to the Path is Denied with IFormFile
Just writing a simple ASP.NET Core WebAPI and when using a simple POST endpoint accepting IFormFiles:

```<code>        [HttpPost]
        public async Task<List<string>> Post(List<IFormFile> files)
        {
            long size = files.Sum(f => f.Length);
            List<string> result = new List<string>();

            Console.WriteLine(files.Count);

            foreach (var f in files)
            {
                if (f.Length > 0)
                {
                    Directory.CreateDirectory("Resources");
                    using (var stream = new FileStream("Resources", FileMode.Create))
                    {
                        await f.CopyToAsync(stream);
                        result.Add(f.FileName);
                    }
                }
            }
            return result;
        }
</code>```

I get this error:

System.UnauthorizedAccessException: Access to the path
  'F:\Documents HDD\spec-backend\Resources' is denied

I have looked into it and apparently it has something to do with my directory being readonly but I cannot figure out how to change this and even then the directory is being created by my ASP.NET controller anyway.

答:
The answer in the end was that the FileStream object required the name of the file in the path, not just the directory.</p>

```<code>using (var stream = new FileStream(Path.Combine("Resources", f.FileName), FileMode.Create))
{
    await f.CopyToAsync(stream);
    result.Add(f.FileName);
}
</code>```

Body:
Just writing a simple ASP.NET Core WebAPI and when using a simple POST endpoint accepting IFormFiles:

        [HttpPost]
        public async Task<List<string>> Post(List<IFormFile> files)
        {
            long size = files.Sum(f => f.Length);
            List<string> result = new List<string>();

            Console.WriteLine(files.Count);

            foreach (var f in files)
            {
                if (f.Length > 0)
                {
                    Directory.CreateDirectory("Resources");
                    using (var stream = new FileStream("Resources", FileMode.Create))
                    {
                        await f.CopyToAsync(stream);
                        result.Add(f.FileName);
                    }
                }
            }
            return result;
        }

I get this error:

System.UnauthorizedAccessException: Access to the path
  'F:\Documents HDD\spec-backend\Resources' is denied

I have looked into it and apparently it has something to do with my directory being readonly but I cannot figure out how to change this and even then the directory is being created by my ASP.NET controller anyway.

Body:
The answer in the end was that the FileStream object required the name of the file in the path, not just the directory.

using (var stream = new FileStream(Path.Combine("Resources", f.FileName), FileMode.Create))
{
    await f.CopyToAsync(stream);
    result.Add(f.FileName);
}


问:
How to include a Font Awesome icon in React's render()
Whenever I try to use a Font Awesome icon in React's render(), it isn't displayed on the resulting web page although it works in normal HTML.

```<code>render: function() {
    return <div><i class="fa fa-spinner fa-spin">no spinner but why</i></div>;
}
</code>```

Here is an live example: http://jsfiddle.net/pLWS3/

Where is the fault?

答:
If you are new to React JS and using create-react-app cli command to create the application, then run the following NPM command to include the latest version of font-awesome.

```<code>npm install --save font-awesome
</code>```

import font-awesome to your index.js file. Just add below line to your index.js file

```<code>import '../node_modules/font-awesome/css/font-awesome.min.css';
</code>```

or

```<code>import 'font-awesome/css/font-awesome.min.css';
</code>```

Don't forget to use className as attribute

```<code> render: function() {
    return <div><i className="fa fa-spinner fa-spin">no spinner but why</i></div>;
}
</code>```

Body:
Whenever I try to use a Font Awesome icon in React's render(), it isn't displayed on the resulting web page although it works in normal HTML.

render: function() {
    return
no spinner but why
;
}

Here is an live example: http://jsfiddle.net/pLWS3/

Where is the fault?

Body:
If you are new to React JS and using create-react-app cli command to create the application, then run the following NPM command to include the latest version of font-awesome.

npm install --save font-awesome

import font-awesome to your index.js file. Just add below line to your index.js file

import '../node_modules/font-awesome/css/font-awesome.min.css';

or

import 'font-awesome/css/font-awesome.min.css';

Don't forget to use className as attribute

 render: function() {
    return <div><i className="fa fa-spinner fa-spin">no spinner but why</i></div>;
}


问:
Javascript can't find element by id?
```<code><html>
<head>
    <title>Test javascript</title>

    <script type="text/javascript">
        var e = document.getElementById("db_info");
        e.innerHTML='Found you';
    </script>
</head>
<body>
    <div id="content">
        <div id="tables">

        </div>
        <div id="db_info">
        </div>
    </div>
</body>
</html>
</code>```

If I use alert(e); it turns up null.... and obviously I don't get any "found you" on screen. What am I doing wrong?

答:
How will the browser know when to run the code inside script tag? So, to make the code run after the window is loaded completely,

```<code>window.onload = doStuff;

function doStuff() {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
}
</code>```

The other alternative is to keep your  just before the closing  tag.

Title: Javascript can't find element by id?

Body:
    <title>Test javascript</title>

If I use alert(e); it turns up null.... and obviously I don't get any "found you" on screen. What am I doing wrong?

Body:
How will the browser know when to run the code inside script tag? So, to make the code run after the window is loaded completely,

window.onload = doStuff;

function doStuff() {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
}

The other alternative is to keep your <script...</script> just before the closing </body> tag.


问:
Laravel Migration table already exists, but I want to add new not the older
I previously created users table. Now I have created a new migration to create a new books table inside my schema. When I try to run the command

```<code>php artisan migrate
</code>```

It shows:

```<code>[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' alre
ady exists (SQL: create table `users` (`id` int unsigned not null auto_incr
ement primary key, `username` varchar(255) not null, `email` varchar(255) n
ot null, `password` varchar(255) not null, `created_at` timestamp default 0
 not null, `updated_at` timestamp default 0 not null) default character set
 utf8 collate utf8_unicode_ci)
</code>```

Here is my new migration table:

```<code><?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBooksTable extends Migration {
    public function up()
    {
        Schema::create('books', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('auther');
            $table->string('area');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('books');
    }
}
</code>```

How can I get rid of the error?

答:
Edit AppServiceProvider.php will be found at app/Providers/AppServiceProvider.php and add

```<code>use Illuminate\Support\Facades\Schema;

public function boot()
{
Schema::defaultStringLength(191);
}
</code>```

Then run

```<code>composer update
</code>```

On your terminal.
It helped me, may be it will work for you as well.

Body:
I previously created users table. Now I have created a new migration to create a new books table inside my schema. When I try to run the command

php artisan migrate

It shows:

[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' alre
ady exists (SQL: create table `users` (`id` int unsigned not null auto_incr
ement primary key, `username` varchar(255) not null, `email` varchar(255) n
ot null, `password` varchar(255) not null, `created_at` timestamp default 0
 not null, `updated_at` timestamp default 0 not null) default character set
 utf8 collate utf8_unicode_ci)

Here is my new migration table:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBooksTable extends Migration {
    public function up()
    {
        Schema::create('books', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('auther');
            $table->string('area');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('books');
    }
}

How can I get rid of the error?

Body:
Edit AppServiceProvider.php will be found at app/Providers/AppServiceProvider.php and add

use Illuminate\Support\Facades\Schema;

public function boot()
{
Schema::defaultStringLength(191);
}

Then run

composer update

On your terminal.
It helped me, may be it will work for you as well.


问:
Disable click propagation for href
This code snippet explains my case:

$("#b").click(function(e) {
  e.stopPropagation();
});

$("#b").click(function() {
  alert("trigger div");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  display: block;
  position: relative;
  width: 100px;
  height: 100px;
  background-color: gray;
}

div {
  position: absolute;
  width: 50px;
  height: 50px;
  top: 0;
  left: 0;
  background-color: red;
}</code>```

Test

```

The problem is that I only want to trigger the click function from the div and not the href from the a tag. In a similar question I found event.stopPropagation(), but that does not work in this case.

答:
```<code>$("#a").click(function (event) {
    event.preventDefault();
});

$("#b").click(function (event) {
    event.stopPropagation();
    alert("trigger div");
});
</code>```

Title: Disable click propagation for href

Body:
This code snippet explains my case:

$("#b").click(function(e) {
  e.stopPropagation();
});

$("#b").click(function() {
  alert("trigger div");
});

a {
  display: block;
  position: relative;
  width: 100px;
  height: 100px;
  background-color: gray;
}

div {
  position: absolute;
  width: 50px;
  height: 50px;
  top: 0;
  left: 0;
  background-color: red;
}

Test

The problem is that I only want to trigger the click function from the div and not the href from the a tag. In a similar question I found event.stopPropagation(), but that does not work in this case.


问:
What's the best alternative function of Lua string.gsub in Python?
What's the best alternative function of Lua's global pattern substitution function string.gsub(s, pattern, function) in Python? e.g.

```<code>> string.gsub("banana", "(a)(n)", function(a,b) return b..a end) -- reverse any "an"s
bnanaa  2
</code>```

UPDATE: I'd like to implement a complex function during pattern substitution in Python like Lua's string.gsub, which can be implemented by Python's re.sub with function or lambda expr.

答:
As string.gsub(s, pattern, replace [, n]) returns a pair of values, the modified string and the number of substitutions made, in Python, you need to use re.subn:

re.subn(pattern, repl, string, count=0, flags=0)

  Perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made).

See a Python demo:

```<code>import re
print (re.subn("(a)(n)", r"\2\1", "banana"))
# => ('bnanaa', 2)
</code>```

And you also may use an anonymous method (or a lambda expression for simpler scenarios) as a replacement argument:

```<code>print (re.subn("(a)(n)", lambda m: "{}{}".format(m.group(2), m.group(1)), "banana"))
# => ('bnanaa', 2)
</code>```

See another Python demo.

NOTE: If you need no number of replacements made, use a mere re.sub.

Body:
What's the best alternative function of Lua's global pattern substitution function string.gsub(s, pattern, function) in Python? e.g.

> string.gsub("banana", "(a)(n)", function(a,b) return b..a end) -- reverse any "an"s
bnanaa  2

UPDATE: I'd like to implement a complex function during pattern substitution in Python like Lua's string.gsub, which can be implemented by Python's re.sub with function or lambda expr.

Body:
As string.gsub(s, pattern, replace [, n]) returns a pair of values, the modified string and the number of substitutions made, in Python, you need to use re.subn:

re.subn(pattern, repl, string, count=0, flags=0)

  Perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made).

See a Python demo:

import re
print (re.subn("(a)(n)", r"\2\1", "banana"))
# => ('bnanaa', 2)

And you also may use an anonymous method (or a lambda expression for simpler scenarios) as a replacement argument:

print (re.subn("(a)(n)", lambda m: "{}{}".format(m.group(2), m.group(1)), "banana"))
# => ('bnanaa', 2)

See another Python demo.

NOTE: If you need no number of replacements made, use a mere re.sub.


问:
Node.JS & Mongoose - insert item into an array in the database
I am currently working on a project and I am stuck with inserting an item into an array/object in the database. What I am trying to do is to add the id of a 'upvoted' post to an array/list in the 'User' Collection, however, I cannot seem to get it to work.

The code for my schemas is as follows:

```<code>// this is a child scheme/sub-document
var uvpSchema = new Schema();
uvpSchema.add({
  post: String
});

var dvpSchema = new Schema();
dvpSchema.add({
  post: String
 });

//main schema
var userSchema = new Schema({
    firstname: { type: String, required: true },
    lastname: { type: String, required: true },
    username: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    upVotedPosts: [uvpSchema],
    downVotedPosts: [dvpSchema],
    created_at: Date,
});
</code>```

And here is the code in my 'routes.js' to insert the id of the post into the array:

```<code>var newPush = {
        post: postID  // postID is a variable that I have already defined
    };
    User.findOneAndUpdate({username: req.session.user}, {$push: {upVotedPosts: newPush}}, {upsert: true, save: true}, (err, user) => {
        if (err) console.log(err);
        user.upVotedPosts.push(newPush);
        User.save;
        res.redirect(req.get('referer'));
        console.log(user.upVotedPosts);
    });
</code>```

The error I receive in my terminal is:

```<code>{ _id: 595f68b5fadd49105813f8a4 },{ _id: 595f693d3c2c21189004b0a7 },{ _id: 595f70a2df80e0252894551b }
events.js:163
      throw er; // Unhandled 'error' event
      ^
</code>```

Thanks in advance ;-)

答:
First of all, I'd like to thank everyone's' help ;-)

I finally managed to get it partially working! My problem was that my functions were running asynchronously, causing some problems. I solved this by adding callback functions to each mongoose function.

However, the same error is still being returned, causing the server to crash. Everything else works; the new item is added to the array.

Is there anyway to ignore the error so that the server doesn't crash?

Body:
I am currently working on a project and I am stuck with inserting an item into an array/object in the database. What I am trying to do is to add the id of a 'upvoted' post to an array/list in the 'User' Collection, however, I cannot seem to get it to work.

The code for my schemas is as follows:

// this is a child scheme/sub-document
var uvpSchema = new Schema();
uvpSchema.add({
  post: String
});

var dvpSchema = new Schema();
dvpSchema.add({
  post: String
 });

//main schema
var userSchema = new Schema({
    firstname: { type: String, required: true },
    lastname: { type: String, required: true },
    username: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    upVotedPosts: [uvpSchema],
    downVotedPosts: [dvpSchema],
    created_at: Date,
});

And here is the code in my 'routes.js' to insert the id of the post into the array:

var newPush = {
        post: postID  // postID is a variable that I have already defined
    };
    User.findOneAndUpdate({username: req.session.user}, {$push: {upVotedPosts: newPush}}, {upsert: true, save: true}, (err, user) => {
        if (err) console.log(err);
        user.upVotedPosts.push(newPush);
        User.save;
        res.redirect(req.get('referer'));
        console.log(user.upVotedPosts);
    });

The error I receive in my terminal is:

{ _id: 595f68b5fadd49105813f8a4 },{ _id: 595f693d3c2c21189004b0a7 },{ _id: 595f70a2df80e0252894551b }
events.js:163
      throw er; // Unhandled 'error' event
      ^

Thanks in advance ;-)


问:
Angular export import object (getting object data)
On file 'A' I have this:

```<code>export const settings: object = {
  base: 1
}
</code>```

Now on file 'B' I import it and extract the base value:

```<code>import * as mySettings from '../settings';

baseValue: object=mySettings.settings.base;
</code>```

This is returning an error:

property: base does not exist on type: object.

How can I fix this?

答:
Solution

Remove the type in your code, in this case the word "object"

Results

Creating the Settings File

Create a file with following code, let's save with the name settings

```<code>export const settings = {
  base: 1
};
</code>```

Importing the file

Now, import the file with the path '../settings', I created a alias mySettings

```<code>import * as mySettings from '../settings';

baseValue: number = mySettings.settings.base;
</code>```

Body:
On file 'A' I have this:

export const settings: object = {
  base: 1
}

Now on file 'B' I import it and extract the base value:

import * as mySettings from '../settings';

baseValue: object=mySettings.settings.base;

This is returning an error:

property: base does not exist on type: object.

How can I fix this?

Body:
Solution

Remove the type in your code, in this case the word "object"

Results

Creating the Settings File

Create a file with following code, let's save with the name settings

export const settings = {
  base: 1
};

Importing the file

Now, import the file with the path '../settings', I created a alias mySettings

import * as mySettings from '../settings';

baseValue: number = mySettings.settings.base;


问:
Code is visible on modal
we're working on a project and anyone knows how to integrate ckeditor on modal? because in modal, it shows the tags that came from the ckeditor.

```<code><li>
    <a href="#" data-toggle="modal" data-target="#editComment'.$row['id'].'">
        <u>Edit</u>
    </a>
    <form id="editComment" method="post" action= '.base_url('admin/editComment').'>
        <div id="editComment'.$row['id'].'"class="modal fade">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h2 class="modal-title">Edit</h2>
                        <span>
                            <input type="hidden" name="task-id" value="'.$row['id'].'">
                        </span>
                    </div>

                    <div class="modal-body">
                        <textarea class="form-control" name="comment">'.$row['comment'].'</textarea>
                        <div class="modal-footer">
                        <button type="button" class="btn btn-primary" data-dismiss="modal">Save</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
</code>```

答:
This is because you cannot have HTML elements inside <textarea>'s. If you do put HTML elements inside, then they will display as plain text. You could use a div instead though, and use some JS/jQuery to make it editable, like this:

$('.editable').each(function() {
  this.contentEditable = true;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.editable {
  width: 200px;
  height: 100px;
  border: 1px solid #ccc;
  padding: 5px;
  /* to make it resizable */
  resize: both;
  overflow: auto;
}</code>```

  hi

```

Notice that, even though there is a  element inside the div, only the text inside it shows.

Title: Code is visible on modal

Body:
we're working on a project and anyone knows how to integrate ckeditor on modal? because in modal, it shows the tags that came from the ckeditor.

        Edit

    <form id="editComment" method="post" action= '.base_url('admin/editComment').'>

Edit

                            <input type="hidden" name="task-id" value="'.$row['id'].'">

                        <textarea class="form-control" name="comment">'.$row['comment'].'</textarea>

                        <button type="button" class="btn btn-primary" data-dismiss="modal">Save</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Body:
This is because you cannot have HTML elements inside <textarea>'s. If you do put HTML elements inside, then they will display as plain text. You could use a div instead though, and use some JS/jQuery to make it editable, like this:

$('.editable').each(function() {
  this.contentEditable = true;
});

div.editable {
  width: 200px;
  height: 100px;
  border: 1px solid #ccc;
  padding: 5px;
  /* to make it resizable */
  resize: both;
  overflow: auto;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="editable">
  <span>hi</span>
</div>

Notice that, even though there is a <span> element inside the div, only the text inside it shows.


问:
Loop not waiting for resolution of promise (containing nested firebase call)
I am trying to make a Firebase database call inside of a loop and an outer firebase call.  The inner Firebase database call is using data returned from the outer firebase call and the loop, which is why it is run within the outer one.  The results then should be set into the state.

Problem
The value that is being retrieved in the inner Firebase database call is not being set in the state.

Theory
Since Firebase database calls are asynchronous, my guess is that the inner Firebase database call does not finish before the loop completes and sets the state.
Therefore, I created a promise for the inner Firebase database call, so that the loop would wait for the call to finish before moving onto the next item.
However, the value retrieved is still not being set.

Does anyone know why the loop does not wait for promise containing call to Firebase database?

MY ATTEMPT

```<code>userRef.on("value", function(snapshot) {
  var snap = [];
  // loop through each branch received from firebase
  snapshot.forEach(function(data) {
    var firstThingsFirst = data.val().firstThingsFirst;
    var someID = data.val().someID;
    var myPromise = new Promise(function(resolve, reject) {
      userRef.child('somechild').child(someID).once('value').then(function(newSnapshot) {
        console.log("newSnapshot = (below)");
        console.log(newSnapshot.val());
        resolve(newSnapshot.val());
      }, function(error) {
        // Something went wrong.
        console.error("error (below)");
        console.error(error);
        reject("noValueFound")
      });
    });
    var someValue = "";
    myPromise.then(function(valueRetrieved) {
      console.log(".then of promise is running...");
      console.log("valueRetrieved = (below)");
      console.log(valueRetrieved);
      someValue = this.checkUndefined(valueRetrieved);
    }.bind(this));
    var array = {"firstThingsFirst": firstThingsFirst, "someValue": someValue};
    snap.push(array);
  });
  this.setState({
    snapshots: snap
  });
}.bind(this));
</code>```

Alternative Attempt:

```<code>userRef.on("value", function(snapshot) {
  var snap = [];
  // loop through each branch received from firebase
  snapshot.forEach(function(data) {
    var firstThingsFirst = data.val().firstThingsFirst;
    var someID = data.val().someID;
    var someValue = this.fetchValueByID(someID);

    var array = {"firstThingsFirst": firstThingsFirst, "someValue": someValue};
    snap.push(array);
  });
  this.setState({
    snapshots: snap
  });
}.bind(this));

fetchValueByID(someID) {
  userProfileRef.child('someChild').child(someID).once('value').then(function(snapshot) {
    console.log("snapshot (fetchValueByID) = (below)");
    console.log(snapshot.val());
    return snapshot.val();
  })
}
</code>```

I have also tried the approaches recommended by Firebase:

https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html

Thanks in advance.

答:
Does anyone know why the loop does not wait for promise containing call to Firebase database?

The reason for this is that you require setState to be called after all the fetches are done. But, your code doesn't do anything to wait. You just carry on with the loop and once it's done, call setState. You never really know whether your fetches completed or not. You need a way to wait for all the the fetches. In a nutshell, there is a problem because of mixing of synchronous and asynchronous code.

You can try this. The idea is to map all the fetchValueByID (I've added a return in the beginning) calls into an array of promises and then wait for all of them to resolve (using Promise.all) before doing setState

```<code>userRef.on("value", function(snapshot) {
  // loop through each branch received from firebase
  // AND map to array of promises
  var promises = [];
  snapshot.forEach(function(data) {
    var firstThingsFirst = data.val().firstThingsFirst;
    var someID = data.val().someID;
    promises.push(this.fetchValueByID(someID).then(function(someValue) {
      return {
        "firstThingsFirst": firstThingsFirst,
        "someValue": someValue
      };
    }));
  });

  // Wait for all promises to resolve
  Promise.all(promises).then(function(results) {
    this.setState({
      snapshots: results
    });
  }.bind(this))

}.bind(this));

fetchValueByID(someID) {
  // Notice the return here
  return userProfileRef.child('someChild').child(someID).once('value').then(function(snapshot) {
    console.log("snapshot (fetchValueByID) = (below)");
    console.log(snapshot.val());
    return snapshot.val();
  })
}
</code>```

I've faked all the possible data and converted my solution to a simple-to-understand snippet below

var promises = [];
// Faking the snapshot
[{
  a: 1,
  b: 10
}, {
  a: 2,
  b: 20
}].forEach(function(data) {
  var firstThingsFirst = data.a
  var someID = data.b
  promises.push(fetchValueByID(someID).then(function(someValue) {
    return {
      "firstThingsFirst": firstThingsFirst,
      "someValue": someValue
    };
  }));
});

// Wait for all promises to resolve
Promise.all(promises).then(function(results) {
  console.log(results);
});

function fetchValueByID(someID) {
  // Dummy Promise resolution
  // Notice the return here
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      // Dummy manipulation
      resolve(someID * 100);
    });
  }).then(function(snapshot) {
    console.log("snapshot (fetchValueByID) = (below)");
    console.log(snapshot);
    return snapshot;
  })
}```

Body:
I am trying to make a Firebase database call inside of a loop and an outer firebase call.  The inner Firebase database call is using data returned from the outer firebase call and the loop, which is why it is run within the outer one.  The results then should be set into the state.

Problem
The value that is being retrieved in the inner Firebase database call is not being set in the state.

Theory
Since Firebase database calls are asynchronous, my guess is that the inner Firebase database call does not finish before the loop completes and sets the state.
Therefore, I created a promise for the inner Firebase database call, so that the loop would wait for the call to finish before moving onto the next item.
However, the value retrieved is still not being set.

Does anyone know why the loop does not wait for promise containing call to Firebase database?

MY ATTEMPT

userRef.on("value", function(snapshot) {
  var snap = [];
  // loop through each branch received from firebase
  snapshot.forEach(function(data) {
    var firstThingsFirst = data.val().firstThingsFirst;
    var someID = data.val().someID;
    var myPromise = new Promise(function(resolve, reject) {
      userRef.child('somechild').child(someID).once('value').then(function(newSnapshot) {
        console.log("newSnapshot = (below)");
        console.log(newSnapshot.val());
        resolve(newSnapshot.val());
      }, function(error) {
        // Something went wrong.
        console.error("error (below)");
        console.error(error);
        reject("noValueFound")
      });
    });
    var someValue = "";
    myPromise.then(function(valueRetrieved) {
      console.log(".then of promise is running...");
      console.log("valueRetrieved = (below)");
      console.log(valueRetrieved);
      someValue = this.checkUndefined(valueRetrieved);
    }.bind(this));
    var array = {"firstThingsFirst": firstThingsFirst, "someValue": someValue};
    snap.push(array);
  });
  this.setState({
    snapshots: snap
  });
}.bind(this));

Alternative Attempt:

userRef.on("value", function(snapshot) {
  var snap = [];
  // loop through each branch received from firebase
  snapshot.forEach(function(data) {
    var firstThingsFirst = data.val().firstThingsFirst;
    var someID = data.val().someID;
    var someValue = this.fetchValueByID(someID);

    var array = {"firstThingsFirst": firstThingsFirst, "someValue": someValue};
    snap.push(array);
  });
  this.setState({
    snapshots: snap
  });
}.bind(this));

fetchValueByID(someID) {
  userProfileRef.child('someChild').child(someID).once('value').then(function(snapshot) {
    console.log("snapshot (fetchValueByID) = (below)");
    console.log(snapshot.val());
    return snapshot.val();
  })
}

I have also tried the approaches recommended by Firebase:

https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html

Thanks in advance.

Body:
Does anyone know why the loop does not wait for promise containing call to Firebase database?

The reason for this is that you require setState to be called after all the fetches are done. But, your code doesn't do anything to wait. You just carry on with the loop and once it's done, call setState. You never really know whether your fetches completed or not. You need a way to wait for all the the fetches. In a nutshell, there is a problem because of mixing of synchronous and asynchronous code.

You can try this. The idea is to map all the fetchValueByID (I've added a return in the beginning) calls into an array of promises and then wait for all of them to resolve (using Promise.all) before doing setState

userRef.on("value", function(snapshot) {
  // loop through each branch received from firebase
  // AND map to array of promises
  var promises = [];
  snapshot.forEach(function(data) {
    var firstThingsFirst = data.val().firstThingsFirst;
    var someID = data.val().someID;
    promises.push(this.fetchValueByID(someID).then(function(someValue) {
      return {
        "firstThingsFirst": firstThingsFirst,
        "someValue": someValue
      };
    }));
  });

  // Wait for all promises to resolve
  Promise.all(promises).then(function(results) {
    this.setState({
      snapshots: results
    });
  }.bind(this))

}.bind(this));

fetchValueByID(someID) {
  // Notice the return here
  return userProfileRef.child('someChild').child(someID).once('value').then(function(snapshot) {
    console.log("snapshot (fetchValueByID) = (below)");
    console.log(snapshot.val());
    return snapshot.val();
  })
}

I've faked all the possible data and converted my solution to a simple-to-understand snippet below

var promises = [];
// Faking the snapshot
[{
  a: 1,
  b: 10
}, {
  a: 2,
  b: 20
}].forEach(function(data) {
  var firstThingsFirst = data.a
  var someID = data.b
  promises.push(fetchValueByID(someID).then(function(someValue) {
    return {
      "firstThingsFirst": firstThingsFirst,
      "someValue": someValue
    };
  }));
});

// Wait for all promises to resolve
Promise.all(promises).then(function(results) {
  console.log(results);
});

function fetchValueByID(someID) {
  // Dummy Promise resolution
  // Notice the return here
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      // Dummy manipulation
      resolve(someID * 100);
    });
  }).then(function(snapshot) {
    console.log("snapshot (fetchValueByID) = (below)");
    console.log(snapshot);
    return snapshot;
  })
}


问:
Using PHP array in the JS code in PDO
I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.

I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array

```<code>$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$type_zagon = 1;
$id_kurat = 1;
$usid = 78;

$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));

    $gyvuliu_array = array();

    while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
        $gyvuliu_array[] = $num;
    }

    $array_encode = json_encode($gyvuliu_array);
?>
    <script>
        $('.surinkti_produkcija_paserti_gyvulius').click(function() {
            var gyvuliai_fermoje = '<?php echo $array_encode; ?>';
            var gyvuliu_array = [1,2,3,4,5,6,7,8,9];

            for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
                console.log(gyvuliu_array[i]);
            }

            // DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
            for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
                console.log(gyvuliai_fermoje[i]);
            }
        });
    </script>
</code>```

I guess something is bad with the $num variable but I'm not sure.

EDIT:
I've changed the second for loop and it looks like it's working:

```<code>for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
    console.log(gyvuliai_fermoje[i]);
}
</code>```

But I'm not sure if it's ok they aren't in the same row.
http://prntscr.com/ft4i9m

EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?

答:
Try this</p>

```<code>var gyvuliai_fermoje = <?php echo json_encode($array_encode, JSON_HEX_QUOT | JSON_HEX_APOS); ?>;
</code>```

Title: Using PHP array in the JS code in PDO

Body:
I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.

I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array

$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$type_zagon = 1;
$id_kurat = 1;
$usid = 78;

$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
    AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
    ':status' => 1,
    ':type' => $type_zagon,
    ':zagon_id' => $id_kurat,
    ':usid' => $usid
));

    $gyvuliu_array = array();

    while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
        $gyvuliu_array[] = $num;
    }

    $array_encode = json_encode($gyvuliu_array);
?>

I guess something is bad with the $num variable but I'm not sure.

EDIT:
I've changed the second for loop and it looks like it's working:

for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
    console.log(gyvuliai_fermoje[i]);
}

But I'm not sure if it's ok they aren't in the same row.
http://prntscr.com/ft4i9m

EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?

Body:
Try this

var gyvuliai_fermoje = <?php echo json_encode($array_encode, JSON_HEX_QUOT | JSON_HEX_APOS); ?>;


问:
What kind of API needs to be exposed to allow outside access to a Hyperledger Fabric private network?
What kind of API needs to be exposed to allow outside access to a Hyperledger Fabric private network?

Are there any specifications describing this?

Thank you in advance for any enlightenment.

答:
Hyperledger Fabric is designed to develep privated (permissioned) network. So, anyone who wants to acces to the network should have permissions for it. Hyperledger Fabric allows the acces to the network throught certificates, for wich it provides a CA. The CA allows you to control who are going to have acces to the netwotk. You register who you want.

Moreover, Hyperledger Fabric provides you a SDK wich makes it easy to use APIs to interact with a Hyperledger Fabric blockchain. More infor about it here.


问:
How to consume GTFS feed in Google Map v3 using Javascript?
I'm first time trying to use GTFS(General Transit Feed Specification) with Google Maps as per the Google developers page i have understood the concept of .txt files which are used as feed and for making a demo i downloaded a transit zip files from Google developers page. but I'm not getting how to use those transit files to show information on map. I tried to search tutorial for the same but could not find anything useful. Do i need to parse all those files to show in map or there is something different implementation.

I'm confused.

Please bear me with my lack of knowledge regarding GTFS.

答:
If you want to display stops and routes on a map, you can use gtfs-to-geojson to convert GTFS to GeoJSON that can be loaded onto a Google Map or Mapbox.

Install gtfs-to-geojson:

```<code>npm install gtfs-to-geojson -g
</code>```

Setup a config.json file, then run:

```<code>gtfs-to-geojson --configPath /path/to/your/config.json
</code>```

The tool will output a folder of GeoJSON files.

Body:
If you want to display stops and routes on a map, you can use gtfs-to-geojson to convert GTFS to GeoJSON that can be loaded onto a Google Map or Mapbox.

Install gtfs-to-geojson:

npm install gtfs-to-geojson -g

Setup a config.json file, then run:

gtfs-to-geojson --configPath /path/to/your/config.json

The tool will output a folder of GeoJSON files.


问:
Adding text scale to jQuery UI Slider
How to add the scales like poor, excellent, very good in the jQuery UI slider plugin</p>

```
|-------|--------|-------|
poor excellent  good   verygood
```

答: Try using Filament Group's jQuery UI selectToUISlider plugin</p>

Title: Adding text scale to jQuery UI Slider

Body:
How to add the scales like poor, excellent, very good in the jQuery UI slider plugin

|-------|--------|-------|
poor excellent  good   verygood


问:
Copying a Laravel's .env file into a Docker container
Setup

I'm running Docker on my Ubuntu server and I'm trying create a Laravel container to run my website with artisan. The Laravel project is inside a GitHub Repository and I clone the project to the docker container with a dockerfile.

Problem

Laravel projects are dependent on the .env (environment files) which are not included in the repo project, for security reasons. So when I clone the repo to the docker container it doesn't include the .env file and thereby doesn't run the website properly. I have an .env file locally on my Ubuntu that I'm trying to COPY to the docker container Laravel project folder, ofcourse it doesn't work. This is because it's looking for the directory in the docker container's file structure.

Error

```<code>Step 6/11 : COPY /containers/.env .env

lstat containers/.env: no such file or directory
</code>```

Question

How can I copy the .env file from the ubuntu server to the docker container with the COPY command?

file structure (Ubuntu) source from:

```<code>root/
  containers/
    - docker-compose
    - .env
</code>```

file structure (docker container) source to:

```<code>root/
  var/www/
</code>```

dockerfile

```<code>FROM hitalos/laravel

RUN git config --system http.sslverify false

RUN git clone repo /var/www

RUN git checkout test

COPY /containers/.env .env

# Run Compser Install
RUN composer install -d /var/www
RUN php /var/www/artisan key:generate

WORKDIR /var/www

CMD php /var/www/artisan serve --port=80 --host=0.0.0.0
EXPOSE 80
</code>```

答:
The path in COPY is relative to the Dockerfile

just change it to COPY containers/.env /var/www/.env

EDIT:
seems like you don't have the .env file at build time (image), only at runtime (container). That means, you have to mount the file when running the container.

Remove the COPY ... command from Dockerfile and instead run the container with

-v /containers/.env:/var/www/.env

so something like this:

docker run... -v /containers/.env:/var/www/.env ...

or change it in the compose yml file

Body:
Setup

I'm running Docker on my Ubuntu server and I'm trying create a Laravel container to run my website with artisan. The Laravel project is inside a GitHub Repository and I clone the project to the docker container with a dockerfile.

Problem

Laravel projects are dependent on the .env (environment files) which are not included in the repo project, for security reasons. So when I clone the repo to the docker container it doesn't include the .env file and thereby doesn't run the website properly. I have an .env file locally on my Ubuntu that I'm trying to COPY to the docker container Laravel project folder, ofcourse it doesn't work. This is because it's looking for the directory in the docker container's file structure.

Error

Step 6/11 : COPY /containers/.env .env

lstat containers/.env: no such file or directory

Question

How can I copy the .env file from the ubuntu server to the docker container with the COPY command?

file structure (Ubuntu) source from:

root/
  containers/
    - docker-compose
    - .env

file structure (docker container) source to:

root/
  var/www/

dockerfile

FROM hitalos/laravel

RUN git config --system http.sslverify false

RUN git clone repo /var/www

RUN git checkout test

COPY /containers/.env .env

# Run Compser Install
RUN composer install -d /var/www
RUN php /var/www/artisan key:generate

WORKDIR /var/www

CMD php /var/www/artisan serve --port=80 --host=0.0.0.0
EXPOSE 80


问:
Save textField value to cell textLabel (name) [SWIFT]
I'm going to do something like this https://i.stack.imgur.com/jAGsk.png

So if user input points - it'll save points to the user's name. How to do it? I paste textField in the tableViewCell with a functions.
Here is code from the tableViewCell file

```<code>@IBOutlet weak var inputScore: UITextField!

public func configure(text: Int?, placeholder: String) {
    inputScore.text = String(text!)
    inputScore.placeholder = placeholder

    inputScore.accessibilityValue = String(text!)
    inputScore.accessibilityLabel = placeholder
}
</code>```

And here is code from the VC file

```<code>public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "InputScore") as! InputScoreTableViewCell
    cell.textLabel?.text = usersIn[indexPath.row]
    cell.configure(text: 100, placeholder: "Score")
    return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return usersIn.count
}
</code>```

So how to save it to the user's name?

答:
In top of use user model provided by @Cesare we need to modified the cellForRowAtIndexPath method and your cell's implementation, adding a closure for data change event, and using it

```<code>@IBOutlet weak var inputScore: UITextField!
fileprivate var fnDataWasUpdated : (Int?) -> Void = {_ in} //closure for data change notification

public func configure(text: Int?, placeholder: String,_ fnListener: @escaping (Int?) -> Void) {
    inputScore.text = String(text!)
    inputScore.placeholder = placeholder

    inputScore.accessibilityValue = String(text!)
    inputScore.accessibilityLabel = placeholder

    //added delegate implementation for UITextField
    inputScore.delegate = self
    self.fnDataWasUpdated = fnListener
}
</code>```

also is needed that your cell adopts UITextFieldDelegate protocol

```<code>extension InputScoreTableViewCell : UITextFieldDelegate
{
    func textFieldDidEndEditing(_ textField: UITextField)
    {
        if let intValue = Int(textField.text)
         {
             self.fnDataWasUpdated(intValue)
         }
    }
}
</code>```

Finally we use the new closure in your cell

```<code>public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "InputScore") as! InputScoreTableViewCell
    let currUser = self.users[indexPath.row]
    cell.configure(text: currUser.points, placeholder: "Score",{ (newIntValue) in
                currUser.points = newIntValue
            })
    return cell
}
</code>```

This code was not tested but I had been using the main concept in several projects, so if you have any kind of problems please let me know

I hope this helps you

Body:
I'm going to do something like this https://i.stack.imgur.com/jAGsk.png

So if user input points - it'll save points to the user's name. How to do it? I paste textField in the tableViewCell with a functions.
Here is code from the tableViewCell file

@IBOutlet weak var inputScore: UITextField!

public func configure(text: Int?, placeholder: String) {
    inputScore.text = String(text!)
    inputScore.placeholder = placeholder

    inputScore.accessibilityValue = String(text!)
    inputScore.accessibilityLabel = placeholder
}

And here is code from the VC file

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "InputScore") as! InputScoreTableViewCell
    cell.textLabel?.text = usersIn[indexPath.row]
    cell.configure(text: 100, placeholder: "Score")
    return cell
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return usersIn.count
}

So how to save it to the user's name?

Body:
In top of use user model provided by @Cesare we need to modified the cellForRowAtIndexPath method and your cell's implementation, adding a closure for data change event, and using it

@IBOutlet weak var inputScore: UITextField!
fileprivate var fnDataWasUpdated : (Int?) -> Void = {_ in} //closure for data change notification

public func configure(text: Int?, placeholder: String,_ fnListener: @escaping (Int?) -> Void) {
    inputScore.text = String(text!)
    inputScore.placeholder = placeholder

    inputScore.accessibilityValue = String(text!)
    inputScore.accessibilityLabel = placeholder

    //added delegate implementation for UITextField
    inputScore.delegate = self
    self.fnDataWasUpdated = fnListener
}

also is needed that your cell adopts UITextFieldDelegate protocol

extension InputScoreTableViewCell : UITextFieldDelegate
{
    func textFieldDidEndEditing(_ textField: UITextField)
    {
        if let intValue = Int(textField.text)
         {
             self.fnDataWasUpdated(intValue)
         }
    }
}

Finally we use the new closure in your cell

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "InputScore") as! InputScoreTableViewCell
    let currUser = self.users[indexPath.row]
    cell.configure(text: currUser.points, placeholder: "Score",{ (newIntValue) in
                currUser.points = newIntValue
            })
    return cell
}

This code was not tested but I had been using the main concept in several projects, so if you have any kind of problems please let me know

I hope this helps you


问:
Pass an object to a function or sub procedure
I am trying to pass and excel work book off to a sub procedure with out having to open and close it again.

I tried this

```<code>Dim ExcelApp As New Excel.Application
Dim ws As Object

Public Function cert()
Set ws = ExcelApp.Workbooks.Open(FileDir).Sheets(1)
If CheckForMutipleUIC(ws) = True Then <---- this is where I call the Function
....
</code>```

The function opens to this

```<code>Public Function CheckForMutipleUIC(ByVal ws As Excel.Workbook) As Boolean
'    Dim ExcelApp As New Excel.Application
'    DataFleet = CurrentProject.Path & "\Extract\Fleet.xls"
'    Set ws1 = ExcelApp.Workbooks.Open(DataFleet).Sheets(1)
UICCheck = ws.Range("GD2").Value
For Each Cell In ws.Range("GD2:GD10000").cells
    If Cell.Text <> "" Then
        If Cell.Value <> UICCheck Then
            Err.Raise 513, "VICILauncher-DataValidation-CheckForMultipleUIC", "Multiple UICS Found in extract. Please Make sure the correct UIC is being Extracted"
        End If
    End If
Next
CheckForMutipleUIC = True
Exit Function
</code>```

But I guess I'm not passing the Excel object properly. How are applications objects passed to sub with out close and reopening.

答:
You have not included what error message you might be getting. But just looking at the posted code, it appears your passing a worksheet 'ws' into the CheckForMutipleUIC function which is expecting a workbook. Try changing the following.

Public Function CheckForMutipleUIC(ByVal ws As Excel.Workbook) As Boolean

to

Public Function CheckForMutipleUIC(ByVal ws As Excel.Worksheet) As Boolean

Body:
I am trying to pass and excel work book off to a sub procedure with out having to open and close it again.

I tried this

Dim ExcelApp As New Excel.Application
Dim ws As Object

Public Function cert()
Set ws = ExcelApp.Workbooks.Open(FileDir).Sheets(1)
If CheckForMutipleUIC(ws) = True Then <---- this is where I call the Function
....

The function opens to this

Public Function CheckForMutipleUIC(ByVal ws As Excel.Workbook) As Boolean
'    Dim ExcelApp As New Excel.Application
'    DataFleet = CurrentProject.Path & "\Extract\Fleet.xls"
'    Set ws1 = ExcelApp.Workbooks.Open(DataFleet).Sheets(1)
UICCheck = ws.Range("GD2").Value
For Each Cell In ws.Range("GD2:GD10000").cells
    If Cell.Text <> "" Then
        If Cell.Value <> UICCheck Then
            Err.Raise 513, "VICILauncher-DataValidation-CheckForMultipleUIC", "Multiple UICS Found in extract. Please Make sure the correct UIC is being Extracted"
        End If
    End If
Next
CheckForMutipleUIC = True
Exit Function

But I guess I'm not passing the Excel object properly. How are applications objects passed to sub with out close and reopening.


问:
How to include bootstrap css and js in reactjs app?
I am new to ReactJS, I want to include bootstrap in my React app

I have installed bootstrap by npm install bootstrap --save

Now, want to load bootstrap CSS and JS in my React app.

I am using webpack.

webpack.config.js

```<code>var config = {
    entry: './src/index',

    output: {
        path: './',
        filename: 'index.js'
    },

    devServer: {
        inline: true,
        port: 8080,
        historyApiFallback: true,
        contentBase:'./src'
    },

    module: {
        loaders: [
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                loader: 'babel',

                query: {
                    presets: ['es2015', 'react']
               }
            }
        ]
    }
};

module. exports = config;
</code>```

My issue is “how to include bootstrap CSS and JS in ReactJS app from node modules?" How to set up for bootstrap to include in my React app?

答:
If you are new to React and using create-react-app cli setup, run the npm command below to include the latest version of bootstrap.

```<code>npm install --save bootstrap
</code>```

or

```<code>npm install --save bootstrap@latest
</code>```

Then add the following import statement to index.js file. (https://getbootstrap.com/docs/4.4/getting-started/webpack/#importing-compiled-css)

```<code>import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
</code>```

or

```<code>import 'bootstrap/dist/css/bootstrap.min.css';
</code>```

don't forget to use className as attribute on target elements (react uses className as attribute instead of class).

Body:
I am new to ReactJS, I want to include bootstrap in my React app

I have installed bootstrap by npm install bootstrap --save

Now, want to load bootstrap CSS and JS in my React app.

I am using webpack.

webpack.config.js

var config = {
    entry: './src/index',

    output: {
        path: './',
        filename: 'index.js'
    },

    devServer: {
        inline: true,
        port: 8080,
        historyApiFallback: true,
        contentBase:'./src'
    },

    module: {
        loaders: [
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                loader: 'babel',

                query: {
                    presets: ['es2015', 'react']
               }
            }
        ]
    }
};

module. exports = config;

My issue is “how to include bootstrap CSS and JS in ReactJS app from node modules?" How to set up for bootstrap to include in my React app?

Body:
If you are new to React and using create-react-app cli setup, run the npm command below to include the latest version of bootstrap.

npm install --save bootstrap

or

npm install --save bootstrap@latest

Then add the following import statement to index.js file. (https://getbootstrap.com/docs/4.4/getting-started/webpack/#importing-compiled-css)

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

or

import 'bootstrap/dist/css/bootstrap.min.css';

don't forget to use className as attribute on target elements (react uses className as attribute instead of class).


问:
How to replace a String which has escape sequence inside a File using Perl?
how to replace a String inside a File using perl ?

```<code>perl -pi -e 's/Arun/Brun/g' *
</code>```

this worked fine for me

but when i tried to change class/students/a to class1/students1/B it throws error how to solve this problem ..i tried adding back slash (\) before every (/) but it didn't help

```<code>perl -pi -e 's/class/students/a/class1/students1/B/g' *
</code>```

答:
You are using / as regex delimiter.
There are / even in your pattern and replacement. You need to somehow ensure that these / should not be treated as delimiter.

You have two options:

Escape the / in your pattern and replacement as:

```<code>perl -pi -e 's/class\/students\/a/class1\/students1\/B/g' *
</code>```

Or use a different delimiter:

```<code>perl -pi -e 's#class/students/a#class1/students1/B#g' *
</code>```

Method 2 is preferred as it keeps your regex short and clean.

Body:
how to replace a String inside a File using perl ?

perl -pi -e 's/Arun/Brun/g' *

this worked fine for me

but when i tried to change class/students/a to class1/students1/B it throws error how to solve this problem ..i tried adding back slash (\) before every (/) but it didn't help

perl -pi -e 's/class/students/a/class1/students1/B/g' *

Body:
You are using / as regex delimiter.
There are / even in your pattern and replacement. You need to somehow ensure that these / should not be treated as delimiter.

You have two options:

Escape the / in your pattern and replacement as:

perl -pi -e 's/class\/students\/a/class1\/students1\/B/g' *

Or use a different delimiter:

perl -pi -e 's#class/students/a#class1/students1/B#g' *

Method 2 is preferred as it keeps your regex short and clean.