问:
Search bar in javascript from a database
For my project I cannot use php. All I found about search bar with database are in php or in html (with no database). That's why I am stuck. With this code, I have access to my database and it does show correctly all the atelier that I have in my list. But now the problem is how should I do to make a search bar that connects with those informations? (I don't care if it searches only the name (ateliers.nom) or all)
Hope you can help me!</p>

```<code><input type="text" id = "search" placeholder="search...">
<input type="submit" name = 'searchsubmit' value="Rechercher">
<table>
    <tr>
        <th>Atelier</th>
        <th>Nombres d'inscrits</th>
        <th>Lieu</th>
        <th>Chef</th>
        <th>Date</th>
        <th>Places disponibles</th>
    </tr>
    <c:forEach var="ateliers" items="${listAteliers}" varStatus="status">
        <tr>
            <th><c:out value="${ateliers.nom}" default="Empty"></c:out></th>
            <th><c:out value="${ateliers.nbinscrit}" default="Empty"></c:out></th>
            <th><c:out value="${ateliers.lieu}" default="Empty"></c:out></th>
            <th><c:out value="${ateliers.chef}"></c:out></th>
            <th><c:out value="${ateliers.date}" default="Empty"></c:out></th>
            <th><c:out value="${ateliers.place}" default="Empty"></c:out></th>
            <th><a href="<c:url value="./atelierdisplay/${listAteliers[status.index].id}"/>">Afficher</a></th>
            <th><a href="<c:url value="./atelieredit/${listAteliers[status.index].id}"/>">Editer</a></th>
        </tr>
    </c:forEach>
</table>
</code>```

答:
function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i
 -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myInput {
    background-image: url('/css/searchicon.png'); /* Add a search icon to input */
    background-position: 10px 12px; /* Position the search icon */
    background-repeat: no-repeat; /* Do not repeat the icon image */
    width: 100%; /* Full-width */
    font-size: 16px; /* Increase font-size */
    padding: 12px 20px 12px 40px; /* Add some padding */
    border: 1px solid #ddd; /* Add a grey border */
    margin-bottom: 12px; /* Add some space below the input */
}

#myTable {
    border-collapse: collapse; /* Collapse borders */
    width: 100%; /* Full-width */
    border: 1px solid #ddd; /* Add a grey border */
    font-size: 18px; /* Increase font-size */
}

#myTable th, #myTable td {
    text-align: left; /* Left-align text */
    padding: 12px; /* Add padding */
}

#myTable tr {
    /* Add a bottom border to all table rows */
    border-bottom: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
    /* Add a grey background color to the table header and on hover */
    background-color: #f1f1f1;
}</code>```

 <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">

    Name
    Country

    Alfreds Futterkiste
    Germany

    Berglunds snabbkop
    Sweden

    Island Trading
    UK

    Koniglich Essen
    Germany

 ```

Body:
For my project I cannot use php. All I found about search bar with database are in php or in html (with no database). That's why I am stuck. With this code, I have access to my database and it does show correctly all the atelier that I have in my list. But now the problem is how should I do to make a search bar that connects with those informations? (I don't care if it searches only the name (ateliers.nom) or all)
Hope you can help me!

<input type="text" id = "search" placeholder="search...">
<input type="submit" name = 'searchsubmit' value="Rechercher">

        Atelier
        Nombres d'inscrits
        Lieu
        Chef
        Date
        Places disponibles

    <c:forEach var="ateliers" items="${listAteliers}" varStatus="status">

            <c:out value="${ateliers.nom}" default="Empty"></c:out>
            <c:out value="${ateliers.nbinscrit}" default="Empty"></c:out>
            <c:out value="${ateliers.lieu}" default="Empty"></c:out>
            <c:out value="${ateliers.chef}"></c:out>
            <c:out value="${ateliers.date}" default="Empty"></c:out>
            <c:out value="${ateliers.place}" default="Empty"></c:out>
            <a href="<c:url value="./atelierdisplay/${listAteliers[status.index].id}"/>">Afficher
            <a href="<c:url value="./atelieredit/${listAteliers[status.index].id}"/>">Editer

    </c:forEach>

Body:
function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

#myInput {
    background-image: url('/css/searchicon.png'); /* Add a search icon to input */
    background-position: 10px 12px; /* Position the search icon */
    background-repeat: no-repeat; /* Do not repeat the icon image */
    width: 100%; /* Full-width */
    font-size: 16px; /* Increase font-size */
    padding: 12px 20px 12px 40px; /* Add some padding */
    border: 1px solid #ddd; /* Add a grey border */
    margin-bottom: 12px; /* Add some space below the input */
}

#myTable {
    border-collapse: collapse; /* Collapse borders */
    width: 100%; /* Full-width */
    border: 1px solid #ddd; /* Add a grey border */
    font-size: 18px; /* Increase font-size */
}

#myTable th, #myTable td {
    text-align: left; /* Left-align text */
    padding: 12px; /* Add padding */
}

#myTable tr {
    /* Add a bottom border to all table rows */
    border-bottom: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
    /* Add a grey background color to the table header and on hover */
    background-color: #f1f1f1;
}

 <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Koniglich Essen</td>
    <td>Germany</td>
  </tr>
</table>


来源: stackexchange

问:
How to use html-webpack-plugin with existing express templates?
I've intalled the express-generetor npm module and like how the project is structured with the jade files used as templates. However I also like to use the HTML-webpack-plugin which generates its own files, what is the best way to go about integrating both approaches?</p>

答:
Step1:

Generate your html file(s):

```<code>module.exports = {
  entry: {
    'page1': './apps/page1/scripts/main.js',
    'page2': './apps/page2/src/main.js'
  },
  output: {
    path: __dirname,
    filename: "apps/[name]/build/bundle.js"
  },
  plugins: [
    new HtmlWebpackPlugin({
      inject: true,
      chunks: ['page1'],
      filename: 'apps/page1/build/index.html'
    }),
    new HtmlWebpackPlugin({
      inject: true,
      chunks: ['page2'],
      filename: 'apps/page2/build/index.html'
    })
  ]
};
</code>```

Step2: Add the generated html file(s) to your jade file

include ../../public/index.html

ContentLicense: CC BY-SA 3.0

Body:
Step1:

Generate your html file(s):

module.exports = {
  entry: {
    'page1': './apps/page1/scripts/main.js',
    'page2': './apps/page2/src/main.js'
  },
  output: {
    path: __dirname,
    filename: "apps/[name]/build/bundle.js"
  },
  plugins: [
    new HtmlWebpackPlugin({
      inject: true,
      chunks: ['page1'],
      filename: 'apps/page1/build/index.html'
    }),
    new HtmlWebpackPlugin({
      inject: true,
      chunks: ['page2'],
      filename: 'apps/page2/build/index.html'
    })
  ]
};

Step2: Add the generated html file(s) to your jade file

include ../../public/index.html


问:
Get word that is surrounded by [tag] in brackets[/tag]
I would like to get a list of words, that is surrounded by a BBCode-like "tag".

E.g.:

```<code>$string = "Hello [tag]world[/tag], how [notag]are[/notag] you today? I am [tag]fine[/tag].";
</code>```

This should return an array like this:

world

fine

because both are surrounded by [tag], but "are" should not be added, because it is surrounded by another tag.

At the moment I try to check and replace the findings this way:

```<code>$e->innertext = preg_replace(
                                '/\b' . preg_quote( "[tag]".$text."[/tag]", "/" ) . '\b/i',
                                "<a href='$url'>\$0</a>",
                                $e->innertext,
                                1
                            );
</code>```

答:
Using lookbehind and lookahead, you can avoid capture groups.

Code (Demo):

```<code>$string = "Hello [tag]world[/tag], how [notag]are[/notag] you today? I am [tag]fine[/tag].";
var_export(preg_match_all('/(?<=\[tag\])[^[]+(?=\[\/tag\])/',$string,$out)?$out[0]:[]);
</code>```

Output:

```<code>array (
  0 => 'world',
  1 => 'fine',
)
</code>```

Or for pattern speed (faster than Sougata's pattern), use capture group with negated character class (Pattern Demo):

```<code>$string = "Hello [tag]world[/tag], how [notag]are[/notag] you today? I am [tag]fine[/tag].";
var_export(preg_match_all('/\[tag\]([^[]+)\[\/tag\]/',$string,$out)?$out[1]:[]);
</code>```

Body:
I would like to get a list of words, that is surrounded by a BBCode-like "tag".

E.g.:

$string = "Hello [tag]world[/tag], how [notag]are[/notag] you today? I am [tag]fine[/tag].";

This should return an array like this:

world

fine

because both are surrounded by [tag], but "are" should not be added, because it is surrounded by another tag.

At the moment I try to check and replace the findings this way:

$e->innertext = preg_replace(
                                '/\b' . preg_quote( "[tag]".$text."[/tag]", "/" ) . '\b/i',
                                "\$0",
                                $e->innertext,
                                1
                            );

Body:
Using lookbehind and lookahead, you can avoid capture groups.

Code (Demo):

$string = "Hello [tag]world[/tag], how [notag]are[/notag] you today? I am [tag]fine[/tag].";
var_export(preg_match_all('/(?<=\[tag\])[^[]+(?=\[\/tag\])/',$string,$out)?$out[0]:[]);

Output:

array (
  0 => 'world',
  1 => 'fine',
)

Or for pattern speed (faster than Sougata's pattern), use capture group with negated character class (Pattern Demo):

$string = "Hello [tag]world[/tag], how [notag]are[/notag] you today? I am [tag]fine[/tag].";
var_export(preg_match_all('/\[tag\]([^[]+)\[\/tag\]/',$string,$out)?$out[1]:[]);


问:
webview Implement Load Cache When Offline
thanks in advance I am trying to implement webview caching mechanism to a webview apk that I have done but I cant make this work.
I am very very inexpert.

Ok, I made some changes now i have no errors but the app still not working offline..

This is my entire code:

AndroidManifiest.xml

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

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <activity android:name="A" >
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="android.intent.action.VIEW" />
            <data android:scheme="activity_a" />
        </intent-filter>
    </activity>
    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="17"/>
    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

          </application>

</manifest>
```

<h3>MainActivity.java</h3>

```package uy.celular.service.HR;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends Activity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(uy.celular.service.HR.R.layout.activity_main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        webView = (WebView) findViewById(R.id.activity_main_webview);
        webView.setInitialScale(110);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new MyAppWebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                WebView webView = new WebView(context);
                webView.getSettings().setAppCacheMaxSize(5 * 1024 * 1024); // 5MB
                webView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
                webView.getSettings().setAllowFileAccess(true);
                webView.getSettings().setAppCacheEnabled(true);
                webView.getSettings().setJavaScriptEnabled(true);
                webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // load online by default

                if (!isNetworkAvailable()) { // loading offline
                    webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                }
                view.loadUrl(url);
                return false;
            }
        });

        webView.loadUrl("http://www.celularservice.uy/p/mobile.html?m=1#trab");
        webView.setWebViewClient(new MyAppWebViewClient(){

            @Override
            public void onPageFinished(WebView view, String url) {
            //hide loading image
            findViewById(R.id.imageLoading1).setVisibility(View.GONE);
            //show webview
            findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);

        }});
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

}
```

<h3>MyAppWebViewClient.java</h3>

```package uy.celular.service.HR;

import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Context;

public class MyAppWebViewClient extends WebViewClient {

    public Context context;
    public boolean isNetworkAvailable() {

        ConnectivityManager cm = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && url.startsWith("http://www.celularservice.uy/p/wp.html?m=1")) {
                view.getContext().startActivity(
                        new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            }
        if (url != null && url.startsWith("https://")) {
            view.getContext().startActivity(
                    new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
        if( url.startsWith("http:") || url.startsWith("https:") ) {
            return false;
        }

        else if (url.startsWith("tel:")) {
            Intent tel = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            view.getContext().startActivity(tel);
            return true;
        }
        else if (url.startsWith("sms:")) {
            Intent sms = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
            view.getContext().startActivity(sms);
            return true;
        }

        else if (url.startsWith("mailto:")) {
            Intent mail = new Intent(Intent.ACTION_SEND);
            mail.setType("application/octet-stream");
            mail.putExtra(Intent.EXTRA_EMAIL, new String[]{"celularservice.uy@gmail.com"});
            view.getContext().startActivity(mail);
            return true;
        }
        return true;

    }

}
```

remember i am new in this, please be expesific whit the answer

答:
Replace these:

```<code>webView.getSettings().setAppCacheMaxSize(5 * 1024 * 1024); // 5MB
webView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // load online by
if (!isNetworkAvailable()) { // loading offline
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
</code>```

with

```<code>webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
</code>```

You are good to go. I'd recommend not using webView as WebView variable. And, also, the setAppCacheMaxSize has been deprecated.

Body:
thanks in advance I am trying to implement webview caching mechanism to a webview apk that I have done but I cant make this work.
I am very very inexpert.

Ok, I made some changes now i have no errors but the app still not working offline..

This is my entire code:

AndroidManifiest.xml

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

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <activity android:name="A" >
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="android.intent.action.VIEW" />
            <data android:scheme="activity_a" />
        </intent-filter>
    </activity>
    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="17"/>
    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

          </application>

</manifest>

MainActivity.java

package uy.celular.service.HR;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends Activity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(uy.celular.service.HR.R.layout.activity_main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        webView = (WebView) findViewById(R.id.activity_main_webview);
        webView.setInitialScale(110);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new MyAppWebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                WebView webView = new WebView(context);
                webView.getSettings().setAppCacheMaxSize(5 * 1024 * 1024); // 5MB
                webView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
                webView.getSettings().setAllowFileAccess(true);
                webView.getSettings().setAppCacheEnabled(true);
                webView.getSettings().setJavaScriptEnabled(true);
                webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // load online by default

                if (!isNetworkAvailable()) { // loading offline
                    webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                }
                view.loadUrl(url);
                return false;
            }
        });

        webView.loadUrl("http://www.celularservice.uy/p/mobile.html?m=1#trab");
        webView.setWebViewClient(new MyAppWebViewClient(){

            @Override
            public void onPageFinished(WebView view, String url) {
            //hide loading image
            findViewById(R.id.imageLoading1).setVisibility(View.GONE);
            //show webview
            findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);

        }});
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

}

MyAppWebViewClient.java

package uy.celular.service.HR;

import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Context;

public class MyAppWebViewClient extends WebViewClient {

    public Context context;
    public boolean isNetworkAvailable() {

        ConnectivityManager cm = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && url.startsWith("http://www.celularservice.uy/p/wp.html?m=1")) {
                view.getContext().startActivity(
                        new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            }
        if (url != null && url.startsWith("https://")) {
            view.getContext().startActivity(
                    new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
        if( url.startsWith("http:") || url.startsWith("https:") ) {
            return false;
        }

        else if (url.startsWith("tel:")) {
            Intent tel = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            view.getContext().startActivity(tel);
            return true;
        }
        else if (url.startsWith("sms:")) {
            Intent sms = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
            view.getContext().startActivity(sms);
            return true;
        }

        else if (url.startsWith("mailto:")) {
            Intent mail = new Intent(Intent.ACTION_SEND);
            mail.setType("application/octet-stream");
            mail.putExtra(Intent.EXTRA_EMAIL, new String[]{"celularservice.uy@gmail.com"});
            view.getContext().startActivity(mail);
            return true;
        }
        return true;

    }

}

remember i am new in this, please be expesific whit the answer

Body:
Replace these:

webView.getSettings().setAppCacheMaxSize(5 * 1024 * 1024); // 5MB
webView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // load online by
if (!isNetworkAvailable()) { // loading offline
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}

with

webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

You are good to go. I'd recommend not using webView as WebView variable. And, also, the setAppCacheMaxSize has been deprecated.


问:
How do I give my websites an icon for iPhone?
How do I set the icon that appears proper on the iPhone for the websites I have created?

答: Add this in your head section:<link rel="icon" href="/your-icon-url"/>

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Zack


问:
Call actual function from blur()
I'm trying to write some jquery that will call a function when an object is blurred.  Because of some of the requirement in my underlying code, I need to call a function, like this:

```<code>$("object").blur(myFunction());
</code>```

instead of like this:

```<code>$("object").blur(function() {
  //do stuff
});
</code>```

Unfortunately, binding the blur event using the first method doesn't work.  It actually runs the method on page load, and then never binds the function.  What am I doing wrong here?

I've set up a jsfiddle that demonstrates my problem, if it helps you visualize. http://jsfiddle.net/WskKJ/

答:
```<code>$("object").blur(function() {
  myFunction();
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: Call actual function from blur()

Body:
I'm trying to write some jquery that will call a function when an object is blurred.  Because of some of the requirement in my underlying code, I need to call a function, like this:

$("object").blur(myFunction());

instead of like this:

$("object").blur(function() {
  //do stuff
});

Unfortunately, binding the blur event using the first method doesn't work.  It actually runs the method on page load, and then never binds the function.  What am I doing wrong here?

I've set up a jsfiddle that demonstrates my problem, if it helps you visualize. http://jsfiddle.net/WskKJ/


问:
How to round money in Twig to save zero in the end?
For example I have 19.796 and I need to round it up  so I use it like this {% set final_sum = sum + (sum / 100 * 21) | number_format(2, 'ceil') %} and it returns me 19.8 but I need 19.80 with zero on the end.

答:
You can try this:

```<code>{{ "%.2f"|format(final_sum) }}
</code>```

or localized currency:

```<code>{{ final_sum|localizedcurrency('EUR') }}
</code>```

UPD:

in your case you can do something like that:

```<code>{% set final_sum = "%.2f" | format(sum + (sum / 100 * 21)) %}
</code>```

So then you just can use this already formatted value as {{ final_sum }}

Body:
You can try this:

{{ "%.2f"|format(final_sum) }}

or localized currency:

{{ final_sum|localizedcurrency('EUR') }}

UPD:

in your case you can do something like that:

{% set final_sum = "%.2f" | format(sum + (sum / 100 * 21)) %}

So then you just can use this already formatted value as {{ final_sum }}


问:
Can't center a View in an activity in XML (Android)
I have created a new (second) activity in my android app, and right now there is one view in the content_area_reduction.xml (EditText). The file looks like this:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.myname.appname.AreaReductionActivity"
    tools:showIn="@layout/activity_area_reduction">

        <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>

</RelativeLayout>
</code>```

The problem is, the view appears on the left of the screen instead of center. How do I fix this issue? Will post more code if needed.

Thank you

答:
You should remove the line android:layout_alignParentTop="true" and add a new one:

```<code> <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_centerInParent="true"
            android:layout_centerHorizontal="true"/>
</code>```

Body:
I have created a new (second) activity in my android app, and right now there is one view in the content_area_reduction.xml (EditText). The file looks like this:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.myname.appname.AreaReductionActivity"
    tools:showIn="@layout/activity_area_reduction">

        <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>

</RelativeLayout>

The problem is, the view appears on the left of the screen instead of center. How do I fix this issue? Will post more code if needed.

Thank you

Body:
You should remove the line android:layout_alignParentTop="true" and add a new one:

 <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_centerInParent="true"
            android:layout_centerHorizontal="true"/>


问:
Angular 2 Get request error response,
I need to send POST request to the API and if response code == 400 get info from response.
http://joxi.ru/l2ZM0KES0M8ZmJ

```<code>public contactUsSendPost(params): Observable<{}> {
    return this.contactUsSendPostWithHttpInfo(params)
        .map((response: Response) => response.json());
}

public contactUsSendPostWithHttpInfo(params): Observable<Response> {
    const path = this.basePath + `/contact-us/send`;

    let queryParameters = new URLSearchParams();
    let headers = new Headers(this.defaultHeaders.toJSON());
    let formParams = new URLSearchParams();
    headers.set('Content-Type', 'application/x-www-form-urlencoded');
    headers.set('Accept', 'application/json');

    if (params.email !== undefined) {
        formParams.set('email', <any>params.email);
    }
    if (params.fullName !== undefined) {
        formParams.set('fullName', <any>params.fullName);
    }
    if (params.question !== undefined) {
        formParams.set('question', <any>params.question);
    }

    let requestOptions: RequestOptionsArgs = new RequestOptions({
        method: RequestMethod.Post,
        headers: headers,
        body: formParams.toString(),
        search: queryParameters
    });

    return this.http.request(path, requestOptions);
}
</code>```

Then im trying to get response from the service, but cant get response body.

```<code>this.fqService.contactUsSendPost(formValues).subscribe(
        data => console.log(data ),
        err => console.log(err) <------
    );
</code>```

So, how can i get response body in angular 2 from http response with 400 status code ?

答:
You just need to catch the error on your observable, see modified code below.</p>

```<code>    public contactUsSendPost(params): Observable<{}> {
        return this.contactUsSendPostWithHttpInfo(params)
            .map((response: Response) => response.json())
            .catch(this.handleError);
    }

    public contactUsSendPostWithHttpInfo(params): Observable<Response> {
        const path = this.basePath + `/contact-us/send`;

        let queryParameters = new URLSearchParams();
        let headers = new Headers(this.defaultHeaders.toJSON());
        let formParams = new URLSearchParams();
        headers.set('Content-Type', 'application/x-www-form-urlencoded');
        headers.set('Accept', 'application/json');

        if (params.email !== undefined) {
            formParams.set('email', <any>params.email);
        }
        if (params.fullName !== undefined) {
            formParams.set('fullName', <any>params.fullName);
        }
        if (params.question !== undefined) {
            formParams.set('question', <any>params.question);
        }

        let requestOptions: RequestOptionsArgs = new RequestOptions({
            method: RequestMethod.Post,
            headers: headers,
            body: formParams.toString(),
            search: queryParameters
        });

        return this.http.request(path, requestOptions);
    }

    private handleError (error: Response | any) {
        return Observable.throw(error.code);
    }
</code>```

Title: Angular 2 Get request error response,

Body:
I need to send POST request to the API and if response code == 400 get info from response.
http://joxi.ru/l2ZM0KES0M8ZmJ

public contactUsSendPost(params): Observable<{}> {
    return this.contactUsSendPostWithHttpInfo(params)
        .map((response: Response) => response.json());
}

public contactUsSendPostWithHttpInfo(params): Observable<Response> {
    const path = this.basePath + `/contact-us/send`;

    let queryParameters = new URLSearchParams();
    let headers = new Headers(this.defaultHeaders.toJSON());
    let formParams = new URLSearchParams();
    headers.set('Content-Type', 'application/x-www-form-urlencoded');
    headers.set('Accept', 'application/json');

    if (params.email !== undefined) {
        formParams.set('email', <any>params.email);
    }
    if (params.fullName !== undefined) {
        formParams.set('fullName', <any>params.fullName);
    }
    if (params.question !== undefined) {
        formParams.set('question', <any>params.question);
    }

    let requestOptions: RequestOptionsArgs = new RequestOptions({
        method: RequestMethod.Post,
        headers: headers,
        body: formParams.toString(),
        search: queryParameters
    });

    return this.http.request(path, requestOptions);
}

Then im trying to get response from the service, but cant get response body.

this.fqService.contactUsSendPost(formValues).subscribe(
        data => console.log(data ),
        err => console.log(err) <------
    );

So, how can i get response body in angular 2 from http response with 400 status code ?

Body:
You just need to catch the error on your observable, see modified code below.

    public contactUsSendPost(params): Observable<{}> {
        return this.contactUsSendPostWithHttpInfo(params)
            .map((response: Response) => response.json())
            .catch(this.handleError);
    }

    public contactUsSendPostWithHttpInfo(params): Observable<Response> {
        const path = this.basePath + `/contact-us/send`;

        let queryParameters = new URLSearchParams();
        let headers = new Headers(this.defaultHeaders.toJSON());
        let formParams = new URLSearchParams();
        headers.set('Content-Type', 'application/x-www-form-urlencoded');
        headers.set('Accept', 'application/json');

        if (params.email !== undefined) {
            formParams.set('email', <any>params.email);
        }
        if (params.fullName !== undefined) {
            formParams.set('fullName', <any>params.fullName);
        }
        if (params.question !== undefined) {
            formParams.set('question', <any>params.question);
        }

        let requestOptions: RequestOptionsArgs = new RequestOptions({
            method: RequestMethod.Post,
            headers: headers,
            body: formParams.toString(),
            search: queryParameters
        });

        return this.http.request(path, requestOptions);
    }

    private handleError (error: Response | any) {
        return Observable.throw(error.code);
    }


问:
Update rows par lot SQL Server
I need to change a value of column in a table, so I need to do this :

```<code>update members
set frequence = 1
where frequence <> 1
</code>```

I have 7 million rows impacted, I need to make the update in batches of 100000 rows and then sleep for 2 minutes (time to replications to other datebases).

How can I do this please?

Regrads

答:
This is a somewhat common way to do it, although usually it's used to limit the impact on transaction logs for large delete operations:

```<code>SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;

WHILE @r > 0
BEGIN
    BEGIN TRANSACTION;

    update top (100000) members
    set frequence = 1
    where frequence <> 1

    SET @r = @@ROWCOUNT;

    COMMIT TRANSACTION;

    WAITFOR DELAY '00:02'

    -- To limit log activity:
    -- CHECKPOINT;    -- if simple
    -- BACKUP LOG ... -- if full
END
</code>```

If you need to do them in order, do it like so:

```<code>SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;

WHILE @r > 0
BEGIN
    BEGIN TRANSACTION;

    ;with CTE as (
        select top 100000 *
        from members
        where frequence <> 1
        order by member_id
    )
    update CTE
    set frequence = 1

    SET @r = @@ROWCOUNT;

    COMMIT TRANSACTION;

    WAITFOR DELAY '00:02'

    -- To limit log activity:
    -- CHECKPOINT;    -- if simple
    -- BACKUP LOG ... -- if full
END
</code>```

Title: Update rows par lot SQL Server

Body:
I need to change a value of column in a table, so I need to do this :

update members
set frequence = 1
where frequence <> 1

I have 7 million rows impacted, I need to make the update in batches of 100000 rows and then sleep for 2 minutes (time to replications to other datebases).

How can I do this please?

Regrads

Body:
This is a somewhat common way to do it, although usually it's used to limit the impact on transaction logs for large delete operations:

SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;

WHILE @r > 0
BEGIN
    BEGIN TRANSACTION;

    update top (100000) members
    set frequence = 1
    where frequence <> 1

    SET @r = @@ROWCOUNT;

    COMMIT TRANSACTION;

    WAITFOR DELAY '00:02'

    -- To limit log activity:
    -- CHECKPOINT;    -- if simple
    -- BACKUP LOG ... -- if full
END

If you need to do them in order, do it like so:

SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;

WHILE @r > 0
BEGIN
    BEGIN TRANSACTION;

    ;with CTE as (
        select top 100000 *
        from members
        where frequence <> 1
        order by member_id
    )
    update CTE
    set frequence = 1

    SET @r = @@ROWCOUNT;

    COMMIT TRANSACTION;

    WAITFOR DELAY '00:02'

    -- To limit log activity:
    -- CHECKPOINT;    -- if simple
    -- BACKUP LOG ... -- if full
END


问:
why data is not inserting to database?
i am using php for inserting data in in mysql database. i am new to php and also mysql please help

```<code><html>
<head>
    <title>create menu</title>
</head>
<h1 align="center">create menu</h1>
<h2 align="center">Dont create more than 7 menu</h2><br/><br/>
<form method="post">
    <table border="2px" width="500px">
        <tr>
            <th colspan="2" align="center">create menu</th>
        </tr>
        <tr>
            <td align="right">menu name</td>
            <td><input type="text" name="menu"></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" name="submit" value="create"></td>
        </tr>
    </table>
</form>
<?php
mysql_connect("localhost","root","");
mysql_select_db("coupons");
if(isset($_POST['submit'])){
    $menu=$_POST['menu'];
    $query = "insert into menu(item) values ('$menu')";
    if(mysql_query($query)){
        echo "<h1 align='center'>DATA INSERTED</h1>";
    }
    else{
        echo "<h1>data not inserted</h1>";
    }
}
?>
</code>```

where am i wrong please help data is not inserting to database

答:
Your code is working absolutely fine. I tried it on my system. Check the screenshot -

HTML form submission result -

Value in database -

Possible errors on your system -

MySql is not running.

Database name is incorrect

You have not provided the password

Title: why data is not inserting to database?

Body:
i am using php for inserting data in in mysql database. i am new to php and also mysql please help

    <title>create menu</title>

create menu

Dont create more than 7 menu

<form method="post">

            create menu

            menu name
            <input type="text" name="menu">

            <input type="submit" name="submit" value="create">

</form>
<?php
mysql_connect("localhost","root","");
mysql_select_db("coupons");
if(isset($_POST['submit'])){
    $menu=$_POST['menu'];
    $query = "insert into menu(item) values ('$menu')";
    if(mysql_query($query)){
        echo "
DATA INSERTED
";
    }
    else{
        echo "
data not inserted
";
    }
}
?>

where am i wrong please help data is not inserting to database


问:
Need a basic understanding of the sqlplus command
sqlplus -s £ORA_LOGIN/£ORA_PASSWORD @./sql/getsess.sql £FEED > £FEED.lst

This is the command in a shell script. Can anyone please tell me what is this doing? because i have no knowledge about the sqlplus command

答:
This command runs the script ./sql/getsess.sql providing the value £FEED as parameter and using the credentials £ORA_LOGIN/£ORA_PASSWORD to login. It will store the output from the call to SQLPlus in the file named £FEED.lst.

Note that SQLPlus is invoked in silent mode (parameter -S), so most of the output will not be seen in the output file.


问:
Selected/Clicked UIButton text title color need to change from number of buttons on scrollview programmatically
I added number of UIButtons on scrollview programmatically based on array count, until this much its working fine. Requirement is only selected button text title color should change into brown color remain are blue.  I can’t able to solve this one please some one help using Swift 3. I need only the selected or clicked button text title color need to change remain all are in rest of the color.      </p>

```<code>           for titles in arrayPageTitles {
        var titleSize: CGSize = (titles as AnyObject).size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14.0)])
        titleSize = CGSize(width: CGFloat(ceilf(Float(titleSize.width))), height: CGFloat(ceilf(Float(titleSize.height))));

        /**
            creating top page strip tab Buttons
         */

        buttonTitle = UIButton(type: UIButtonType.custom)
        buttonTitle = UIButton(frame: CGRect(x: buttonPositionX + 5, y: 10, width: titleSize.width+40, height: (scrollViewTop?.frame.size.height)! - 20))
        buttonTitle.setTitle(titles, for: .normal)
        buttonTitle.setTitleColor(UIColor.blue, for: .normal)
        buttonTitle.setTitleColor(UIColor.white, for: .selected

        buttonTitle.clipsToBounds = true
        buttonTitle.layer.masksToBounds = true
        buttonTitle.layer.cornerRadius = 17
        buttonTitle.layer.borderWidth = 1
        buttonTitle.layer.borderColor = UIColor.darkGray.cgColor

        buttonTitle.tag = increaseIndex
        buttonTitle.addTarget(self, action: #selector(buttonTitleAction), for: .touchUpInside)

        arrayTitleButtons .add(buttonTitle)
        scrollViewTop?.addSubview(buttonTitle)
        let currentButtonX:CGFloat = buttonPositionX
        let buttonWidth:CGFloat = buttonTitle.frame.size.width
        buttonPositionX = currentButtonX + buttonWidth + 10

        if arrayPageTitles.first == titles  {

            viewLine.frame = CGRect(x: buttonTitle.frame.origin.x, y: buttonTitle.frame.origin.y, width: buttonTitle.frame.size.width, height: buttonTitle.frame.size.height)

            viewLine.layer.cornerRadius = 17
            viewLine.clipsToBounds = true
            viewLine.layer.masksToBounds = true

            viewLine.backgroundColor = UIColor.red
            scrollViewTop?.addSubview(viewLine)
            scrollViewTop?.addSubview(buttonTitle) // need to fix ... this add only first button
            buttonTitle.setTitleColor(UIColor.white, for: .normal)
        }

        /**
            creating collection views
         */
        let storyBoard = UIStoryboard(name:"Main", bundle:nil)
        let pageStripTypeViewController = storyBoard.instantiateViewController(withIdentifier: "kPageStripVC") as! FirstViewController
</code>```

<p>....</p>

答:
You need to pass the reference of the button when you create a selector so that you can compare with other buttons and change the isSelected state

buttonTitle.addTarget(self, action: #selector(ViewController.buttonTitleAction(_:)), for: .touchUpInside) //replace ViewController with your ViewController name

```<code>func buttonTitleAction(_ sender: UIButton) {
      arrayTitleButtons.forEach { (button) in
           if button == sender {
               button.isSelected = true
               sender.setTitleColor(UIColor.brown, for: .selected)
           } else {
                button.isSelected = false
           }
        }
  }
</code>```

Body:
I added number of UIButtons on scrollview programmatically based on array count, until this much its working fine. Requirement is only selected button text title color should change into brown color remain are blue.  I can’t able to solve this one please some one help using Swift 3. I need only the selected or clicked button text title color need to change remain all are in rest of the color.

           for titles in arrayPageTitles {
        var titleSize: CGSize = (titles as AnyObject).size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14.0)])
        titleSize = CGSize(width: CGFloat(ceilf(Float(titleSize.width))), height: CGFloat(ceilf(Float(titleSize.height))));

        /**
            creating top page strip tab Buttons
         */

        buttonTitle = UIButton(type: UIButtonType.custom)
        buttonTitle = UIButton(frame: CGRect(x: buttonPositionX + 5, y: 10, width: titleSize.width+40, height: (scrollViewTop?.frame.size.height)! - 20))
        buttonTitle.setTitle(titles, for: .normal)
        buttonTitle.setTitleColor(UIColor.blue, for: .normal)
        buttonTitle.setTitleColor(UIColor.white, for: .selected

        buttonTitle.clipsToBounds = true
        buttonTitle.layer.masksToBounds = true
        buttonTitle.layer.cornerRadius = 17
        buttonTitle.layer.borderWidth = 1
        buttonTitle.layer.borderColor = UIColor.darkGray.cgColor

        buttonTitle.tag = increaseIndex
        buttonTitle.addTarget(self, action: #selector(buttonTitleAction), for: .touchUpInside)

        arrayTitleButtons .add(buttonTitle)
        scrollViewTop?.addSubview(buttonTitle)
        let currentButtonX:CGFloat = buttonPositionX
        let buttonWidth:CGFloat = buttonTitle.frame.size.width
        buttonPositionX = currentButtonX + buttonWidth + 10

        if arrayPageTitles.first == titles  {

            viewLine.frame = CGRect(x: buttonTitle.frame.origin.x, y: buttonTitle.frame.origin.y, width: buttonTitle.frame.size.width, height: buttonTitle.frame.size.height)

            viewLine.layer.cornerRadius = 17
            viewLine.clipsToBounds = true
            viewLine.layer.masksToBounds = true

            viewLine.backgroundColor = UIColor.red
            scrollViewTop?.addSubview(viewLine)
            scrollViewTop?.addSubview(buttonTitle) // need to fix ... this add only first button
            buttonTitle.setTitleColor(UIColor.white, for: .normal)
        }

        /**
            creating collection views
         */
        let storyBoard = UIStoryboard(name:"Main", bundle:nil)
        let pageStripTypeViewController = storyBoard.instantiateViewController(withIdentifier: "kPageStripVC") as! FirstViewController

....

Body:
You need to pass the reference of the button when you create a selector so that you can compare with other buttons and change the isSelected state

buttonTitle.addTarget(self, action: #selector(ViewController.buttonTitleAction(_:)), for: .touchUpInside) //replace ViewController with your ViewController name

func buttonTitleAction(_ sender: UIButton) {
      arrayTitleButtons.forEach { (button) in
           if button == sender {
               button.isSelected = true
               sender.setTitleColor(UIColor.brown, for: .selected)
           } else {
                button.isSelected = false
           }
        }
  }


问:
OutOfMemoryException when using SQL Filestream
I'm trying to upload a zip file which is around 600 MB to SQL 2008 FILESTREAM table and I get the OutOfMemoryException. I'm using the SqlFileStream class to upload the file (as described in this tutorial - http://www.aghausman.net/dotnet/saving-and-retrieving-file-using-filestream-sql-server-2008.html). I have a 32-bit Vista machine with 4GB ram if that matters and I'm using VS 2010, Entity Framework 4.

Here's my code snippet -

```<code>public static void AddItem(RepositoryFile repository)
    {
        var contents = repository.Data; // I get the exception at this line.
        repository.Data = System.Text.Encoding.ASCII.GetBytes("0x00");

        using (var scope = new TransactionScope())
        {
            using (var db = new MyEntities())
            {
                db.RepositoryTable.AddObject(repository);
                db.SaveChanges();
            }

            using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            using (var cmd = new SqlCommand("SELECT Data.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() FROM dbo.RepositoryTable", con))
            {
                cmd.Connection.Open();
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var path = reader.GetString(0);
                        var transactionContext = reader.GetSqlBytes(1).Buffer;
                        var fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write);

                        fileStream.Write(contents, 0, contents.Length);
                        fileStream.Close();
                    }
                }
            }

            scope.Complete();
        }
    }
</code>```

How do I upload the file without any errors?

Thanks!

答: Knowing where exactly the error is happening could go a long way in helping to find the solution.  One change to make that may help is to chunk the file writing (don't write it all at once, loop and write a little bit at a time).  This gives the stream a chance to flush and therefore release system resources.</p>

Body:
I'm trying to upload a zip file which is around 600 MB to SQL 2008 FILESTREAM table and I get the OutOfMemoryException. I'm using the SqlFileStream class to upload the file (as described in this tutorial - http://www.aghausman.net/dotnet/saving-and-retrieving-file-using-filestream-sql-server-2008.html). I have a 32-bit Vista machine with 4GB ram if that matters and I'm using VS 2010, Entity Framework 4.

Here's my code snippet -

public static void AddItem(RepositoryFile repository)
    {
        var contents = repository.Data; // I get the exception at this line.
        repository.Data = System.Text.Encoding.ASCII.GetBytes("0x00");

        using (var scope = new TransactionScope())
        {
            using (var db = new MyEntities())
            {
                db.RepositoryTable.AddObject(repository);
                db.SaveChanges();
            }

            using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            using (var cmd = new SqlCommand("SELECT Data.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() FROM dbo.RepositoryTable", con))
            {
                cmd.Connection.Open();
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var path = reader.GetString(0);
                        var transactionContext = reader.GetSqlBytes(1).Buffer;
                        var fileStream = new SqlFileStream(path, transactionContext, FileAccess.Write);

                        fileStream.Write(contents, 0, contents.Length);
                        fileStream.Close();
                    }
                }
            }

            scope.Complete();
        }
    }

How do I upload the file without any errors?

Thanks!


问:
Read array of objects and output values by given conditions in JavaScript
Here is the problem:

Client wants to buy 2 same name PCs both color white or black with the total price less than 1600. Write a JavaScript program that would read given array var pcs and would find him the best offers.

var pcs = [
 { "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
 { "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
 { "model":"toshiba", "price":256, "color":{"mėlyna":3,"green":1} },
 { "model":"dell", "price":697, "color":{"black":1,"white":2} },
 { "model":"acer", "price":620, "color":{"black":4,"white":2} },
 { "model":"apple", "price":2560, "color":{"white":3,"black":1} },
 { "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
],
    PC,
    Collors,
    offer = "Offers: " + "\n";

for (var i = 0; i < pcs.length; i++) {
    PC = pcs[i];
    Collors = Object.keys(PC.color);

    if ((((PC.price) * 2) <= 1600) && (PC.color.black >= 2 || PC.color.white >= 2)) {

        for ( var j = 0; j < Collors.length; j++) {

            if ((PC.color.black >= 2) && (PC.color.white >= 2)) {

            offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
            + "Collors: " + Collors[0] + " and " + Collors[1] + "\n";
            }

            else if (((PC.color.black >= 2) && (Collors[j] === "black"))) {

            offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
                + "Collors: " + Collors[j] + "\n";
            }

            else if (((PC.color.white >= 2) && (Collors[j] === "white"))) {

            offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
            + "Collors: " + Collors[j] + "\n";
            }
        }
    }
}

console.log(offer);```

Written code find the best offers, but could someone tell why acer in the output duplicates itself and how is possible to repair it?

Many thanks for all help,

答:
Code to solve problem to get required output in console.

var pcs = [
 { "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
 { "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
 { "model":"toshiba", "price":256, "color":{"mėlyna":3,"green":1} },
 { "model":"dell", "price":697, "color":{"black":1,"white":2} },
 { "model":"acer", "price":620, "color":{"black":4,"white":2} },
 { "model":"apple", "price":2560, "color":{"white":3,"black":1} },
 { "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
];

for (var i=0; i < pcs.length; i++) {

    if((pcs[i].color.black >=2 || pcs[i].color.white >=2) && pcs[i].price *2 <=1600){
       //console.log (pcs[i]);

        var colors = Object.keys(pcs[i].color),
            color = '';
        for(var j = 0; j < colors.length; j++){

            if ((pcs[i].color.black >= 2 && colors[j] === "black") ||
                (pcs[i].color.white >= 2 && colors[j] === "white" )) {

                if (color.length > 0) {
                    color += ' and ' + colors[j];
                    } else {
                            color = colors[j];
                    }

                }
        }

        console.log('Model: ' + pcs[i].model + '\nPrice: ' + pcs[i].price*2 + '\nSpalvos: ' + color);

    }
}```

Body:
Here is the problem:

Client wants to buy 2 same name PCs both color white or black with the total price less than 1600. Write a JavaScript program that would read given array var pcs and would find him the best offers.

var pcs = [
 { "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
 { "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
 { "model":"toshiba", "price":256, "color":{"mėlyna":3,"green":1} },
 { "model":"dell", "price":697, "color":{"black":1,"white":2} },
 { "model":"acer", "price":620, "color":{"black":4,"white":2} },
 { "model":"apple", "price":2560, "color":{"white":3,"black":1} },
 { "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
],
    PC,
    Collors,
    offer = "Offers: " + "\n";

for (var i = 0; i < pcs.length; i++) {
    PC = pcs[i];
    Collors = Object.keys(PC.color);

    if ((((PC.price) * 2) <= 1600) && (PC.color.black >= 2 || PC.color.white >= 2)) {

        for ( var j = 0; j < Collors.length; j++) {

            if ((PC.color.black >= 2) && (PC.color.white >= 2)) {

            offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
            + "Collors: " + Collors[0] + " and " + Collors[1] + "\n";
            }

            else if (((PC.color.black >= 2) && (Collors[j] === "black"))) {

            offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
                + "Collors: " + Collors[j] + "\n";
            }

            else if (((PC.color.white >= 2) && (Collors[j] === "white"))) {

            offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
            + "Collors: " + Collors[j] + "\n";
            }
        }
    }
}

console.log(offer);

Written code find the best offers, but could someone tell why acer in the output duplicates itself and how is possible to repair it?

Many thanks for all help,


问:
codeigniter session destroy two different application
For example i am using two admin panel.Once I destroy all session value through one admin panel, another one admin session value also will destroyed . I am using unset and session_destroy for both admin panel. Is this any way to prevent one another

答: use tow different sessions for admin panels and unset the particular admin session data instead of destroying all session data.</p>


问:
Calendar info using confluence API
I have a Confluence page which has a Calendar inside it (please check photo below).
Calendar
 I am trying to pull information from this calendar, like how many events in each day. nothing more.

i used a code from stackoverflow that reads Confluence page using API. but the json response does not contain any data about the calendar inside the page.

```<code>`import requests
import json
from requests.auth import HTTPDigestAuth
confluence_host = "https://confluence.tools.mycompany.com"
url = confluence_host + '/rest/api/content/'
page_id = "36013799"
page = requests.get(url=url + page_id,
                       params={'expand': 'body.storage'},
                   auth=('my_user', 'my_password') ).json()`
</code>```

Even if i write,  html = page['body']['storage']['value'] and check its output, it only gives this:

name="calendar" ac:schema-version="1" ac:macro-id="99a26d73-abaa-45a1-92cc-0edafec567f5">72da4ae5-4888-46dd-9078-0299b51ab815,743a55b4-7b3b-4e00-b102-90d95916de8d

Is there any way to get the calendar info ?

Thanks

答: You are using Team Calendar in your page and Team Calendar is a plugin in your page. Technically, /rest/api/content only gives you the content of the page not the Content of the Plugins. As far as I know, Team Calendar doesn't have Public Rest API as you can see on CONFSERVER-51323 but you can get the data that you want from the database instead of REST API since Team Calendar has already creates couple of AO Tables in your database.

Title: Calendar info using confluence API

Body:
I have a Confluence page which has a Calendar inside it (please check photo below).
Calendar
 I am trying to pull information from this calendar, like how many events in each day. nothing more.

i used a code from stackoverflow that reads Confluence page using API. but the json response does not contain any data about the calendar inside the page.

`import requests
import json
from requests.auth import HTTPDigestAuth
confluence_host = "https://confluence.tools.mycompany.com"
url = confluence_host + '/rest/api/content/'
page_id = "36013799"
page = requests.get(url=url + page_id,
                       params={'expand': 'body.storage'},
                   auth=('my_user', 'my_password') ).json()`

Even if i write,  html = page['body']['storage']['value'] and check its output, it only gives this:

name="calendar" ac:schema-version="1" ac:macro-id="99a26d73-abaa-45a1-92cc-0edafec567f5">72da4ae5-4888-46dd-9078-0299b51ab815,743a55b4-7b3b-4e00-b102-90d95916de8d

Is there any way to get the calendar info ?

Thanks


问:
Too few parameters: the query defines 1 parameters but you only bound 0
Symfony Version 3.2.8

I am unsure what is causing this error, according to Doctrine Documentation the setParameter function is being used correctly?

Broken Code:

```<code>public function getNewShipChoices($uid, $fid) {
        /*Identify ships all ready added in fleet and do not allow them to be added again*/
        $q2 = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = :uid')->setParameter('uid', $uid)
                    ->andWhere('c2.fleetId = :fid')->setParameter('fid', $fid);

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $q2->getDQL()))->andWhere('c3.userid = :uid')->setParameter('uid', $uid);

        return $query->getQuery()->getResult();
    }
</code>```

Another thing I tried was to hard code the setParameter values, which brings the same error message

```<code> ->where('c.userid = :uid')->setParameter('uid', 1)
                            ->andWhere('c2.fleetId = :fid')->setParameter('fid', 1);
</code>```

Working Code:
Replacing the setParameter with hard coded values instead of passing in 2 integer values of 1 and 1 works fine.

```<code> public function getNewShipChoices($uid, $fid) {
        $q2 = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = 1')
                    ->andWhere('c2.fleetId = 1');

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $q2->getDQL()))->andWhere('c3.userid = 1');

        return $query->getQuery()->getResult();
    }
</code>```

Did I miss something completely obvious?

答:
Why not trying setParameters instead of setParameter ? </p>

```<code>$q2 = $this->createQueryBuilder('c')
->select('DISTINCT (c2.shipId)')
->join('AppBundle:ShipsFleet', 'c2')
->where('c.userid = :uid')
->andWhere('c2.fleetId = :fid')
->setParameters(['fid'=> $fid,'uid'=> $uid]);
</code>```

Body:
Symfony Version 3.2.8

I am unsure what is causing this error, according to Doctrine Documentation the setParameter function is being used correctly?

Broken Code:

public function getNewShipChoices($uid, $fid) {
        /*Identify ships all ready added in fleet and do not allow them to be added again*/
        $q2 = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = :uid')->setParameter('uid', $uid)
                    ->andWhere('c2.fleetId = :fid')->setParameter('fid', $fid);

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $q2->getDQL()))->andWhere('c3.userid = :uid')->setParameter('uid', $uid);

        return $query->getQuery()->getResult();
    }

Another thing I tried was to hard code the setParameter values, which brings the same error message

 ->where('c.userid = :uid')->setParameter('uid', 1)
                            ->andWhere('c2.fleetId = :fid')->setParameter('fid', 1);

Working Code:
Replacing the setParameter with hard coded values instead of passing in 2 integer values of 1 and 1 works fine.

 public function getNewShipChoices($uid, $fid) {
        $q2 = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = 1')
                    ->andWhere('c2.fleetId = 1');

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $q2->getDQL()))->andWhere('c3.userid = 1');

        return $query->getQuery()->getResult();
    }

Did I miss something completely obvious?

Body:
Why not trying setParameters instead of setParameter ?

$q2 = $this->createQueryBuilder('c')
->select('DISTINCT (c2.shipId)')
->join('AppBundle:ShipsFleet', 'c2')
->where('c.userid = :uid')
->andWhere('c2.fleetId = :fid')
->setParameters(['fid'=> $fid,'uid'=> $uid]);


问:
Angular throwing error on my html <ul> tag and as well as my *ng
I'm using atom and my ul and  *ngFor is getting an error and I don't understand why. I tried search around but can't seem to find out the reason why I get errors on all *ng stuff as well as my ul. Seems to be html tags aren't appearing. </p>

```<code>    import { Component } from '@angular/core';

@Component({
  selector: 'user',
  template: `<h1>Hello {{name}}</h1>
            <p><strong>Email</strong>: {{email}}</p>
            <p>Address:{{address.street}} {{address.city}}, {{address.state}}</p>
            <button (click) = "toggleHobbies()">Show Hobbies</button>
            <div *ngIf = 'showHobbies'>
            <h3>Hobbies</h3>
              <ul>
                  <li *ngFor="let hobby of hobbies">
                      {{hobby}}
                  </li>
              </ul>
            </div>
            `,
})
export class UserComponent  {
  name: string;
  email: string;
  address : address;
  hobbies: string[];
  showHobbies: boolean;

constructor(){
        this.name = 'Richard';
        this.email = 'Rjime061@fiu.edu'
        this.address = {
          street : '12 Main St.',
          city : 'Boston',
          state : 'MA'
        }
    }
        this.hobbies = ['Music', 'Movies', 'Sports'];
        this.showHobbies = false;
}
interface address {
    street: string;
    city: string;
    state: string;
}
</code>```

答:
You have closed the DIV just before *ngIf, which is causing this errors.

Please try following correct version of the code:

```<code>@Component({
      selector: 'user',
      template: `<h1>Hello {{name}}</h1>
                <p><strong>Email</strong>: {{email}}</p>
                <p>Address:{{address.street}} {{address.city}}, {{address.state}}</p>
                <button (click) = "toggleHobbies()">Show Hobbies</button>
        <div *ngIf = 'showHobbies'>
        <h3>Hobbies</h3>
          <ul>
              <li *ngFor="let hobby of hobbies">
                  {{hobby}}
              </li>
          </ul>
        </div>
        `,
})
</code>```

I have made changes in the line no. 7 of the code.

Body:
I'm using atom and my ul and  *ngFor is getting an error and I don't understand why. I tried search around but can't seem to find out the reason why I get errors on all *ng stuff as well as my ul. Seems to be html tags aren't appearing.

    import { Component } from '@angular/core';

@Component({
  selector: 'user',
  template: `
Hello {{name}}

Email: {{email}}

Address:{{address.street}} {{address.city}}, {{address.state}}

            <button (click) = "toggleHobbies()">Show Hobbies</button>

Hobbies

                      {{hobby}}

            `,
})
export class UserComponent  {
  name: string;
  email: string;
  address : address;
  hobbies: string[];
  showHobbies: boolean;

constructor(){
        this.name = 'Richard';
        this.email = 'Rjime061@fiu.edu'
        this.address = {
          street : '12 Main St.',
          city : 'Boston',
          state : 'MA'
        }
    }
        this.hobbies = ['Music', 'Movies', 'Sports'];
        this.showHobbies = false;
}
interface address {
    street: string;
    city: string;
    state: string;
}

Body:
You have closed the DIV just before *ngIf, which is causing this errors.

Please try following correct version of the code:

@Component({
      selector: 'user',
      template: `<h1>Hello {{name}}</h1>
                <p><strong>Email</strong>: {{email}}</p>
                <p>Address:{{address.street}} {{address.city}}, {{address.state}}</p>
                <button (click) = "toggleHobbies()">Show Hobbies</button>
        <div *ngIf = 'showHobbies'>
        <h3>Hobbies</h3>
          <ul>
              <li *ngFor="let hobby of hobbies">
                  {{hobby}}
              </li>
          </ul>
        </div>
        `,
})

I have made changes in the line no. 7 of the code.


问:
Express Generator Without Jade
I am trying to generate an express skeleton, using the express generator.
So it would be this:

```<code>$ npm install express-generator -g
</code>```

However, it adds a bunch of automatic jade files.

I was wondering if there was a way to get rid of those jade files and just using html with the express generator

Thanks!

答:
You can also directly include your html file into your jade file</p>

```<code>include ../../public/index.html
</code>```

Title: Express Generator Without Jade

Body:
I am trying to generate an express skeleton, using the express generator.
So it would be this:

$ npm install express-generator -g

However, it adds a bunch of automatic jade files.

I was wondering if there was a way to get rid of those jade files and just using html with the express generator

Thanks!

Body:
You can also directly include your html file into your jade file

include ../../public/index.html


问:
C# selecting data from a SQL database
Having problems selecting data from my database, any clue as to what is wrong as I've been staring at this for for a solid 2 hours.... (have made a login system to which can write and use data but can't search for it)

答:
Few things to consider here:

DO NOT paste screenshots, copy/paste your code. It will be easier to read, easier to copy and to index for other SO users.

DO NOT concatenate strings as SQL commands, use parameters

You have syntax error, your WHERE shoud be like WHERE Item = '" + textbox.Text + "'";

Correct way to query database is to make parameterized query, like this:

```<code>SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
cmd.Connection = search;
cmd.CommandText = "SELECT * FROM [Table] WHERE Item = @item";
cmd.Parameters.Add("@item", SqlDbType.NVarChar).Value = txtLogin.Text;

sda.SelectCommand = cmd;
</code>```

[Table] and Item should be real table name and column names from table you're trying to select data from.
I'm guessing that in your case select should be something like SELECT * FROM [Users] where Username = ...

Title: C# selecting data from a SQL database

Body:
Few things to consider here:

DO NOT paste screenshots, copy/paste your code. It will be easier to read, easier to copy and to index for other SO users.

DO NOT concatenate strings as SQL commands, use parameters

You have syntax error, your WHERE shoud be like WHERE Item = '" + textbox.Text + "'";

Correct way to query database is to make parameterized query, like this:

SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
cmd.Connection = search;
cmd.CommandText = "SELECT * FROM [Table] WHERE Item = @item";
cmd.Parameters.Add("@item", SqlDbType.NVarChar).Value = txtLogin.Text;

sda.SelectCommand = cmd;

[Table] and Item should be real table name and column names from table you're trying to select data from.
I'm guessing that in your case select should be something like SELECT * FROM [Users] where Username = ...


答:
try this code</p>

```<code>  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <EditText
        android:id="@+id/edit2"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:textAlignment="center"
        android:layout_centerInParent="true" />

</RelativeLayout>
</code>```

Title: Can't center a View in an activity in XML (Android)

Body:
I have created a new (second) activity in my android app, and right now there is one view in the content_area_reduction.xml (EditText). The file looks like this:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.myname.appname.AreaReductionActivity"
    tools:showIn="@layout/activity_area_reduction">

        <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>

</RelativeLayout>

The problem is, the view appears on the left of the screen instead of center. How do I fix this issue? Will post more code if needed.

Thank you

Body:
try this code

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <EditText
        android:id="@+id/edit2"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:textAlignment="center"
        android:layout_centerInParent="true" />

</RelativeLayout>


问:
Convert & sort javascript array numerically using non-numeric key
I have a JS array in following structure:

```<code>Array(
    [0] => Array(
        reference : "8926"
        name : "xyz1"
        id_product : "78"
    )
    [1] => Array(
        reference : "11588"
        name : "xyz2"
        id_product : "21"
    )
    [2] => Array(
        reference : "119"
        name : "xyz3"
        id_product : "135"
    )
)
</code>```

I needed to sort this array using the reference key, I have done it using multisort function;

But the problem is : even though reference is numeric but in the array structure it is defined as string and hence instead of sorting like:
119, 8926, 11588 it is sorting it like 11588 119 8926, i.e., like string.

I cannot re-structure the array because I receive it through an API, is there anyway to sort it numerically without having to recreate it in numeric data type separately (because I have to pass the array forward in same format & hence double-conversion will make the script hectic)?

PS - Current sorting (non-numeric) is done using this function.

答:
You can convert both parameters from string to number using unary plus + operator inside sort() function.

var data = [{"reference":"8926","name":"xyz1","id_product":"78"},{"reference":"11588","name":"xyz2","id_product":"21"},{"reference":"119","name":"xyz3","id_product":"135"}]

data.sort((a, b) => +a.reference - +b.reference);
console.log(data)```

Body:
I have a JS array in following structure:

Array(
    [0] => Array(
        reference : "8926"
        name : "xyz1"
        id_product : "78"
    )
    [1] => Array(
        reference : "11588"
        name : "xyz2"
        id_product : "21"
    )
    [2] => Array(
        reference : "119"
        name : "xyz3"
        id_product : "135"
    )
)

I needed to sort this array using the reference key, I have done it using multisort function;

But the problem is : even though reference is numeric but in the array structure it is defined as string and hence instead of sorting like:
119, 8926, 11588 it is sorting it like 11588 119 8926, i.e., like string.

I cannot re-structure the array because I receive it through an API, is there anyway to sort it numerically without having to recreate it in numeric data type separately (because I have to pass the array forward in same format & hence double-conversion will make the script hectic)?

PS - Current sorting (non-numeric) is done using this function.


问:
Learning Netsuite
I am starting to learn Netsuite, since that is required for our New project.
I am completely new to it. Currently I am working on PHP.

As suggested by my manager I created the developer account on it. But I have no Idea about It. So if someone can spare to answer my below questions than I will be very greatful.

Do i need to learn JavaScript for that?

Is here any other technology that will be needed ?

Are there any free webresources that can give me the insight on this?

How long will it take to learn netsuite once My javascript is done?

Thanks in advance.
Glad

答:
Yes you need only basic information about javascript. We are using here suitescript language. you are already familier with programming so it will not be difficult for you.

For integration purpose you may be need.

May be.

It will take hardly 1 month. First you learn manual , later you start coding. It will helpful for you.

Title: Learning Netsuite


问:
How to make a file into dictionary
There are two different files that is opened in the code.
1. 'file.txt' file looks like this:

```<code>33,80,71,180
280,80,260,45,240,80
200,100,119,41,150,136,181,41,100,100
75,50,87,28,75,6,50,6,37,28,49,50
</code>```

The 'colours.txt' file looks like this:

```<code>2:red
3:orange
5:yellow
6:green
</code>```

My current code below:

```<code>def create_colours_dictionary(filename):
    colour_dict = {}
    file = open('colours.txt', "r")
    for line in file:
            (key, value) = line.split(":")
            colour_dict[int(key.strip())] = value.strip()
    file.close()
    return colour_dict

def read_coordinates(filename, shapes_dict):
    file = open('file.txt', 'r')
    file_dict = {}
    for line in file:
            (value) = line.split()
            file_dict[line] = [value]

    print('')

def main():
    colours_dict = create_colours_dictionary('colours.txt')
    print(colours_dict)

    shapes_dict = {}
    for key in colours_dict.keys():
        shapes_dict[key] = []
    for filename in filenames_list:
        read_coordinates(filename, shapes_dict)
    print(shapes_dict)

main()
</code>```

What i expected to have for the out put is:

```<code>{2: 'red', 3: 'orange', 5: 'yellow', 6: 'green'}

{2: [['33', '80', '71', '180']], 3: [['280', '80', '260', '45', '240', '80']],
5: [['200', '100', '119', '41', '150', '136', '181', '41', '100', '100']],
6: [['75', '50', '87', '28', '75', '6', '50', '6', '37', '28', '49', '50']]}
</code>```

How to get the correct output for the second part?

Thank S!

答:
What are you expecting your keys to be for the second dictionary? Your example output showed the same keys as your color dictionary. I'm guessing you actually want the line number (assuming starting at '1') to be the key?

Also, why would you do you want your values to be list of lists rather than just a list of the provided numbers?

Title: How to make a file into dictionary

Body:
There are two different files that is opened in the code.
1. 'file.txt' file looks like this:

33,80,71,180
280,80,260,45,240,80
200,100,119,41,150,136,181,41,100,100
75,50,87,28,75,6,50,6,37,28,49,50

The 'colours.txt' file looks like this:

2:red
3:orange
5:yellow
6:green

My current code below:

def create_colours_dictionary(filename):
    colour_dict = {}
    file = open('colours.txt', "r")
    for line in file:
            (key, value) = line.split(":")
            colour_dict[int(key.strip())] = value.strip()
    file.close()
    return colour_dict

def read_coordinates(filename, shapes_dict):
    file = open('file.txt', 'r')
    file_dict = {}
    for line in file:
            (value) = line.split()
            file_dict[line] = [value]

    print('')

def main():
    colours_dict = create_colours_dictionary('colours.txt')
    print(colours_dict)

    shapes_dict = {}
    for key in colours_dict.keys():
        shapes_dict[key] = []
    for filename in filenames_list:
        read_coordinates(filename, shapes_dict)
    print(shapes_dict)

main()

What i expected to have for the out put is:

{2: 'red', 3: 'orange', 5: 'yellow', 6: 'green'}

{2: [['33', '80', '71', '180']], 3: [['280', '80', '260', '45', '240', '80']],
5: [['200', '100', '119', '41', '150', '136', '181', '41', '100', '100']],
6: [['75', '50', '87', '28', '75', '6', '50', '6', '37', '28', '49', '50']]}

How to get the correct output for the second part?

Thank S!


问:
“this” keyword doesn’t seem to work
I am trying to understand how the this keyword works in JavaScript and I made this script:

```<code>function click(){
    this.innerHTML="changed";
}
</code>```

Used in this HTML:

```<code><button id="clicker" onclick="click()" >Click me</button>
</code>```

But it doesn't work, can anyone explain why?

答:
You function click doesn't know about 'this'. Change it to:

```<code>function click(elemenet){
    element.innerHTML="changed";
}
</code>```

and

```<code><button id="clicker" onclick="click(this)" >Click me</button>
</code>```

Title: “this” keyword doesn’t seem to work

Body:
I am trying to understand how the this keyword works in JavaScript and I made this script:

function click(){
    this.innerHTML="changed";
}

Used in this HTML:

<button id="clicker" onclick="click()" >Click me</button>

But it doesn't work, can anyone explain why?

Body:
You function click doesn't know about 'this'. Change it to:

function click(elemenet){
    element.innerHTML="changed";
}

and

<button id="clicker" onclick="click(this)" >Click me</button>


问:
POST method is not set
During debug, I realize that all the request property and method I set is not executed at all. Can anyone explain why?

Because of this, whenever I request an output from URLConnection, that line will create a runtime error.

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        url = new URL("https://ussouthcentral.services.azureml.net/workspaces/80b0369fe0df48308d956e2ddce52806/services/6379155db28f4c91b84e78d268a927f9/execute?api-version=2.0&format=swagger");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        urlConnection = (URLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
       // urlConnection.setRequestMethod("POST");

        String api_key = "Bearer api_key";
        urlConnection.setDoInput(true);

        urlConnection.addRequestProperty("Authorization", api_key);
        urlConnection.addRequestProperty("Content-Type", "application/json");
        urlConnection.addRequestProperty("Accept", "application/json");
         } catch (IOException e) {
        e.printStackTrace();
    }

   try {
        urlConnection.connect();
        urlConnection.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

答:
sending a network request in Activity.onCreate will crash your app with a NetworkOnMainThreadException, you should never do that

I strongly suggest using other networking libraries which will take care of most of the things you're struggling with here such as OkHttp, Volley or Retrofit

Title: POST method is not set

Body:
During debug, I realize that all the request property and method I set is not executed at all. Can anyone explain why?

Because of this, whenever I request an output from URLConnection, that line will create a runtime error.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        url = new URL("https://ussouthcentral.services.azureml.net/workspaces/80b0369fe0df48308d956e2ddce52806/services/6379155db28f4c91b84e78d268a927f9/execute?api-version=2.0&format=swagger");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    try {
        urlConnection = (URLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
       // urlConnection.setRequestMethod("POST");

        String api_key = "Bearer api_key";
        urlConnection.setDoInput(true);

        urlConnection.addRequestProperty("Authorization", api_key);
        urlConnection.addRequestProperty("Content-Type", "application/json");
        urlConnection.addRequestProperty("Accept", "application/json");
         } catch (IOException e) {
        e.printStackTrace();
    }

   try {
        urlConnection.connect();
        urlConnection.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }