Programs & Examples On #Beforenavigate2

Fires before navigation occurs in the given object (on either a window element or a frameset element).

How to check if all of the following items are in a list?

This was what I was searching online but unfortunately found not online but while experimenting on python interpreter.

>>> case  = "caseCamel"
>>> label = "Case Camel"
>>> list  = ["apple", "banana"]
>>> (case or label) in list
>>> list = ["apple", "caseCamel"]
>>> (case or label) in list
>>> (case and label) in list
>>> list = ["case", "caseCamel", "Case Camel"]
>>> (case and label) in list

and if you have a looong list of variables held in a sublist variable

>>> list  = ["case", "caseCamel", "Case Camel"]
>>> label = "Case Camel"
>>> case  = "caseCamel"
>>> sublist = ["unique banana", "very unique banana"]
>>> # example for if any (at least one) item contained in superset (or statement)
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
>>> sublist[0] = label
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)
>>> # example for whether a subset (all items) contained in superset (and statement)
>>> # a bit of demorgan's law
>>> next((False for item in sublist if item not in list), True)
>>> sublist[1] = case
>>> next((False for item in sublist if item not in list), True)
>>> next((True for item in sublist if next((True for x in list if x == item), False)), False)

How do I send a file in Android from a mobile device to server using http?

Easy, you can use a Post request and submit your file as binary (byte array).

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(
            new FileInputStream(file), -1);
    reqEntity.setChunked(true); // Send in multiple parts if needed
    HttpResponse response = httpclient.execute(httppost);
    //Do something with response...

} catch (Exception e) {
    // show error

How to blur background images in Android

You can quickly get to blur effect by doing the following.

// Add this to build.gradle app //

Compile ' com.github.jgabrielfreitas:BlurImageView:1.0.1 '

// Add to XML


//Add this to java

Import com.jgabrielfreitas.core.BlueImageView;

// Under public class *activity name * //

BlurImageView myBlurImage;

// Under Oncreate//

myBlurImage = (ImageView) findViewById(

I hope that helps someone

Warning: #1265 Data truncated for column 'pdd' at row 1

As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)


Following your comment, I run a test table:

mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)


mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)


So, aparently you want to insert a NULL value to pdd field as your comment states ? You can do that in 2 ways like this:

Method 1:

mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)

Method 2:

mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)


You failed to change the default value of pdd field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)

mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3  Duplicates: 0  Warnings: 1

How to prevent page scrolling when scrolling a DIV element?

see if this help you:

demo: jsfiddle

$('#notscroll').bind('mousewheel', function() {
     return false


try this:

    $("body").delegate("div.scrollable","mouseover mouseout", function(e){
       if(e.type === "mouseover"){
               return false;
       }else if(e.type === "mouseout"){
               return true;

How to Convert JSON object to Custom C# object?

To keep your options open, if you're using .NET 3.5 or later, here is a wrapped up example you can use straight from the framework using Generics. As others have mentioned, if it's not just simple objects you should really use

public static string Serialize<T>(T obj)
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.UTF8.GetString(ms.ToArray());
    return retVal;

public static T Deserialize<T>(string json)
    T obj = Activator.CreateInstance<T>();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    return obj;

You'll need:

using System.Runtime.Serialization;

using System.Runtime.Serialization.Json;

Best way to remove items from a collection

For a simple List structure the most efficient way seems to be using the Predicate RemoveAll implementation.


 workSpace.RoleAssignments.RemoveAll(x =>x.Member.Name == shortName);

The reasons are:

  1. The Predicate/Linq RemoveAll method is implemented in List and has access to the internal array storing the actual data. It will shift the data and resize the internal array.
  2. The RemoveAt method implementation is quite slow, and will copy the entire underlying array of data into a new array. This means reverse iteration is useless for List

If you are stuck implementing this in a the pre c# 3.0 era. You have 2 options.

  • The easily maintainable option. Copy all the matching items into a new list and and swap the underlying list.


List<int> list2 = new List<int>() ; 
foreach (int i in GetList())
    if (!(i % 2 == 0))
list2 = list2;


  • The tricky slightly faster option, which involves shifting all the data in the list down when it does not match and then resizing the array.

If you are removing stuff really frequently from a list, perhaps another structure like a HashTable (.net 1.1) or a Dictionary (.net 2.0) or a HashSet (.net 3.5) are better suited for this purpose.

Can I write native iPhone apps using Python?

Not currently, currently the only languages available to access the iPhone SDK are C/C++, Objective C and Swift.

There is no technical reason why this could not change in the future but I wouldn't hold your breath for this happening in the short term.

That said, Objective-C and Swift really are not too scary...

2016 edit

Javascript with NativeScript framework is available to use now.

shell init issue when click tab, what's wrong with getcwd?

This usually occurs when your current directory does not exist anymore. Most likely, from another terminal you remove that directory (from within a script or whatever). To get rid of this, in case your current directory was recreated in the meantime, just cd to another (existing) directory and then cd back; the simplest would be: cd; cd -.

Email and phone Number Validation in android

For Email Address Validation

private boolean isValidMail(String email) {

    String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    return Pattern.compile(EMAIL_STRING).matcher(email).matches();



private boolean isValidMail(String email) {
   return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();

For Mobile Validation

For Valid Mobile You need to consider 7 digit to 13 digit because some country have 7 digit mobile number. If your main target is your own country then you can match with the length. Assuming India has 10 digit mobile number. Also we can not check like mobile number must starts with 9 or 8 or anything.

For mobile number I used this two Function:

private boolean isValidMobile(String phone) {
    if(!Pattern.matches("[a-zA-Z]+", phone)) {
        return phone.length() > 6 && phone.length() <= 13;
    return false;


private boolean isValidMobile(String phone) {
    return android.util.Patterns.PHONE.matcher(phone).matches();    

C# "as" cast vs classic cast

You use the "as" statement to avoid the possibility of an exception, e.g. you can handle the cast failure gracefully via logic. Only use the cast when you are sure that the object is of the desired type. I almost always use the "as" and then check for null.

How do I convert an existing callback API to promises?

Node.js 8.0.0 includes a new util.promisify() API that allows standard Node.js callback style APIs to be wrapped in a function that returns a Promise. An example use of util.promisify() is shown below.

const fs = require('fs');
const util = require('util');

const readFile = util.promisify(fs.readFile);

  .then((data) => { /** ... **/ })
  .catch((err) => { /** ... **/ });

See Improved support for Promises

How do I import a .dmp file into Oracle?

imp system/system-password@SID file=directory-you-selected\FILE.dmp log=log-dir\oracle_load.log fromuser=infodba touser=infodba commit=Y

SQL SERVER, SELECT statement with auto generate row id

This will work in SQL Server 2008.

select  top 100 ROW_NUMBER() OVER (ORDER BY tmp.FirstName) ,* from tmp


CSS center display inline block?

Great article i found what worked best for me was to add a % to the size

.wrap {

Error Message: Type or namespace definition, or end-of-file expected

You have extra brackets in Hours property;

public  object Hours { get; set; }}

disable textbox using jquery?

I'm not sure why some of these solutions use .each() - it's not necessary.

Here's some working code that disables if the 3rd checkbox is clicked, otherwise is removes the disabled attribute.

Note: I added an id to the checkbox. Also, remember that ids must be unique in your document, so either remove the ids on the radiobuttons, or make them unique

$("input:radio[name='userradiobtn']").click(function() {
    var isDisabled = $(this).is(":checked") && $(this).val() == "3";
    $("#chkbox").attr("disabled", isDisabled);
    $("#usertxtbox").attr("disabled", isDisabled);

What does a lazy val do?

The difference between them is, that a val is executed when it is defined whereas a lazy val is executed when it is accessed the first time.

scala> val x = { println("x"); 15 }
x: Int = 15

scala> lazy val y = { println("y"); 13 }
y: Int = <lazy>

scala> x
res2: Int = 15

scala> y
res3: Int = 13

scala> y
res4: Int = 13

In contrast to a method (defined with def) a lazy val is executed once and then never again. This can be useful when an operation takes long time to complete and when it is not sure if it is later used.

scala> class X { val x = { Thread.sleep(2000); 15 } }
defined class X

scala> class Y { lazy val y = { Thread.sleep(2000); 13 } }
defined class Y

scala> new X
res5: X = X@262505b7 // we have to wait two seconds to the result

scala> new Y
res6: Y = Y@1555bd22 // this appears immediately

Here, when the values x and y are never used, only x unnecessarily wasting resources. If we suppose that y has no side effects and that we do not know how often it is accessed (never, once, thousands of times) it is useless to declare it as def since we don't want to execute it several times.

If you want to know how lazy vals are implemented, see this question.

How to open CSV file in R when R says "no such file or directory"?

I had the same problem and when I checked the properties of the file on file explorer, it shows me the next message:

"Security: This file came from another computer and might be blocked to help protect this computer"

You click on the "Unblock" button and... you can access to the file from R without any problem, just using read.csv() function and from the directory specified as your working directory, even if is not the same as the file’s directory you are accessing to.

How do I disable the security certificate check in Python requests

Use requests.packages.urllib3.disable_warnings() and verify=False on requests methods.

import requests
from urllib3.exceptions import InsecureRequestWarning

# Suppress only the single warning from urllib3 needed.

# Set `verify=False` on ``.'', data={'bar':'baz'}, verify=False)

Data access object (DAO) in Java

Pojo also consider as Model class in Java where we can create getter and setter for particular variable defined in private . Remember all variables are here declared with private modifier

git push vs git push origin <branchname>

First, you need to create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Your Teammates/colleagues can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch 

Batch file to copy files from one folder to another folder

Just to be clear, when you use xcopy /s c:\source d:\target, put "" around the c:\source and d:\target,otherwise you get error.

ie if there are spaces in the path ie if you have:

"C:\Some Folder\*.txt"

but not required if you have:


Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

            top: 0%;
            left: 0%;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            z- index must be lower than pop up box
            z-index: 99;
           //for transparency
            top: 50%;
            left: 50%;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            //on click show the hider div and the message
            $("#showpopup").click(function () {
            //on click hide the message and the
            $("#buttonClose").click(function () {

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>

    I have used jquery-1.4.1.min.js and tested the code in Firefox. Hope this helps.

  • Using openssl to get the certificate from a server
    openssl s_client -servername $HOST -connect $HOST:$PORT < /dev/null 2>/dev/null | openssl x509 -outform pem

    How to make a input field readonly with JavaScript?

    document.getElementById('TextBoxID').readOnly = true;    //to enable readonly
    document.getElementById('TextBoxID').readOnly = false;   //to  disable readonly

    Mocking a class: Mock() or patch()?

    I've got a YouTube video on this.

    Short answer: Use mock when you're passing in the thing that you want mocked, and patch if you're not. Of the two, mock is strongly preferred because it means you're writing code with proper dependency injection.

    Silly example:

    # Use a mock to test this.
    my_custom_tweeter(twitter_api, sentence):
        sentence.replace('cks','x')   # We're cool and hip.
    # Use a patch to mock out twitter_api. You have to patch the Twitter() module/class 
    # and have it return a mock. Much uglier, but sometimes necessary.
        twitter_api = Twitter(user="XXX", password="YYY")

    How to target the href to div

    From what I know this will not be possible only with css. Heres a solution how you could make it work with jQuery which is a javascript Library. More about jquery here:

    Here is a working example :

            var aID = $(this).attr('href');
            var elem = $(''+aID).html();

    Update 2018 (as this still gets upvoted) here is a plain javascript solution without jQuery

    var target = document.querySelector('.target');_x000D_
    [...document.querySelectorAll('table a')].forEach(function(element){_x000D_
        element.addEventListener('click', function(){_x000D_
            target.innerHTML = document.querySelector(element.getAttribute('href')).innerHTML;_x000D_
        border:solid black 1px; _x000D_
    #m1, #m2, #m3, #m4, #m5, #m6, #m7, #m8, #m9{_x000D_
    <table border="0">_x000D_
    <a href="#m1">fea1</a><br><hr>_x000D_
    <a href="#m2">fea2</a><br><hr>_x000D_
    <a href="#m3">fea3</a><br><hr>_x000D_
    <a href="#m4">fea4</a><br><hr>_x000D_
    <a href="#m5">fea5</a><br><hr>_x000D_
    <a href="#m6">fea6</a><br><hr>_x000D_
    <a href="#m7">fea7</a><br><hr>_x000D_
    <a href="#m8">fea8</a><br><hr>_x000D_
    <a href="#m9">fea9</a>_x000D_
    <div class="target">_x000D_
    <div id="m1">dasdasdasd</div>_x000D_
    <div id="m2">dadasdasdasd</div>_x000D_
    <div id="m3">sdasdasds</div>_x000D_
    <div id="m4">dasdasdsad</div>_x000D_
    <div id="m5">dasdasd</div>_x000D_
    <div id="m6">asdasdad</div>_x000D_
    <div id="m7">asdasda</div>_x000D_
    <div id="m8">dasdasd</div>_x000D_
    <div id="m9">dasdasdsgaswa</div>

    Basic HTML - how to set relative path to current folder?

    You can use


    to mean up one level. If you have a page called page2.html in the same folder as page.html then the relative path is:


    If you have page2.html at the same level with folder then the path is:


    convert datetime to date format dd/mm/yyyy

    this is you need and all people

       string date  = textBox1.Text;
            DateTime date2 = Convert.ToDateTime(date);
            var date3 = date2.Date;
            var D = date3.Day;
          var M =  date3.Month;         
          var y = date3.Year;
          string monthStr = M.ToString("00");
          string date4 = D.ToString() + "/" + monthStr.ToString() + "/" + y.ToString();
          textBox1.Text = date4;

    count number of rows in a data frame in R based on group

    Using the example data set that Ananda dummied up, here's an example using aggregate(), which is part of core R. aggregate() just needs something to count as function of the different values of MONTH-YEAR. In this case, I used VALUE as the thing to count:

    aggregate(cbind(count = VALUE) ~ MONTH.YEAR, 
              data = mydf, 
              FUN = function(x){NROW(x)})

    which gives you..

      MONTH.YEAR count
    1  FEB. 2012     2
    2  JAN. 2012     2
    3  MAR. 2012     1

    Change url query string value using jQuery

    purls $.params() used without a parameter will give you a key-value object of the parameters.

    jQuerys $.param() will build a querystring from the supplied object/array.

    var params = parsedUrl.param();
    delete params["page"];
    var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

    I've no idea why I used delete here...

    var params = parsedUrl.param();
    params["page"] = $(this).val();
    var newUrl = "?" + $.param(params);

    How do I search for an object by its ObjectId in the mongo console?

    If you are working on the mongo shell, Please refer this : Answer from Tyler Brock

    I wrote the answer if you are using mongodb using node.js

    You don't need to convert the id into an ObjectId. Just use :


    this collection method will automatically convert id into ObjectId.

    On the other hand :

    db.collection.findOne({"_id":'4ecbe7f9e8c1c9092c000027'}) doesn't work as expected. You've manually convert id into ObjectId.

    That can be done like this :

    let id = '58c85d1b7932a14c7a0a320d';
    let o_id = new ObjectId(id);   // id as a string is passed

    Regex for checking if a string is strictly alphanumeric

    It's 2016 or later and things have progressed. This matches Unicode alphanumeric strings:


    See the reference (section "Classes for Unicode scripts, blocks, categories and binary properties"). There's also this answer that I found helpful.

    WCF gives an unsecured or incorrectly secured fault error

    In my case I was using certificates for authentication with certificateValidationMode set to "PeerTrust" and I had forgotten to install the client certificate in windows store (LocalMachine\TrustedPeople) to make it accepted by the server.

    Non-alphanumeric list order from os.listdir()

    I think by default the order is determined with the ASCII value. The solution to this problem is this

    dir = sorted(os.listdir(os.getcwd()), key=len)

    Timing a command's execution in PowerShell

    You can also get the last command from history and subtract its EndExecutionTime from its StartExecutionTime.

    $command = Get-History -Count 1  
    $command.EndExecutionTime - $command.StartExecutionTime

    How are zlib, gzip and zip related? What do they have in common and how are they different?

    The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.

    If you have a big archive and you only need one single file out of it, you have to decompress the whole gzip file to get to that file. This is not required if you have a zip file.

    On the other hand, if you compress 10 similiar or even identical files, the zip archive will be much bigger because each file is compressed individually, whereas in gzip in combination with tar a single file is compressed which is much more effective if the files are similiar (equal).

    Which is the default location for keystore/truststore of Java applications?

    In Java, according to the JSSE Reference Guide, there is no default for the keystore, the default for the truststore is "jssecacerts, if it exists. Otherwise, cacerts".

    A few applications use ~/.keystore as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).

    I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.

    How can I extract a good quality JPEG image from a video file with ffmpeg?

    Use -qscale:v to control quality

    Use -qscale:v (or the alias -q:v) as an output option.

    • Normal range for JPEG is 2-31 with 31 being the worst quality.
    • The scale is linear with double the qscale being roughly half the bitrate.
    • Recommend trying values of 2-5.
    • You can use a value of 1 but you must add the -qmin 1 output option (because the default is -qmin 2).

    To output a series of images:

    ffmpeg -i input.mp4 -qscale:v 2 output_%03d.jpg

    See the image muxer documentation for more options involving image outputs.

    To output a single image at ~60 seconds duration:

    ffmpeg -ss 60 -i input.mp4 -qscale:v 4 -frames:v 1 output.jpg

    Also see

    How to see the changes in a Git commit?

    As mentioned in "Shorthand for diff of git commit with its parent?", you can also use git diff with:

    git diff COMMIT^!


    git diff-tree -p COMMIT

    With git show, you would need (in order to focus on diff alone) to do:

    git show --color --pretty=format:%b $COMMIT

    The COMMIT parameter is a commit-ish:

    A commit object or an object that can be recursively dereferenced to a commit object. The following are all commit-ishes: a commit object, a tag object that points to a commit object, a tag object that points to a tag object that points to a commit object, etc.

    See gitrevision "SPECIFYING REVISIONS" to reference a commit-ish.
    See also "What does tree-ish mean in Git?".

    How to switch databases in psql?

    In PostgreSQL, you can use the \connect meta-command of the client tool psql:

    \connect DBNAME

    or in short:

    \c DBNAME

    comparing elements of the same array in java

    First things first, you need to loop to < a.length rather than a.length - 1. As this is strictly less than you need to include the upper bound.

    So, to check all pairs of elements you can do:

    for (int i = 0; i < a.length; i++) {
        for (int k = 0; k < a.length; k++) {
            if (a[i] != a[k]) {
                //do stuff

    But this will compare, for example a[2] to a[3] and then a[3] to a[2]. Given that you are checking != this seems wasteful.

    A better approach would be to compare each element i to the rest of the array:

    for (int i = 0; i < a.length; i++) {
        for (int k = i + 1; k < a.length; k++) {
            if (a[i] != a[k]) {
                //do stuff

    So if you have the indices [1...5] the comparison would go

    1. 1 -> 2
    2. 1 -> 3
    3. 1 -> 4
    4. 1 -> 5
    5. 2 -> 3
    6. 2 -> 4
    7. 2 -> 5
    8. 3 -> 4
    9. 3 -> 5
    10. 4 -> 5

    So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.

    Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

    In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p

    It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

    Extract a page from a pdf as a jpeg

    The pdf2image library can be used.

    You can install it simply using,

    pip install pdf2image

    Once installed you can use following code to get images.

    from pdf2image import convert_from_path
    pages = convert_from_path('pdf_file', 500)

    Saving pages in jpeg format

    for page in pages:'out.jpg', 'JPEG')

    Edit: the Github repo pdf2image also mentions that it uses pdftoppm and that it requires other installations:

    pdftoppm is the piece of software that does the actual magic. It is distributed as part of a greater package called poppler. Windows users will have to install poppler for Windows. Mac users will have to install poppler for Mac. Linux users will have pdftoppm pre-installed with the distro (Tested on Ubuntu and Archlinux) if it's not, run sudo apt install poppler-utils.

    You can install the latest version under Windows using anaconda by doing:

    conda install -c conda-forge poppler

    note: Windows versions upto 0.67 are available at but note that 0.68 was released in Aug 2018 so you'll not be getting the latest features or bug fixes.

    Bash conditionals: how to "and" expressions? (if [ ! -z $VAR && -e $VAR ])

    I found an answer now. Thanks for your suggestions!

    for e in ./*.cutoff.txt; do
    if grep -q -E 'COX1|Cu-oxidase' $e
        echo xyz >$e.match.txt
    if grep -q -E 'AMO' $e
        echo abc >$e.match.txt
    fi; done

    Any comments on that? It seems inefficient to grep twice, but it works...

    login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

    I was stuck in same problem for many hours. I tried everything found on internet.

    At last, I figured out a surprising solution : I had missed \SQLEXPRESS part of the Server name: MY-COMPUTER-NAME\SQLEXPRESS

    I hope this helps someone who is stuck in similar kind of problem.

    XmlDocument - load from string?

    XmlDocument doc = new XmlDocument();

    Where str is your XML string. See the MSDN article for more info.

    UTF-8 output from PowerShell

    Spent some time working on a solution to my issue and thought it may be of interest. I ran into a problem trying to automate code generation using PowerShell 3.0 on Windows 8. The target IDE was the Keil compiler using MDK-ARM Essential Toolchain 5.24.1. A bit different from OP, as I am using PowerShell natively during the pre-build step. When I tried to #include the generated file, I received the error

    fatal error: UTF-16 (LE) byte order mark detected '..\GITVersion.h' but encoding is not supported

    I solved the problem by changing the line that generated the output file from:

    out-file -FilePath GITVersion.h -InputObject $result


    out-file -FilePath GITVersion.h -Encoding ascii -InputObject $result

    Local variable referenced before assignment?

    When Python parses the body of a function definition and encounters an assignment such as

    feed = ...

    Python interprets feed as a local variable by default. If you do not wish for it to be a local variable, you must put

    global feed

    in the function definition. The global statement does not have to be at the beginning of the function definition, but that is where it is usually placed. Wherever it is placed, the global declaration makes feed a global variable everywhere in the function.

    Without the global statement, since feed is taken to be a local variable, when Python executes

    feed = feed + 1,

    Python evaluates the right-hand side first and tries to look up the value of feed. The first time through it finds feed is undefined. Hence the error.

    The shortest way to patch up the code is to add global feed to the beginning of onLoadFinished. The nicer way is to use a class:

    class Page(object):
        def __init__(self):
            self.feed = 0
        def onLoadFinished(self, result):
            self.feed += 1

    The problem with having functions which mutate global variables is that it makes it harder to grok your code. Functions are no longer isolated units. Their interaction extends to everything that affects or is affected by the global variable. Thus it makes larger programs harder to understand.

    By avoiding mutating globals, in the long run your code will be easier to understand, test and maintain.

    What is the hamburger menu icon called and the three vertical dots icon called?

    For the 3 vertical dot icon, these are the most popular names

    • Kebab menu
    • More options icon

    For the remaining, here is the list.

    Picture Credit- @MichaelBabich

    WPF What is the correct way of using SVG files as icons in WPF

    We can use directly the path's code from the SVG's code:

                <PathGeometry Figures="M52.8,105l-1.9,4.1c ... 

    What is the difference between primary, unique and foreign key constraints, and indexes?

    Primary Key: identify uniquely every row it can not be null. it can not be a duplicate.

    Foreign Key: create relationship between two tables. can be null. can be a duplicate  

    how to insert datetime into the SQL Database table?

    You will need to have a datetime column in a table. Then you can do an insert like the following to insert the current date:

    INSERT INTO MyTable (MyDate) Values (GetDate())

    If it is not today's date then you should be able to use a string and specify the date format:

    INSERT INTO MyTable (MyDate) Values (Convert(DateTime,'19820626',112)) --6/26/1982

    You do not always need to convert the string either, often you can just do something like:

    INSERT INTO MyTable (MyDate) Values ('06/26/1982') 

    And SQL Server will figure it out for you.

    selecting from multi-index pandas

    Another option is:

    filter1 = df.index.get_level_values('A') == 1
    filter2 = df.index.get_level_values('B') == 4
    df.iloc[filter1 & filter2]
    A B
    1 4  1

    How to compare LocalDate instances Java 8

    I believe this snippet will also be helpful in a situation where the dates comparison spans more than two entries.

    static final int COMPARE_EARLIEST = 0;
    static final int COMPARE_MOST_RECENT = 1;
    public LocalDate getTargetDate(List<LocalDate> datesList, int comparatorType) { 
       LocalDate refDate = null;
           case COMPARE_EARLIEST:         
           //returns the most earliest of the date entries
              refDate = (LocalDate) -> 
           case COMPARE_MOST_RECENT:
              //returns the most recent of the date entries 
              refDate = (LocalDate) -> 
       return refDate;

    Find empty or NaN entry in Pandas Dataframe

    you also do something good:

    text_empty = df['column name'].str.len() > -1


    The results will be the rows which are empty & it's index number.

    What killed my process and why?

    We have had recurring problems under Linux at a customer site (Red Hat, I think), with OOMKiller (out-of-memory killer) killing both our principle application (i.e. the reason the server exists) and it's data base processes.

    In each case OOMKiller simply decided that the processes were using to much resources... the machine wasn't even about to fail for lack of resources. Neither the application nor it's database has problems with memory leaks (or any other resource leak).

    I am not a Linux expert, but I rather gathered it's algorithm for deciding when to kill something and what to kill is complex. Also, I was told (I can't speak as to the accuracy of this) that OOMKiller is baked into the Kernel and you can't simply not run it.

    Disable all table constraints in Oracle

    Use following cursor to disable all constraint.. And alter query for enable constraints...

    cursor r1 is select * from user_constraints;
    cursor r2 is select * from user_tables;
      FOR c1 IN r1
        for c2 in r2
           if c1.table_name = c2.table_name and c1.status = 'ENABLED' THEN
            dbms_utility.exec_ddl_statement('alter table ' || c1.owner || '.' || c1.table_name || ' disable constraint ' || c1.constraint_name);
           end if;
        end loop;
      END LOOP;

    Why does using from __future__ import print_function breaks Python2-style print?

    First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

    from __future__ import print_function
    import sys, os, time
    for x in range(0,10):
        print(x, sep=' ', end='')  # No need for sep here, but okay :)

    __future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

    A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

    The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

    In Java, how do I parse XML as a String instead of a file?

    javadocs show that the parse method is overloaded.

    Create a StringStream or InputSource using your string XML and you should be set.

    How to get the children of the $(this) selector?

    Ways to refer to a child in jQuery. I summarized it in the following jQuery:

    $(this).find("img"); // any img tag child or grandchild etc...   
    $(this).children("img"); //any img tag child that is direct descendant 
    $(this).find("img:first") //any img tag first child or first grandchild etc...
    $(this).children("img:first") //the first img tag  child that is direct descendant 
    $(this).children("img:nth-child(1)") //the img is first direct descendant child
    $(this).next(); //the img is first direct descendant child

    Is it possible to iterate through JSONArray?

    You can use the opt(int) method and use a classical for loop.

    Import Excel spreadsheet columns into SQL Server database

    First of all, try the 32 Bit Version of the Import Wizard. This shows a lot more supported import formats.

    Background: All depends on your Office (Runtimes Engines) installation.

    If you dont't have Office 2007 or greater installed, the Import Wizard (32 Bit) only allows you to import Excel 97-2003 (.xls) files.

    If you have the Office 2010 and geater (comes also in 64 Bit, not recommended) installed, the Import Wizard also supports Excel 2007+ (.xlsx) files.

    To get an overview on the runtimes see 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

    Producer/Consumer threads using a Queue

    Java 5+ has all the tools you need for this kind of thing. You will want to:

    1. Put all your Producers in one ExecutorService;
    2. Put all your Consumers in another ExecutorService;
    3. If necessary, communicate between the two using a BlockingQueue.

    I say "if necessary" for (3) because from my experience it's an unnecessary step. All you do is submit new tasks to the consumer executor service. So:

    final ExecutorService producers = Executors.newFixedThreadPool(100);
    final ExecutorService consumers = Executors.newFixedThreadPool(100);
    while (/* has more work */) {
    producers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    consumers.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

    So the producers submit directly to consumers.

    How to append to New Line in Node.js

    Use the os.EOL constant instead.

    var os = require("os");
    function processInput ( text ) 
    {  'H://log.txt', 'a', 666, function( e, id ) {
       fs.write( id, text + os.EOL, null, 'utf8', function(){
        fs.close(id, function(){
         console.log('file is updated');

    Add a Progress Bar in WebView

    in oncreate method where you have set your Webview.

    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    web_view = (WebView) findViewById(;
    pd = new ProgressDialog(SiteOpenInWebView.this);
        pd.setMessage("Please wait Loading...");;
        web_view.setWebViewClient(new MyWebViewClient());
        web_view.loadUrl("ur site name");


    private class MyWebViewClient extends WebViewClient {
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (!pd.isShowing()) {
        return true;
    public void onPageFinished(WebView view, String url) {
        System.out.println("on finish");
        if (pd.isShowing()) {

    EXCEL VBA Check if entry is empty or not 'space'

    Most terse version I can think of

    Len(Trim(TextBox1.Value)) = 0

    If you need to do this multiple times, wrap it in a function

    Public Function HasContent(text_box as Object) as Boolean
        HasContent = (Len(Trim(text_box.Value)) > 0)
    End Function


    If HasContent(TextBox1) Then
        ' ...

    How do I get a file's last modified time in Perl?

    You could use stat() or the File::Stat module.

    perldoc -f stat

    wampserver doesn't go green - stays orange

    click WAMP icon -> Apache -> httpd.conf and find listen 80

    new versions of WAMP uses

    Listen [::0]:80

    ServerName localhost:80

    Change Port Number as you want, like

    Listen [::0]:81

    ServerName localhost:81

    and now restart Wamp, thats it

    and in web browser type as


    Happy Coding..

    Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

    Quick answer:

            app:layout_constraintTop_toTopOf="parent" />

    Responsive Google Map?

    i think the simplest way will be to add this css and it will work perfectly.

    embed, object, iframe{max-width: 100%;}

    What's the common practice for enums in Python?

    You could probably use an inheritance structure although the more I played with this the dirtier I felt.

    class AnimalEnum:
      def verify(cls, other):
        return issubclass(other.__class__, cls)
    class Dog(AnimalEnum):
    def do_something(thing_that_should_be_an_enum):
      if not AnimalEnum.verify(thing_that_should_be_an_enum):
        raise OhGodWhy

    CSS vertical alignment text inside li

    Give this solution a try

    Works best in most of the cases

    you may have to use div instead of li for that

    .DivParent {_x000D_
        height: 100px;_x000D_
        border: 1px solid lime;_x000D_
        white-space: nowrap;_x000D_
    .verticallyAlignedDiv {_x000D_
        display: inline-block;_x000D_
        vertical-align: middle;_x000D_
        white-space: normal;_x000D_
    .DivHelper {_x000D_
        display: inline-block;_x000D_
        vertical-align: middle;_x000D_
    <div class="DivParent">_x000D_
        <div class="verticallyAlignedDiv">_x000D_
            <p>Isnt it good!</p>_x000D_
        </div><div class="DivHelper"></div>_x000D_

    How to compare two vectors for equality element by element in C++?

    C++11 standard on == for std::vector

    Others have mentioned that operator== does compare vector contents and works, but here is a quote from the C++11 N3337 standard draft which I believe implies that.

    We first look at Chapter 23.2.1 "General container requirements", which documents things that must be valid for all containers, including therefore std::vector.

    That section Table 96 "Container requirements" which contains an entry:

    Expression   Operational semantics
    ===========  ======================
    a == b       distance(a.begin(), a.end()) == distance(b.begin(), b.end()) &&
                 equal(a.begin(), a.end(), b.begin())

    The distance part of the semantics means that the size of both containers are the same, but stated in a generalized iterator friendly way for non random access addressable containers. distance() is defined at 24.4.4 "Iterator operations".

    Then the key question is what does equal() mean. At the end of the table we see:

    Notes: the algorithm equal() is defined in Clause 25.

    and in section 25.2.11 "Equal" we find its definition:

    template<class InputIterator1, class InputIterator2>
    bool equal(InputIterator1 first1, InputIterator1 last1,
               InputIterator2 first2);
    template<class InputIterator1, class InputIterator2,
    class BinaryPredicate>
    bool equal(InputIterator1 first1, InputIterator1 last1,
               InputIterator2 first2, BinaryPredicate pred);

    1 Returns: true if for every iterator i in the range [first1,last1) the following corresponding conditions hold: *i == *(first2 + (i - first1)), pred(*i, *(first2 + (i - first1))) != false. Otherwise, returns false.

    In our case, we care about the overloaded version without BinaryPredicate version, which corresponds to the first pseudo code definition *i == *(first2 + (i - first1)), which we see is just an iterator-friendly definition of "all iterated items are the same".

    Similar questions for other containers:

    How exactly to use Notification.Builder

    I was having a problem building notifications (only developing for Android 4.0+). This link showed me exactly what I was doing wrong and says the following:

    Required notification contents
    A Notification object must contain the following:
    A small icon, set by setSmallIcon()
    A title, set by setContentTitle()
    Detail text, set by setContentText()

    Basically I was missing one of these. Just as a basis for troubleshooting with this, make sure you have all of these at the very least. Hopefully this will save someone else a headache.

    Difference between <context:annotation-config> and <context:component-scan>

    <context:annotation-config/> <!-- is used to activate the annotation for beans -->
    <context:component-scan base-package="x.y.MyClass" /> <!-- is for the Spring IOC container to look for the beans in the base package. -->

    The other important point to note is that context:component-scan implicitly calls the context:annotation-config to activate the annotations on beans. Well if you don't want context:component-scan to implicitly activate annotations for you, you can go on setting the annotation-config element of the context:component-scan to false.

    To summarize:

    <context:annotation-config/> <!-- activates the annotations --> 
    <context:component-scan base-package="x.y.MyClass" /> <!-- activates the annotations + register the beans by looking inside the base-package -->

    Run a string as a command within a Bash script

    Here is my gradle build script that executes strings stored in heredocs:

    current_directory=$( realpath "." )
    build_gradle=$( realpath build.gradle )
    ## touch because .gitignore ignores this folder:
    touch $GENERATED
        gradle run

    The lone ")" are kind of ugly. But I have no clue how to fix that asthetic aspect.

    How to update maven repository in Eclipse?

    You can right-click on your project then Maven > Update Project..., then select Force Update of Snapshots/Releases checkbox then click OK.

    How do I add button on each row in datatable?

    I contribute with my settings for buttons: view, edit and delete. The last column has data: null At the end with the property defaultContent is added a string that HTML code. And since it is the last column, it is indicated with index -1 by means of the targets property when indicating the columns.

    columns: [
        { title: "", "data": null, defaultContent: '' }, //Si pone da error al cambiar de paginas la columna index con numero de fila
        { title: "Id", "data": "id", defaultContent: '', "visible":false },
        { title: "Nombre", "data": "nombre" },
        { title: "Apellido", "data": "apellido" },
        { title: "Documento", "data": "tipo_documento.siglas" },
        { title: "Numero", "data": "numero_documento" },
        { title: "Fec.Nac.", format: 'dd/mm/yyyy', "data": "fecha_nacimiento"}, //formato
        { title: "Teléfono", "data": "telefono1" },
        { title: "Email", "data": "email1" }
        , { title: "", "data": null }
    columnDefs: [
            "searchable": false,
            "orderable": false,
            "targets": 0
          width: '3%', 
          targets: 0  //la primer columna tendra una anchura del  20% de la tabla
            targets: -1, //-1 es la ultima columna y 0 la primera
            data: null,
            defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info btn-xs dt-view" style="margin-right:16px;"><span class="glyphicon glyphicon-eye-open glyphicon-info-sign" aria-hidden="true"></span></button>  <button type="button" class="btn btn-primary btn-xs dt-edit" style="margin-right:16px;"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button><button type="button" class="btn btn-danger btn-xs dt-delete"><span class="glyphicon glyphicon-remove glyphicon-trash" aria-hidden="true"></span></button></div>'
        { orderable: false, searchable: false, targets: -1 } //Ultima columna no ordenable para botones

    enter image description here

    Align button at the bottom of div using CSS

    Parent container has to have this:

    position: relative;

    Button itself has to have this:

    position: relative;
    bottom: 20px;
    right: 20px;

    or whatever you like

    Collections.sort with multiple fields

    This is an old question so I don't see a Java 8 equivalent. Here is an example for this specific case.

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
     * Compares multiple parts of the Report object.
    public class SimpleJava8ComparatorClass {
        public static void main(String[] args) {
            List<Report> reportList = new ArrayList<>();
            reportList.add(new Report("reportKey2", "studentNumber2", "school1"));
            reportList.add(new Report("reportKey4", "studentNumber4", "school6"));
            reportList.add(new Report("reportKey1", "studentNumber1", "school1"));
            reportList.add(new Report("reportKey3", "studentNumber2", "school4"));
            reportList.add(new Report("reportKey2", "studentNumber2", "school3"));
            Collections.sort(reportList, Comparator.comparing(Report::getReportKey)
        private static class Report {
            private String reportKey;
            private String studentNumber;
            private String school;
            public Report(String reportKey, String studentNumber, String school) {
                this.reportKey = reportKey;
                this.studentNumber = studentNumber;
       = school;
            public String getReportKey() {
                return reportKey;
            public void setReportKey(String reportKey) {
                this.reportKey = reportKey;
            public String getStudentNumber() {
                return studentNumber;
            public void setStudentNumber(String studentNumber) {
                this.studentNumber = studentNumber;
            public String getSchool() {
                return school;
            public void setSchool(String school) {
       = school;
            public String toString() {
                return "Report{" +
                       "reportKey='" + reportKey + '\'' +
                       ", studentNumber='" + studentNumber + '\'' +
                       ", school='" + school + '\'' +

    Getting "Cannot call a class as a function" in my React Project

    For me it was a wrong import of a reducer in the rootReducer.js. I imported container instead of reducer file.


    import settings from './pages/Settings';

    But sure it should be

    import settings from './pages/Settings/reducer';

    Where settings directory contains following files actions.js, index.js, reducer.js.

    To check it you can log reducers arg of the assertReducerShape() function from the redux/es/redux.js.

    String parsing in Java with delimiter tab "\t" using split

    I just had the same question and noticed the answer in some kind of tutorial. In general you need to use the second form of the split method, using the

    split(regex, limit)

    Here is the full tutorial

    If you set some negative number for the limit parameter you will get empty strings in the array where the actual values are missing. To use this your initial string should have two copies of the delimiter i.e. you should have \t\t where the values are missing.

    Hope this helps :)

    jQuery window scroll event does not fire up

    To whom its just not working to (like me) no matter what you tried: <element onscroll="myFunction()"></element> works like a charm

    exactly as they explain in W3 schools

    Empty ArrayList equals null

    No, because it contains items there must be an instance of it. Its items being null is irrelevant, so the statment ((arrayList) != null) == true

    Which comes first in a 2D array, rows or columns?

    The best way to remember if rows or columns come first would be writing a comment and mentioning it.

    Java does not store a 2D Array as a table with specified rows and columns, it stores it as an array of arrays, like many other answers explain. So you can decide, if the first or second dimension is your row. You just have to read the array depending on that.

    So, since I get confused by this all the time myself, I always write a comment that tells me, which dimension of the 2d Array is my row, and which is my column.

    Python Set Comprehension

    You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

    The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

    With an appropriate predicate in hand, problem 1 simplifies to:

     low_primes = {x for x in range(1, 100) if is_prime(x)}

    And problem 2 simplifies to:

     low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

    Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

    P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

    Adding gif image in an ImageView in android

    In your build.gradle(Module:app), add android-gif-drawable as a dependency by adding the following code:

    allprojects {
        repositories {
    dependencies {
        compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.+'

    UPDATE: As of Android Gradle Plugin 3.0.0, the new command for compiling is implementation, so the above line might have to be changed to:

    dependencies {
        implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.17'

    Then sync your project. When synchronization ends, go to your layout file and add the following code:


    And that's it, you can manage it with a simple ImageView.

    How do I create a user account for basic authentication?

    Right click on Computer and choose "Manage" (or go to Control Panel > Administrative Tools > Computer Management) and under "Local Users and Groups" you can add a new user. Then, give that user permission to read the directory where the site is hosted.

    Note: After creating the user, be sure to edit the user and remove all roles.

    How to connect HTML Divs with Lines?

    You can use SVGs to connect two divs using only HTML and CSS:

    <div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#777; position:absolute;"></div>
    <div id="div2" style="width: 100px; height: 100px; top:300px; left:300px; background:#333; position:absolute;"></div>

    (please use seperate css file for styling)

    Create a svg line and use this line to connect above divs

    <svg width="500" height="500"><line x1="50" y1="50" x2="350" y2="350" stroke="black"/></svg>


    x1,y1 indicates center of first div and
    x2,y2 indicates center of second div

    You can check how it looks in the snippet below

    <div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#777; position:absolute;"></div>_x000D_
    <div id="div2" style="width: 100px; height: 100px; top:300px; left:300px; background:#333; position:absolute;"></div>_x000D_
    <svg width="500" height="500"><line x1="50" y1="50" x2="350" y2="350" stroke="black"/></svg>

    How to Merge Two Eloquent Collections?

    The merge method returns the merged collection, it doesn't mutate the original collection, thus you need to do the following

    $original = new Collection(['foo']);
    $latest = new Collection(['bar']);
    $merged = $original->merge($latest); // Contains foo and bar.

    Applying the example to your code

    $related = new Collection();
    foreach ($question->tags as $tag)
        $related = $related->merge($tag->questions);

    Why use 'git rm' to remove a file instead of 'rm'?

    Remove files from the index, or from the working tree and the index. git rm will not remove a file from just your working directory.

    Here's how you might delete a file using rm -f and then remove it from your index with git rm

    $ rm -f index.html
    $ git status -s
     D index.html
    $ git rm index.html
    rm 'index.html'
    $ git status -s
    D  index.html

    However you can do this all in one go with just git rm

    $ git status -s
    $ git rm index.html
    rm 'index.html'
    $ ls
    lib vendor
    $ git status -s
    D  index.html

    What generates the "text file busy" message in Unix?

    root@h1:bin[0]# mount h2:/ /x             
    root@h1:bin[0]# cp /usr/bin/cat /x/usr/local/bin/
    root@h1:bin[0]# umount /x
    root@h2:~[0]# /usr/local/bin/cat 
    -bash: /usr/local/bin/cat: Text file busy
    ubuntu 20.04, 5.4.0-40-generic
    nfsd problem, after reboot ok

    Passing data between controllers in Angular JS?

    You can do this by two methods.

    1. By using $rootscope, but I don't reccommend this. The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable.

    2. Using services. You can do this by sharing a service between two controllers. Code for service may look like this:

      app.service('shareDataService', function() {
          var myList = [];
          var addList = function(newObj) {
          var getList = function(){
              return myList;
          return {
              addList: addList,
              getList: getList

      You can see my fiddle here.

    JSONException: Value of type java.lang.String cannot be converted to JSONObject

    return response;

    After that get the response we need to parse this By:

    JSONObject myObj=new JSONObject(response);

    On response there is no need for double quotes.

    Access denied; you need (at least one of) the SUPER privilege(s) for this operation

    * Answer may only be applicable to MacOS *

    When trying to import a .sql file into a docker container, I encountered the error message:

    Access denied; you need (at least one of) the SUPER privilege(s) for this operation

    Then while trying some of the other suggestions, I received the below error on my MacOS (osx)

    sed: RE error: illegal byte sequence

    Finally, the following command from this resource resolved my "Access Denied" issue.

    LC_ALL=C sed -i old 's/\DEFINER\=`[^`]*`@`[^`]*`//g' fileName.sql

    So I could import into the docker database with:

    docker exec -i dockerContainerName mysql -uuser -ppassword table < importFile.sql

    Hope this helps! :)

    How to get first and last day of the current week in JavaScript

    function getMonday(d) {
        d = new Date(d);
        var day = d.getDay(),
            diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
        return new Date(d.setDate(diff));
     console.log( getMonday(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())) )  // Mon Nov 08 2010

    Reading/writing an INI file

    PeanutButter.INI is a Nuget-packaged class for INI files manipulation. It supports read/write, including comments – your comments are preserved on write. It appears to be reasonably popular, is tested and easy to use. It's also totally free and open-source.

    Disclaimer: I am the author of PeanutButter.INI.

    SQL query for a carriage return in a string and ultimately removing carriage return

    If you are considering creating a function, try this: DECLARE @schema sysname = 'dbo' , @tablename sysname = 'mvtEST' , @cmd NVarchar(2000) , @ColName sysname

        DECLARE @NewLine Table
        (ColumnName Varchar(100)
        ,Location Int
        ,ColumnValue Varchar(8000)
        OPEN looper
        FETCH NEXT FROM looper INTO @ColName
        WHILE @@fetch_status = 0
        SELECT @cmd = 'select ''' +@ColName+    ''',  CHARINDEX(Char(10),  '+  @ColName +') , '+ @ColName + ' from '+@schema + '.'+@tablename +' where CHARINDEX(Char(10),  '+  @ColName +' ) > 0 or CHARINDEX(CHAR(13), '+@ColName +') > 0'
        PRINT @cmd
        INSERT @NewLine ( ColumnName, Location, ColumnValue )
        EXEC sp_executesql @cmd
        FETCH NEXT FROM looper INTO @ColName
        CLOSE looper
        DEALLOCATE looper
        SELECT * FROM  @NewLine

    No signing certificate "iOS Distribution" found

    I had the same issue and I have gone through all these solutions given, but none of them worked for me. But then I realised my stupid mistake. I forgot to change Code signing identity to iOS Distribution from iOS Developer, under build settings tab. Please make sure you have selected 'iOS Distribution' there.

    CRON job to run on the last day of the month

    You can just connect all answers in one cron line and use only date command.

    Just check the difference between day of the month which is today and will be tomorrow:

    0 23 * * * root [ $(expr $(date +\%d -d '1 days') - $(date +\%d)  ) -le 0 ]  && echo true

    If these difference is below 0 it means that we change the month and there is last day of the month.

    How to use the 'main' parameter in package.json?

    To answer your first question, the way you load a module is depending on the module entry point and the main parameter of the package.json.

    Let's say you have the following file structure:

    |-- lib
    |   |-- module.js
    |-- package.json

    Without main parameter in the package.json, you have to load the module by giving the module entry point: require('my-npm-module/lib/module.js').

    If you set the package.json main parameter as follows "main": "lib/module.js", you will be able to load the module this way: require('my-npm-module').

    jQuery SVG vs. Raphael

    If you don't need VML and IE8 support then use Canvas (PaperJS for example). Look at latest IE10 demos for Windows 7. They have amazing animations in Canvas. SVG is not capable to do anything close to them. Overall Canvas is available at all mobile browsers. SVG is not working at early versions of Android 2.0- 2.3 (as I know)

    Yes, Canvas is not scalable, but it so fast that you can redraw the whole canvas faster then browser capable to scroll view port.

    From my perspective Microsoft's optimizations provides means to use Canvas as regular GDI engine and implement graphics applications like we do them for Windows now.

    Log4net does not write the log in the log file

    For me I had to move Logger to a Nuget Package. Below code need to be added in NuGet package project.

    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]

    See for more details.

    Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

    In build:app

    apply plugin: ''
    android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.proyecto.marketdillo"
        minSdkVersion 14
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner ""
        multiDexEnabled true
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), ''
    dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation ''
    implementation ''
    implementation ''
    implementation ''
    implementation ''
    implementation ''
    implementation 'com.squareup.picasso:picasso:2.5.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation ''
    androidTestImplementation ''
    implementation ''
    implementation ''
    apply plugin: ''

    Failed to allocate memory: 8

    Have a look at the official issue 33930. There is pointed out, that it may have to do with the start up of OpenGL during the start of the emulator. Others wrote it only crashes when they use WXGA800-skin and suggest to manually set the resolution to 800x1280.

    Further there are ZIP-files provided to manually downgrade your android SDK to version 19 and plattform-tools to version 11. This may help as well to temporally fix the issue.

    How to create a new variable in a data.frame based on a condition?

    If you have a very limited number of levels, you could try converting y into factor and change its levels.

    > xy <- data.frame(x = c(1, 2, 4), y = c(1, 4, 5))
    > xy$w <- as.factor(xy$y)
    > levels(xy$w) <- c("good", "fair", "bad")
    > xy
      x y    w
    1 1 1 good
    2 2 4 fair
    3 4 5  bad

    Import Maven dependencies in IntelliJ IDEA

    If everything else fails, check if the jar file in your local .m2 repository is indeed valid and not corrupted. In my case, the file had not been fully downloaded.

    MySQL and GROUP_CONCAT() maximum length

    The correct parameter to set the maximum length is:

    SET @@group_concat_max_len = value_numeric;

    value_numeric must be > 1024; by default the group_concat_max_len value is 1024.

    The Completest Cocos2d-x Tutorial & Guide List

    Here you got complementaries discussions about the topic, it can be interesting.



    Difference between jQuery’s .hide() and setting CSS to display: none

    Looking at the jQuery code, this is what happens:

    hide: function( speed, easing, callback ) {
        if ( speed || speed === 0 ) {
            return this.animate( genFx("hide", 3), speed, easing, callback);
        } else {
            for ( var i = 0, j = this.length; i < j; i++ ) {
                var display = jQuery.css( this[i], "display" );
                if ( display !== "none" ) {
           this[i], "olddisplay", display );
            // Set the display of the elements in a second loop
            // to avoid the constant reflow
            for ( i = 0; i < j; i++ ) {
                this[i].style.display = "none";
            return this;

    Visibility of global variables in imported modules

    As a workaround, you could consider setting environment variables in the outer layer, like this.

    import os
    os.environ['MYVAL'] = str(myintvariable)

    import os
    myval = None
    if 'MYVAL' in os.environ:
        myval = os.environ['MYVAL']

    As an extra precaution, handle the case when MYVAL is not defined inside the module.

    Adding a month to a date in T SQL

    DATEADD is the way to go with this

    See the W3Schools tutorial:

    PDF Blob - Pop up window not showing content

    problem is, it is not converted to proper format. Use function "printPreview(binaryPDFData)" to get print preview dialog of binary pdf data. you can comment script part if you don't want print dialog open.

    printPreview = (data, type = 'application/pdf') => {
        let blob = null;
        blob = this.b64toBlob(data, type);
        const blobURL = URL.createObjectURL(blob);
        const theWindow =;
        const theDoc = theWindow.document;
        const theScript = document.createElement('script');
        function injectThis() {
        theScript.innerHTML = `window.onload = ${injectThis.toString()};`;
    b64toBlob = (content, contentType) => {
        contentType = contentType || '';
        const sliceSize = 512;
         // method which converts base64 to binary
        const byteCharacters = window.atob(content); 
        const byteArrays = [];
        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            const slice = byteCharacters.slice(offset, offset + sliceSize);
            const byteNumbers = new Array(slice.length);
            for (let i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob(byteArrays, {
            type: contentType
        }); // statement which creates the blob
        return blob;

    What is the difference between a "function" and a "procedure"?

    I object with something I keep seeing over and over in most of these answers, that what makes a function a function is that it returns a value.

    A function is not just any old method that returns a value. Not so: In order for a method to be a real function it must return the same value always given a specific input. An example of a method that is not a function is the random method in most languages, because although it does return a value the value is not always the same.

    A function therefore is more akin to a map (e.g. where x -> x' for a one dimensional function). This is a very important distinction between regular methods and functions because when dealing with real functions the timing and the order in which they are evaluated should never matter where as this is not always the case with non functions.

    Here's another example of a method that is not a function but will otherwise still return a value.

    // The following is pseudo code:
    g(x) = {
      if (morning()) {
         g = 2 * x;
      else {
       g = x;
      return g;

    I further object to the notion that procedures do not return values. A procedure is just a specific way of talking about a function or method. So that means if the underlying method that your procedure defines or implements returns a value then, guess what that procedure returns a value. Take for example the following snippet from the SICP:

    // We can immediately translate this definition into a recursive procedure 
    // for computing Fibonacci numbers:
    (define (fib n)
      (cond ((= n 0) 0)
            ((= n 1) 1)
            (else (+ (fib (- n 1))
                     (fib (- n 2))))))

    Have you heard of recursive procedures much lately? They are talking about a recursive function (a real function) and it's returning a value and they are using the word "procedure". So what's the difference, then?

    Well another way of thinking of a function (besides the meaning mentioned above) is as an abstract representation of an ideal like the numeral 1. A procedure is that actual implementation of that thing. I personally think they are interchangeable.

    (Note, if you read that chapter from the link I provide you may find that a harder concept to grasp is not the difference between a function and a procedure, but a process and a procedure. Did you know that a recursive procedure can have an iterative process?)

    An analog for procedures are recipes. For example; suppose you have a machine called make-pies this machine takes in ingredients of (fruit, milk, flower, eggs, sugar, heat) and this machine returns a pie.

    A representation of this machine might look like

    make-pies (fruit, milk, flower, eggs, sugar, heat) = {
       return (heat (add fruit (mix eggs flower milk)))

    Of course that's not the only way to make a pie.

    In this case we can see that:

    A       function     is to a     machine
    as a    procedure    is to a     recipe
    as      attributes   are to      ingredients
    as      output       is to       product

    That analogy is OK but it breaks down when you take into account that when you are dealing with a computer program everything is an abstraction. So unlike in the case of a recipe to a machine we are comparing two things that are themselves abstractions; two things that might as well be the same thing. And I hold that they are (for all intent and purposes) the same thing.

    Pinging an IP address using PHP and echoing the result

    I use this function :

    function is_ping_address($ip) {
        exec('ping -c1 -w1 '.$ip, $outcome, $status);
        preg_match('/([0-9]+)% packet loss/', $outcome[3], $arr);
        return ( $arr[1] == 100 ) ? false : true;

    What is null in Java?

    Bytecode representation

    Java's null has direct JVM support: three instructions are used to implement it:

    • aconst_null: e.g. to set a variable to null as in Object o = null;
    • ifnull and ifnonnull: e.g. to compare an object to null as in if (o == null)

    Chapter 6 "The Java Virtual Machine Instruction Set " then mentions the effects of null on other instructions: it throws a NullPointerException for many of them.

    2.4. "Reference Types and Values" also mentions null in generic terms:

    A reference value may also be the special null reference, a reference to no object, which will be denoted here by null. The null reference initially has no run-time type, but may be cast to any type. The default value of a reference type is null.

    Authentication plugin 'caching_sha2_password' cannot be loaded

    Actually MySql allows two type of authentication at the time of installation.

    1. Password Encryption
    2. Legacy Encryption

    enter image description here

    Read Here

    So by checking legacy authentication the issue was resolved.

    Fastest way to list all primes below N

    This is an elegant and simpler solution to find primes using a stored list. Starts with a 4 variables, you only have to test odd primes for divisors, and you only have to test up to a half of what number you are testing as a prime (no point in testing whether 9, 11, 13 divide into 17). It tests previously stored primes as divisors.`

        # Program to calculate Primes
     primes = [1,3,5,7]
    for n in range(9,100000,2):
        for x in range(1,(len(primes)/2)):
            if n % primes[x] == 0:
    print primes

    Read url to string in few lines of java code

    Java 11+:

    URI uri = URI.create("");
    HttpRequest request = HttpRequest.newBuilder(uri).build();
    String content = HttpClient.newHttpClient().send(request, BodyHandlers.ofString()).body();

    How to strip a specific word from a string?

    A bit 'lazy' way to do this is to use startswith- it is easier to understand this rather regexps. However regexps might work faster, I haven't measured.

    >>> papa = "papa is a good man"
    >>> app = "app is important"
    >>> strip_word = 'papa'
    >>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
    ' is a good man'
    >>> app[len(strip_word):] if app.startswith(strip_word) else app
    'app is important'

    TypeError: Missing 1 required positional argument: 'self'

    You need to initialize it first:

    p = Pump().getPumps()

    How to trim a string in SQL Server before 2017?

    SELECT LTRIM(RTRIM(Replace(Replace(Replace(name,'   ',' '),CHAR(13), ' '),char(10), ' ')))
    from author

    using BETWEEN in WHERE condition

    $this->db->where('accommodation BETWEEN '' . $sdate . '' AND '' . $edate . ''');

    this is my solution

    Barcode scanner for mobile phone for Website in form

    Check out

    "QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real- time localization and decoding of various types of barcodes such as EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93 and CODABAR. The library is also capable of using getUserMedia to get direct access to the user's camera stream. Although the code relies on heavy image-processing even recent smartphones are capable of locating and decoding barcodes in real-time."

    Do I need to compile the header files in a C program?

    You don't need to compile header files. It doesn't actually do anything, so there's no point in trying to run it. However, it is a great way to check for typos and mistakes and bugs, so it'll be easier later.

    rsync: difference between --size-only and --ignore-times

    The short answer is that --ignore-times does more than its name implies. It ignores both the time and size. In contrast, --size-only does exactly what it says.

    The long answer is that rsync has three ways to decide if a file is outdated:

    1. Compare the size of source and destination.
    2. Compare the timestamp of source and destination.
    3. Compare the static checksum of source and destination.

    These checks are performed before transferring data. Notably, this means the static checksum is distinct from the stream checksum - the later is computed while transferring data.

    By default, rsync uses only 1 and 2. Both 1 and 2 can be acquired together by a single stat, whereas 3 requires reading the entire file (this is independent from reading the file for transfer). Assuming only one modifier is specified, that means the following:

    • By using --size-only, only 1 is performed - timestamps and checksum are ignored. A file is copied unless its size is identical on both ends.

    • By using --ignore-times, neither of 1, 2 or 3 is performed. A file is always copied.

    • By using --checksum, 3 is used in addition to 1, but 2 is not performed. A file is copied unless size and checksum match. The checksum is only computed if size matches.

    What is the email subject length limit?

    What's important is which mechanism you are using the send the email. Most modern libraries (i.e. System.Net.Mail) will hide the folding from you. You just put a very long email subject line in without (CR,LF,HTAB). If you start trying to do your own folding all bets are off. It will start reporting errors. So if you are having this issue just filter out the CR,LF,HTAB and let the library do the work for you. You can usually also set the encoding text type as a separate field. No need for iso encoding in the subject line.

    HTML5 Canvas and Anti-aliasing

    I haven't needed to turn on anti-alias because it's on by default but I have needed to turn it off. And if it can be turned off it can also be turned on.

    ctx.imageSmoothingEnabled = true;

    I usually shut it off when I'm working on my canvas rpg so when I zoom in the images don't look blurry.

    How can I make a DateTimePicker display an empty string?

    The basic concept is the same told by others. But its easier to implement this way when you have multiple dateTimePicker.

    dateTimePicker1.Value = DateTime.Now;
    dateTimePicker1.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);
    dateTimePicker2.Value = DateTime.Now;
    dateTimePicker2.ValueChanged += new System.EventHandler(this.Dtp_ValueChanged);

    the value changed event function

            void Dtp_ValueChanged(object sender, EventArgs e)
                        ((DateTimePicker)sender).CustomFormat = " ";
                        ((DateTimePicker)sender).Format = DateTimePickerFormat.Custom;
                        ((DateTimePicker)sender).Format = DateTimePickerFormat.Short;
                    ((DateTimePicker)sender).Format = DateTimePickerFormat.Short;

    When unchecked enter image description here

    When checked enter image description here

    How to get height of Keyboard?

    Swift 3.0 and Swift 4.1

    1- Register the notification in the viewWillAppear method:

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

    2- Method to be called:

    @objc func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height

    Adding a Method to an Existing Object Instance

    This question was opened years ago, but hey, there's an easy way to simulate the binding of a function to a class instance using decorators:

    def binder (function, instance):
      copy_of_function = type (function) (function.func_code, {})
      copy_of_function.__bind_to__ = instance
      def bound_function (*args, **kwargs):
        return copy_of_function (copy_of_function.__bind_to__, *args, **kwargs)
      return bound_function
    class SupaClass (object):
      def __init__ (self):
        self.supaAttribute = 42
    def new_method (self):
      print self.supaAttribute
    supaInstance = SupaClass ()
    supaInstance.supMethod = binder (new_method, supaInstance)
    otherInstance = SupaClass ()
    otherInstance.supaAttribute = 72
    otherInstance.supMethod = binder (new_method, otherInstance)
    otherInstance.supMethod ()
    supaInstance.supMethod ()

    There, when you pass the function and the instance to the binder decorator, it will create a new function, with the same code object as the first one. Then, the given instance of the class is stored in an attribute of the newly created function. The decorator return a (third) function calling automatically the copied function, giving the instance as the first parameter.

    In conclusion you get a function simulating it's binding to the class instance. Letting the original function unchanged.

    Mock MVC - Add Request Parameter to test

    @ModelAttribute is a Spring mapping of request parameters to a particular object type. so your parameters might look like userClient.username and userClient.firstName, etc. as MockMvc imitates a request from a browser, you'll need to pass in the parameters that Spring would use from a form to actually build the UserClient object.

    (i think of ModelAttribute is kind of helper to construct an object from a bunch of fields that are going to come in from a form, but you may want to do some reading to get a better definition)

    How to Count Duplicates in List with LINQ

    Slightly shorter version using methods chain:

    var list = new List<string> {"a", "b", "a", "c", "a", "b"};
    var q = list.GroupBy(x => x)
                .Select(g => new {Value = g.Key, Count = g.Count()})
    foreach (var x in q)
        Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);

    how to reference a YAML "setting" from elsewhere in the same YAML file?

    I have wrote my own library on Python to expand variables being loaded from directories with a hierarchy like:

     +- /proj1
         +- config.yaml
         +- /proj2
             +- config.yaml
             ... and so on ...

    The key difference here is that the expansion must be applied only after all the config.yaml files is loaded, where the variables from the next file can override the variables from the previous, so the pseudocode should look like this:

    env = YamlEnv()

    As an additional option the xonsh script can export the resulting variables into environment variables (see the yaml_update_global_vars function).

    The scripts:


    • simple, does not support recursion and nested variables
    • can replace an undefined variable to a placeholder (${MYUNDEFINEDVAR} -> *$/{MYUNDEFINEDVAR})
    • can expand a reference from environment variable (${env:MYVAR})
    • can replace all \\ to / in a path variable (${env:MYVAR:path})


    • does not support nested variables, so can not expand values in nested dictionaries (something like ${MYSCOPE.MYVAR} is not implemented)
    • does not detect expansion recursion, including recursion after a placeholder put

    Style input type file?

    Use the clip property along with opacity, z-index, absolute positioning, and some browser filters to place the file input over the desired button:

    Ruby on Rails: How do I add placeholder text to a f.text_field?

    In Rails 4(Using HAML):

    =f.text_field :first_name, class: 'form-control', autofocus: true, placeholder: 'First Name'

    git add remote branch

    If the remote branch already exists then you can (probably) get away with..

    git checkout branch_name

    and git will automatically set up to track the remote branch with the same name on origin.

    Get a specific bit from byte


    public static bool GetBit(this byte b, int bitNumber) {
       return (b & (1 << bitNumber)) != 0;

    should do it, I think.

    HttpClient 4.0.1 - how to release connection?

    This seems to work great :

          if( response.getEntity() != null ) {

    And don't forget to consume the entity even if you didn't open its content. For instance, you expect a HTTP_OK status from the response and don't get it, you still have to consume the entity !

    Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

    Be aware, that \W leaves the underscore. A short equivalent for [^a-zA-Z0-9] would be [\W_]

    text.replace(/[\W_]+/g," ");

    \W is the negation of shorthand \w for [A-Za-z0-9_] word characters (including the underscore)

    Example at

    How do you list the primary key of a SQL Server table?

    I like the INFORMATION_SCHEMA technique, but another I've used is: exec sp_pkeys 'table'

    How can I check for "undefined" in JavaScript?

    The most reliable way I know of checking for undefined is to use void 0.

    This is compatible with newer and older browsers, alike, and cannot be overwritten like window.undefined can in some cases.

    if( myVar === void 0){
        //yup it's undefined

    What is the problem with shadowing names defined in outer scopes?

    A good workaround in some cases may be to move the variables and code to another function:

    def print_data(data):
        print data
    def main():
        data = [4, 5, 6]

    Running python script inside ipython

    The %run magic has a parameter file_finder that it uses to get the full path to the file to execute (see here); as you note, it just looks in the current directory, appending ".py" if necessary.

    There doesn't seem to be a way to specify which file finder to use from the %run magic, but there's nothing to stop you from defining your own magic command that calls into %run with an appropriate file finder.

    As a very nasty hack, you could override the default file_finder with your own:[2] = my_file_finder

    To be honest, at the rate the IPython API is changing that's as likely to continue to work as defining your own magic is.

    Create Carriage Return in PHP String?

    There is also the PHP 5.0.2 PHP_EOL constant that is cross-platform !

    Stackoverflow reference

    Consider marking event handler as 'passive' to make the page more responsive

    Also encounter this in select2 dropdown plugin in Laravel. Changing the value as suggested by Alfred Wallace from

    this.element.addEventListener(t, e, !1)


    this.element.addEventListener(t, e, { passive: true} )

    solves the issue. Why he has a down vote, I don't know but it works for me.

    require(vendor/autoload.php): failed to open stream

    Create composer.json file with requisite library for ex:

        "require": {
            "mpdf/mpdf": "^6.1"

    Execute the below command where composer.json exists:

    composer install

    In case of Drupal :

    Use the web root folder of drupal to include autoload for ex:

    define('DRUPAL_ROOT', getcwd());
    require_once DRUPAL_ROOT . '/vendor/autoload.php';

    In case of other systems: Use the root folder variable or location to include the autoload.php

    How to verify if nginx is running or not?

    For Mac users

    I found out one more way: You can check if /usr/local/var/run/ exists. If it is - nginx is running. Useful way for scripting.


    if [ -f /usr/local/var/run/ ]; then
       echo "Nginx is running"

    What is the role of the bias in neural networks?

    Bias determines how much angle your weight will rotate.

    In 2-dimensional chart, weight and bias can help us to find the decision boundary of outputs.

    Say we need to build a AND function, the input(p)-output(t) pair should be

    {p=[0,0], t=0},{p=[1,0], t=0},{p=[0,1], t=0},{p=[1,1], t=1}

    enter image description here

    Now we need to find a decision boundary, the ideal boundary should be:

    enter image description here

    See? W is perpendicular to our boundary. Thus, we say W decided the direction of boundary.

    However, it is hard to find correct W at first time. Mostly, we choose original W value randomly. Thus, the first boundary may be this: enter image description here

    Now the boundary is pareller to y axis.

    We want to rotate boundary, how?

    By changing the W.

    So, we use the learning rule function: W'=W+P: enter image description here

    W'=W+P is equivalent to W'=W+bP, while b=1.

    Therefore, by changing the value of b(bias), you can decide the angle between W' and W. That is "the learning rule of ANN".

    You could also read Neural Network Design by Martin T. Hagan / Howard B. Demuth / Mark H. Beale, chapter 4 "Perceptron Learning Rule"

    WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

    The problem was a missing dependency that wasn't on the server but was on my local machine. In our case, it was a Devart.Data.Linq dll.

    To get to that answer, I turned on IIS tracing for 500 errors. That gave a little bit of information, but the really helpful thing was in the web.config setting the <system.web><customErrors mode="Off"/></system.web> This pointed to a missing dynamically-loaded dependency. After adding this dependency and telling it to be copied locally, the server started working.

    How to store NULL values in datetime fields in MySQL?

    Specifically relating to the error you're getting, you can't do something like this in PHP for a nullable field in MySQL:

    $sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . null . ')';

    Because null in PHP will equate to an empty string which is not the same as a NULL value in MysQL. Instead you want to do this:

    $sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . (is_null($col2) ? 'NULL' : $col2). ')';

    Of course you don't have to use is_null but I figure that it demonstrates the point a little better. Probably safer to use empty() or something like that. And if $col2 happens to be a string which you would enclose in double quotes in the query, don't forget not to include those around the 'NULL' string, otherwise it wont work.

    Hope that helps!

    How can I get the current contents of an element in webdriver

    In Java its Webelement.getText() . Not sure about python.

    Multiple lines of input in <input type="text" />

    You should use textarea to support multiple-line inputs.

    <textarea rows="4" cols="50">
    Here you can write some text to display in the textarea as the default text

    Checking letter case (Upper/Lower) within a string in Java

    function TellFirstCharacterType(inputString){
        var firstCharacter = inputString[0];
            if(firstCharacter == firstCharacter.toUpperCase()){
                return "It's a uppercase character";
                return "It's a lowercase character";
            return "It's a Number";

    CLEAR SCREEN - Oracle SQL Developer shortcut?

    SQL>Clear Screen (It is used the Clear The Screen FUlly in SQL Plus Window)

    PHP code is not being executed, instead code shows on the page

    In my case the php module was not loaded. Try this:

    1. Check which modules are loaded: apache2ctl -M. Look for module like php7_module (shared)
    2. If no php module is listed, then try to load the module that corresponds to your php version. In my case the php packet is libapache2-mod-php7.3. So I did: a2enmod php7.3 and the problem was solved.

    ggplot combining two plots from different data.frames

    You can take this trick to use only qplot. Use inner variable $mapping. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.

    cpu_metric2 <- qplot(y=Y2,x=X1) 
    cpu_metric1 <- qplot(y=Y1, 
                        xlab="Time", ylab="%") 
    combined_cpu_plot <- cpu_metric1 + 
      geom_line() +

    What is aria-label and how should I use it?

    The title attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).

    As such, the mindful approach here would be to serve all users. I would add both title and aria-label attributes (serving different types of users and different types of usage of the web).

    Here's a good article that explains aria-label in depth

    Why std::cout instead of simply cout?

    If you are working in ROOT, you do not even have to write #include<iostream> and using namespace std; simply start from int filename().

    This will solve the issue.

    Stop Visual Studio from mixing line endings in files

    see and

    1. If it does not exist, add a new file called .editorconfig for your project

    2. manipulate editor config to use your preferred behaviour.

    I prefer spaces over tabs, and CRLF for all code files.
    Here's my .editorconfig

    root = true
    indent_style = space
    indent_size = 4
    end_of_line = crlf
    charset = utf-8
    trim_trailing_whitespace = true
    insert_final_newline = true
    trim_trailing_whitespace = false
    indent_size = 4
    indent_size = 2 

    Is there a way to link someone to a YouTube Video in HD 1080p quality?

    No, this is not working. And it's not just for you, in case you spent the last hour trying to find an answer for having your embeded videos open in HD.

    Question: Oh, but how do you know this is not working anymore and there is no other alternative to make embeded videos open in a different quality?

    Answer: Just went to Google's official documentation regarding Youtube's player parameters and there is not a single parameter that allows you to change its quality.

    Also, hd=1 doesn't work either. More info here.

    Apparently Youtube analyses the width and height of the user's window (or iframe) and automatically sets the quality based on this.


    As of 10 of April of 2018 it still doesn't work (see my comment on the accepted answer for more details).

    What I can see from comments is that it MAY work sometimes, but some others it doesn't. The accepted answer states that "it measures the network speed and the screen and player sizes". So, by that, we can understand that I CANNOT force HD as YouTube will still do whatever it wants in case of low network speed/screen resolution. From my perspective everyone saying it works just have false positives on their hands and on the occasion they tested it worked for some random reason not related to the vq parameter. If it was a valid parameter, Google would document it somewhere, and vq isn't documented anywhere.

    How to count no of lines in text file and store the value into a variable using batch script?

    One nice surprise is for one who has git bash on his windows: just plain old linux wc -l <filename> will works for you there

    java.lang.OutOfMemoryError: Java heap space

    1. Local variables are located on the stack. Heap space is occupied by objects.

    2. You can use the -Xmx option.

    3. Basically heap space is used up everytime you allocate a new object with new and freed some time after the object is no longer referenced. So make sure that you don't keep references to objects that you no longer need.

    Creating a generic method in C#

    What about this? Change the return type from T to Nullable<T>

    public static Nullable<T> GetQueryString<T>(string key) where T : struct, IConvertible
                T result = default(T);
                if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
                    string value = HttpContext.Current.Request.QueryString[key];
                        result = (T)Convert.ChangeType(value, typeof(T));  
                        //Could not convert.  Pass back default value...
                        result = default(T);
                return result;

    BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

    I had the same problem in SSIS 2008. I tried to connect to an Oracle 11g using ODAC 12c 32 bit. Tried to install ODAC 12c 64 bit as well. SSIS was actually able to preview the table but when trying to run the package it was giving this error message. Nothing helped. Switched to VS 2013, now it was running in debug mode but got the same error when the running the package using dtexec /f filename. Then I found this page:

    To make it short it says: (if the page is still there just go to the page and follow the instrucrtions...) 1) Download and install the latest version of odac 64 bit xcopy from oracle site. 2) Download and install the latest version of odac 32 bit xcopy from oracle site. How? open a cmd shell AS AN ADMINSTARTOR and run: c:\64bitODACLocation> install.bat oledb c:\odac\odac64. the first parameter is the component you want to install. The second param is where to install to. install the 32 version as well like this: c:\32bitODACLocation> install.bat oledb c:\odac\odac32. 3) Change the path of the system to include c:\odac\odac32; c:\odac\odac32\bin; c:\odac\odac64;c:\odac\odac64\bin IN THIS ORDER. 4) Restart the machine. 5) make sure you have the same tnsnames.ora in both odac32\admin\network and odac64\admin\network folders (or at least the same entry for your connection). 6) Now open up SSIS in visual studio (I used the free 2013 version with the ssis package) - Use OLEDB and then select the Oracle Provider for OLE DB provider as your connection type. Set the name of the entry in your tnsnames.ora as the "server or file name". Username is your schema name (db name) and password is the password for schema. you are done!

    Again, you can find the very detailed solution and much more in the original site.

    This was the only thing which worked for me and did not mess up my environment.

    Cheers! gcr

    Maven compile: package does not exist

    You have to add the following dependency to your build:


    Furthermore i would suggest to take a deep look into the documentation about how to use the lib.

    How to capture Enter key press?

    Form approach

    As scoota269 says, you should use onSubmit instead, cause pressing enter on a textbox will most likey trigger a form submit (if inside a form)

    <form action="#" onsubmit="handle">
        <input type="text" name="txt" />
        function handle(e){
            e.preventDefault(); // Otherwise the form will be submitted
            alert("FORM WAS SUBMITTED");

    Textbox approach

    If you want to have an event on the input-field then you need to make sure your handle() will return false, otherwise the form will get submitted.

    <form action="#">
        <input type="text" name="txt" onkeypress="handle(event)" />
        function handle(e){
            if(e.keyCode === 13){
                e.preventDefault(); // Ensure it is only this code that runs
                alert("Enter was pressed was presses");

    Python-Requests close http connection

    To remove the "keep-alive" header in requests, I just created it from the Request object and then send it with Session

    headers = {
    'Host' : '',
    'User-Agent' : 'Test client (x86_64-pc-linux-gnu 7.16.3)',
    'Accept' : '*/*',
    'Accept-Encoding' : 'deflate, gzip',
    'Accept-Language' : 'it_IT'
    url = ""
    #r = requests.get(url, headers = headers) #this triggers keep-alive: True
    s = requests.Session()
    r = requests.Request('GET', url, headers)

    How to change Screen buffer size in Windows Command Prompt from batch script

    I was just searching for an answer to this exact question, come to find out the command itself adjusts the buffer!

    mode con:cols=140 lines=70

    The lines=70 part actually adjusts the Height in the 'Screen Buffer Size' setting, NOT the Height in the 'Window Size' setting.

    Easily proven by running the command with a setting for 'lines=2500' (or whatever buffer you want) and then check the 'Properties' of the window, you'll see that indeed the buffer is now set to 2500.

    My batch script ends up looking like this:

    @echo off
    cmd "mode con:cols=140 lines=2500"

    Where can I view Tomcat log files in Eclipse?

    Double click and open the server. Go to 'Arguments'. -Dcatalina.base= .. something. Go to that something. Your logs are there.

    Django return redirect() with parameters

    Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

    Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:


    and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

    So your urlconf would be:

    url(r'^link/(?P<backend>\w+?)/$', my_function)

    and the view would look like:

    def my_function(request, backend):
       data = request.GET

    and the reverse would be (after importing urllib):

    return "%s?%s" % (redirect('my_function', args=(backend,)),

    Edited after comment

    The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

    If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

    That said, if all you want to do is store the data, then just put it in the session:

    request.session['temp_data'] = form.cleaned_data

    How to return a file using Web API?

    Example with IHttpActionResult in ApiController.

    public IHttpActionResult GetFileForCustomer(int id)
        if (id == 0)
          return BadRequest();
        var file = GetFile(id);
        IHttpActionResult response;
        HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.OK);
        responseMsg.Content = new ByteArrayContent(file.SomeData);
        responseMsg.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        responseMsg.Content.Headers.ContentDisposition.FileName = file.FileName;
        responseMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
        response = ResponseMessage(responseMsg);
        return response;

    If you don't want to download the PDF and use a browsers built in PDF viewer instead remove the following two lines:

    responseMsg.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    responseMsg.Content.Headers.ContentDisposition.FileName = file.FileName;

    Unique constraint on multiple columns

    This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.

    1. Under the table, right click Indexes->Click/hover New Index->Click Non-Clustered Index...

    enter image description here

    1. A default Index name will be given but you may want to change it. Check the Unique checkbox and click Add... button

    enter image description here

    1. Check the columns you want included

    enter image description here

    Click OK in each window and you're done.

    Hidden Features of Xcode

    Use the Class Browser to show inherited methods

    Apple's API reference documentation does not show methods inherited from a superclass. Sometimes, though. it's useful to be able to see the full range of functionality available for a class -- including a custom class of your own. You can use the Class Browser (from the Project menu) to display a flat or hierarchical list of all the classes related to a current project. The upper pane on the right hand side of the browser window shows a list of methods associated with the object selected in the browser. You can use the Configure Options sheet to select "Show Inherited Members" to show inherited methods as well as those defined by the selected class itself. You click the small book symbol to go to the corresponding documentation.

    Viewing full version tree in git

    If you don't need branch or tag name:
    git log --oneline --graph --all --no-decorate

    If you don't even need color (to avoid tty color sequence):
    git log --oneline --graph --all --no-decorate --no-color

    And a handy alias (in .gitconfig) to make life easier:

      tree = log --oneline --graph --all --no-decorate

    Only last option takes effect, so it's even possible to override your alias:
    git tree --decorate

    Powershell Execute remote exe with command line arguments on remote computer

    $sb = ScriptBlock::Create("$command")
    Invoke-Command -ScriptBlock $sb

    This should work and avoid misleading the beginners.

    In Javascript/jQuery what does (e) mean?

    e doesn't have any special meaning. It's just a convention to use e as function parameter name when the parameter is event.

    It can be

    $(this).click(function(loremipsumdolorsitamet) {
        // does something

    as well.

    RESTful Authentication via Spring

    Why don't you start using OAuth with JSON WebTokens

    OAuth2 is an standardized authorization protocol/framework. As per Official OAuth2 Specification:

    You can find more info here

    Failed linking file resources

    -May be the problem is that you have deleted .java files doing this doesn't delete the .XML files so go to res-> layout and delete those .XML files that you had delete before. -the another problem may be you haven't delete the files that is present in manifests under syntax that you deleted recently... So delete and run the code

    UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

    I see three solutions to this:

    1. Change the output encoding, so it will always output UTF-8. See e.g. Setting the correct encoding when piping stdout in Python, but I could not get these example to work.

    2. Following example code makes the output aware of your target charset.

      # -*- coding: utf-8 -*-
      import sys
      print sys.stdout.encoding
      print u"Stöcker".encode(sys.stdout.encoding, errors='replace')
      print u"????????".encode(sys.stdout.encoding, errors='replace')

      This example properly replaces any non-printable character in my name with a question mark.

      If you create a custom print function, e.g. called myprint, using that mechanisms to encode output properly you can simply replace print with myprint whereever necessary without making the whole code look ugly.

    3. Reset the output encoding globally at the begin of the software:

      The page has a good summary what to do to change output encoding. Especially the section "StreamWriter Wrapper around Stdout" is interesting. Essentially it says to change the I/O encoding function like this:

      In Python 2:

      if sys.stdout.encoding != 'cp850':
        sys.stdout = codecs.getwriter('cp850')(sys.stdout, 'strict')
      if sys.stderr.encoding != 'cp850':
        sys.stderr = codecs.getwriter('cp850')(sys.stderr, 'strict')

      In Python 3:

      if sys.stdout.encoding != 'cp850':
        sys.stdout = codecs.getwriter('cp850')(sys.stdout.buffer, 'strict')
      if sys.stderr.encoding != 'cp850':
        sys.stderr = codecs.getwriter('cp850')(sys.stderr.buffer, 'strict')

      If used in CGI outputting HTML you can replace 'strict' by 'xmlcharrefreplace' to get HTML encoded tags for non-printable characters.

      Feel free to modify the approaches, setting different encodings, .... Note that it still wont work to output non-specified data. So any data, input, texts must be correctly convertable into unicode:

      # -*- coding: utf-8 -*-
      import sys
      import codecs
      sys.stdout = codecs.getwriter("iso-8859-1")(sys.stdout, 'xmlcharrefreplace')
      print u"Stöcker"                # works
      print "Stöcker".decode("utf-8") # works
      print "Stöcker"                 # fails

    MySql Error: 1364 Field 'display_name' doesn't have default value

    MySQL is most likely in STRICT mode, which isn't necessarily a bad thing, as you'll identify bugs/issues early and not just blindly think everything is working as you intended.

    Change the column to allow null:

    ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NULL

    or, give it a default value as empty string:

    ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NOT NULL DEFAULT ''

    How to get data from observable in angular2

    You need to subscribe to the observable and pass a callback that processes emitted values

    this.myService.getConfig().subscribe(val => console.log(val));

    How to record phone calls in android?

    The accepted answer is perfect, except it does not record outgoing calls. Note that for outgoing calls it is not possible (as near as I can tell from scouring many posts) to detect when the call is actually answered (if anybody can find a way other than scouring notifications or logs please let me know). The easiest solution is to just start recording straight away when the outgoing call is placed and stop recording when IDLE is detected. Just adding the same class as above with outgoing recording in this manner for completeness:

    private void startRecord(String seed) {
            String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
            File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
            if (!sampleDir.exists()) {
            String file_name = "Record" + seed;
            try {
                audiofile = File.createTempFile(file_name, ".amr", sampleDir);
            } catch (IOException e) {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath();
            recorder = new MediaRecorder();
            try {
            } catch (IllegalStateException e) {
            } catch (IOException e) {
            recordstarted = true;
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_IN)) {
                if ((bundle = intent.getExtras()) != null) {
                    state = bundle.getString(TelephonyManager.EXTRA_STATE);
                    if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                        inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                        wasRinging = true;
                        Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
                    } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                        if (wasRinging == true) {
                            Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
                    } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                        wasRinging = false;
                        Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
                        if (recordstarted) {
                            recordstarted = false;
            } else if (intent.getAction().equals(ACTION_OUT)) {
                if ((bundle = intent.getExtras()) != null) {
                    outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                    Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
                    if ((bundle = intent.getExtras()) != null) {
                        state = bundle.getString(TelephonyManager.EXTRA_STATE);
                        if (state != null) {
                            if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                                wasRinging = false;
                                Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
                                if (recordstarted) {
                                    recordstarted = false;

    What does "javax.naming.NoInitialContextException" mean?

    It basically means that the application wants to perform some "naming operations" (e.g. JNDI or LDAP lookups), and it didn't have sufficient information available to be able to create a connection to the directory server. As the docs for the exception state,

    This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.

    And if you dutifully have a look at the javadocs for InitialContext, they describe quite well how the initial context is constructed, and what your options are for supplying the address/credentials/etc.

    If you have a go at creating the context and get stuck somewhere else, please post back explaining what you've done so far and where you're running aground.

    Rebase array keys after unsetting elements

    Try this:

    $array = array_values($array);

    Using array_values()

    JavaScript URL Decode function

    Use this


    I'm not a great JS programmer, tried all, and this worked awesome!

    What should I do when 'svn cleanup' fails?

    There are some very good suggestions in the previous answer, but if you are having an issue with TortoiseSVN on Windows (a good product, but ...) always fallback to the command line and do a simple "svn cleanup" first.

    In many circumstances the Windows client will not run the cleanup command, but cleanup works fine using thing the SVN command line utility.

    How do I make a stored procedure in MS Access?

    If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:

     PARAMETERS SomeParam Text(10);
     SELECT Field FROM Table
     WHERE OtherField=SomeParam

    You can also say:

    CREATE PROCEDURE ProcedureName
       (Parameter1 datatype, Parameter2 datatype) AS


    Note that the procedure contains only one statement.

    Unable to start the mysql server in ubuntu

    Yes, should try reinstall mysql, but use the --reinstall flag to force a package reconfiguration. So the operating system service configuration is not skipped:

    sudo apt --reinstall install mysql-server

    Better way to Format Currency Input editText?

    I built on Guilhermes answer, but I preserve the position of the cursor and also treat the periods differently - this way if a user is typing after the period, it does not affect the numbers before the period I find that this gives a very smooth input.

        [yourtextfield].addTextChangedListener(new TextWatcher()
            NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();
            private String current = "";
            public void onTextChanged(CharSequence s, int start, int before, int count)
                       int selection = [yourtextfield].getSelectionStart();
                       // We strip off the currency symbol
                       String replaceable = String.format("[%s,\\s]", NumberFormat.getCurrencyInstance().getCurrency().getSymbol());
                       String cleanString = s.toString().replaceAll(replaceable, "");
                       double price;
                       // Parse the string                     
                           price = Double.parseDouble(cleanString);
                       catch(java.lang.NumberFormatException e)
                           price = 0;
                       // If we don't see a decimal, then the user must have deleted it.
                       // In that case, the number must be divided by 100, otherwise 1
                       int shrink = 1;
                           shrink = 100;
                       // Reformat the number
                       String formated = currencyFormat.format((price / shrink));
                       current = formated;
                       [yourtextfield].setSelection(Math.min(selection, [yourtextfield].getText().length()));
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            public void afterTextChanged(Editable s)

    UINavigationBar Hide back Button Text

    This is from my xamarin.forms code, the class derives from NavigationRenderer

    NavigationBar.Items.FirstOrDefault().BackBarButtonItem = new UIBarButtonItem( "", UIBarButtonItemStyle.Plain, null);

    Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

    You need to do two additional things after following the link that you have mentioned in your post:

    One have to map the changed login cridentials in phpmyadmin's

    and second, you need to restart your web and mysql servers..

    php version is not the issue need to go to phpmyadmin installation directory and find file and in that file put your current mysql password at line

    $cfg['Servers'][$i]['user'] = 'root'; //mysql username here
    $cfg['Servers'][$i]['password'] = 'password'; //mysql password here

    How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

    Finally I get the solution for my problem. The account not appear in the IIS manager because I didn't check its check Box in IIS to do this in windows 7 follow the steps

    1. Open control panel
    2. Click on” program” link (not uninstall programs)
    3. Click” turn windows features on/off” link
    4. locate” Internet Information services IIS” in the pop up window and expand its node
    5. Expand the” World Wide Web Service” node
    6. Expand “Application Development Features” node
    7. check the check box of”ASP.NET”
    8. Then click ok button

    Now you will see the account on the IIS manager and by default you see IIS account Now you should move you website from “my document” to another place the IIS have permission to access it (to any partition on your computer) Now browse your website from IIS manager and it should work.

    Basic HTTP and Bearer Token Authentication

    With nginx you can send both tokens like this (even though it's against the standard):

    Authorization: Basic basic-token,Bearer bearer-token

    This works as long as the basic token is first - nginx successfully forwards it to the application server.

    And then you need to make sure your application can properly extract the Bearer from the above string.

    How do you display code snippets in MS Word preserving format and syntax highlighting?

    I'm using Easy Code Formatter. It's also an Office add-in. It allows you to select the coding style / and has a quick formatting button. Pretty neat.

    enter image description here