Programs & Examples On #Selectsinglenode

Selects the first Xml Node that matches the XPath expression

How to get the xml node value in string

The problem in your code is xml.LoadXml(filePath);

LoadXml method take parameter as xml data not the xml file path

Try this code

   string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xmlFile);
                XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall");
                string Short_Fall=string.Empty;
                foreach (XmlNode node in nodeList)
                {
                    Short_Fall = node.InnerText;
                }

Edit

Seeing the last edit of your question i found the solution,

Just replace the below 2 lines

XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");
string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")

with

string id = xml.SelectSingleNode("Data/Short_Fall").InnerText;

It should solve your problem or you can use the solution i provided earlier.

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

Try to go to App_Data folder property and add ASPNET user with read and write privileges

Ref:
How to assign correct permissions to App_Data folder of WebMail Pro ASP.NET
Permissions on APP_DATA Folder
ASP/ASP.NET Best way to handle write permissions?

If it does not solve your problem then check whether your XML files are not open by another thread using these configuration files.. and provide some more details if still persists.

Read a XML (from a string) and get some fields - Problems reading XML

Or use the XmlSerializer class.

XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

Modify XML existing content in C#

The XmlTextWriter is usually used for generating (not updating) XML content. When you load the xml file into an XmlDocument, you don't need a separate writer.

Just update the node you have selected and .Save() that XmlDocument.

SelectSingleNode returning null for known good xml node path using XPath

If you want to ignore namespaces completely, you can use this:

static void Main(string[] args)
{
    string xml =
        "<My_RootNode xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"\">\n" +
        "    <id root=\"2.16.840.1.113883.3.51.1.1.1\" extension=\"someIdentifier\" xmlns=\"urn:hl7-org:v3\" />\n" +
        "    <creationTime xsi:nil=\"true\" xmlns=\"urn:hl7-org:v3\" />\n" +
        "</My_RootNode>";

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    XmlNode idNode = doc.SelectSingleNode("/*[local-name()='My_RootNode']/*[local-name()='id']");
}

Find position of a node using xpath

The problem is that the position of the node doesn't mean much without a context.

The following code will give you the location of the node in its parent child nodes

using System;
using System.Xml;

public class XpathFinder
{
    public static void Main(string[] args)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(args[0]);
        foreach ( XmlNode xn in xmldoc.SelectNodes(args[1]) )
        {
            for (int i = 0; i < xn.ParentNode.ChildNodes.Count; i++)
            {
                if ( xn.ParentNode.ChildNodes[i].Equals( xn ) )
                {
                    Console.Out.WriteLine( i );
                    break;
                }
            }
        }
    }
}

Storing sex (gender) in database

I'd call the column "gender".

Data Type   Bytes Taken          Number/Range of Values
------------------------------------------------
TinyINT     1                    255 (zero to 255)
INT         4            -       2,147,483,648 to 2,147,483,647
BIT         1 (2 if 9+ columns)  2 (0 and 1)
CHAR(1)     1                    26 if case insensitive, 52 otherwise

The BIT data type can be ruled out because it only supports two possible genders which is inadequate. While INT supports more than two options, it takes 4 bytes -- performance will be better with a smaller/more narrow data type.

CHAR(1) has the edge over TinyINT - both take the same number of bytes, but CHAR provides a more narrow number of values. Using CHAR(1) would make using "m", "f",etc natural keys, vs the use of numeric data which are referred to as surrogate/artificial keys. CHAR(1) is also supported on any database, should there be a need to port.

Conclusion

I would use Option 2: CHAR(1).

Addendum

An index on the gender column likely would not help because there's no value in an index on a low cardinality column. Meaning, there's not enough variety in the values for the index to provide any value.

How to download and save a file from Internet using Java?

There is an issue with simple usage of:

org.apache.commons.io.FileUtils.copyURLToFile(URL, File) 

if you need to download and save very large files, or in general if you need automatic retries in case connection is dropped.

What I suggest in such cases is Apache HttpClient along with org.apache.commons.io.FileUtils. For example:

GetMethod method = new GetMethod(resource_url);
try {
    int statusCode = client.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        logger.error("Get method failed: " + method.getStatusLine());
    }       
    org.apache.commons.io.FileUtils.copyInputStreamToFile(
        method.getResponseBodyAsStream(), new File(resource_file));
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
    method.releaseConnection();
}

Select statement to find duplicates on certain fields

try this query to have sepratley count of each SELECT statements :

select field1,count(field1) as field1Count,field2,count(field2) as field2Counts,field3, count(field3) as field3Counts
from table_name
group by field1,field2,field3
having count(*) > 1

How to set back button text in Swift

Set self.title = "" before self.navigationController?.pushViewController(vc, animated: true).

How can I echo the whole content of a .html file in PHP?

If you want to make sure the HTML file doesn't contain any PHP code and will not be executed as PHP, do not use include or require. Simply do:

echo file_get_contents("/path/to/file.html");

How to prevent rm from reporting that a file was not found?

Yes, -f is the most suitable option for this.

Multi-dimensional arraylist or list in C#?

Depending on your exact requirements, you may do best with a jagged array of sorts with:

List<string>[] results = new { new List<string>(), new List<string>() };

Or you may do well with a list of lists or some other such construct.

AngularJS: Insert HTML from a string

you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"'),if you want to know more detail, please refer to $sce

Oracle query to fetch column names

  1. SELECT * FROM <SCHEMA_NAME.TABLE_NAME> WHERE ROWNUM = 0; --> Note that, this is Query Result, a ResultSet. This is exportable to other formats. And, you can export the Query Result to Text format. Export looks like below when I did SELECT * FROM SATURN.SPRIDEN WHERE ROWNUM = 0; :

    "SPRTELE_PIDM" "SPRTELE_SEQNO" "SPRTELE_TELE_CODE" "SPRTELE_ACTIVITY_DATE" "SPRTELE_PHONE_AREA" "SPRTELE_PHONE_NUMBER" "SPRTELE_PHONE_EXT" "SPRTELE_STATUS_IND" "SPRTELE_ATYP_CODE" "SPRTELE_ADDR_SEQNO" "SPRTELE_PRIMARY_IND" "SPRTELE_UNLIST_IND" "SPRTELE_COMMENT" "SPRTELE_INTL_ACCESS" "SPRTELE_DATA_ORIGIN" "SPRTELE_USER_ID" "SPRTELE_CTRY_CODE_PHONE" "SPRTELE_SURROGATE_ID" "SPRTELE_VERSION" "SPRTELE_VPDI_CODE"

  2. DESCRIBE <TABLE_NAME> --> Note: This is script output.

Where's my invalid character (ORA-00911)

Of the top of my head, can you try to use the 'q' operator for the string literal

something like

insert all
  into domo_queries values (q'[select 
substr(to_char(max_data),1,4) as year,
substr(to_char(max_data),5,6) as month,
max_data
from dss_fin_user.acq_dashboard_src_load_success
where source = 'CHQ PeopleSoft FS']')
select * from dual;

Note that the single quotes of your predicate are not escaped, and the string sits between q'[...]'.

Laravel 5 Class 'form' not found

There is an update to this for Laravel 5.2. Notice this is a slightly different format from what is indicated above.

Begin by installing this package through Composer. Edit your project's composer.json file to require laravelcollective/html.

"require": {
    "laravelcollective/html": "5.2.*"
}

Next, update Composer from the Terminal:

composer update

Next, add your new provider to the providers array of config/app.php:

  'providers' => [
    // ...
    Collective\Html\HtmlServiceProvider::class,
    // ...
  ],

Finally, add two class aliases to the aliases array of config/app.php:

  'aliases' => [
    // ...
      'Form' => Collective\Html\FormFacade::class,
      'Html' => Collective\Html\HtmlFacade::class,
    // ...
  ],

After making this update this code worked for me on a new installation of Laravel 5.2:

{!! Form::open(array('url' => 'foo/bar')) !!}
    //
{!! Form::close() !!}

I got this information here: https://laravelcollective.com/docs/5.2/html

How to pass arguments to a Button command in Tkinter?

Building on Matt Thompsons answer : a class can be made callable so it can be used instead of a function:

import tkinter as tk

class Callback:
    def __init__(self, func, *args, **kwargs):
        self.func = func
        self.args = args
        self.kwargs = kwargs
    def __call__(self):
        self.func(*self.args, **self.kwargs)

def default_callback(t):
    print("Button '{}' pressed.".format(t))

root = tk.Tk()

buttons = ["A", "B", "C"]

for i, b in enumerate(buttons):
    tk.Button(root, text=b, command=Callback(default_callback, b)).grid(row=i, column=0)

tk.mainloop()

Can promises have multiple arguments to onFulfilled?

Here is a CoffeeScript solution.

I was looking for the same solution and found seomething very intersting from this answer: Rejecting promises with multiple arguments (like $http) in AngularJS

the answer of this guy Florian

promise = deferred.promise

promise.success = (fn) ->
  promise.then (data) ->
   fn(data.payload, data.status, {additional: 42})
  return promise

promise.error = (fn) ->
  promise.then null, (err) ->
    fn(err)
  return promise

return promise 

And to use it:

service.get().success (arg1, arg2, arg3) ->
    # => arg1 is data.payload, arg2 is data.status, arg3 is the additional object
service.get().error (err) ->
    # => err

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

I want to chime in since I have a QEMU environment where I have to download files in java. It turns out the /etc/ssl/certs/java/cacerts in QEMU does have problem because it does not match the /etc/ssl/certs/java/cacerts in the host environment. The host environment is behind a company proxy so the java cacerts is a customized version.

If you are using a QEMU environment, make sure the host system can access files first. For example you can try this script on your host machine first to see. If the script runs just fine in host machine but not in QEMU, then you are having the same problem as me.

To solve this issue, I had to make a backup of the original file in QEMU, copy over the file in host environment to the QEMU chroot jail, and then java could download files normally in QEMU.

A better solution would be mount the /etc into the QEMU environment; however I am not sure if other files will get impacted in this process. So I decided to use this ugly but easy work-around.

reading HttpwebResponse json response, C#

First you need an object

public class MyObject {
  public string Id {get;set;}
  public string Text {get;set;}
  ...
}

Then in here

    using (var twitpicResponse = (HttpWebResponse)request.GetResponse()) {

        using (var reader = new StreamReader(twitpicResponse.GetResponseStream())) {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var objText = reader.ReadToEnd();
            MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
        }

    }

I haven't tested with the hierarchical object you have, but this should give you access to the properties you want.

JavaScriptSerializer System.Web.Script.Serialization

How can I pretty-print JSON using Go?

For better memory usage, I guess this is better:

var out io.Writer
enc := json.NewEncoder(out)
enc.SetIndent("", "    ")
if err := enc.Encode(data); err != nil {
    panic(err)
}

What does "&" at the end of a linux command mean?

In addition, you can use the "&" sign to run many processes through one (1) ssh connections in order to to keep minimum number of terminals. For example, I have one process that listens for messages in order to extract files, the second process listens for messages in order to upload files: Using the "&" I can run both services in one terminal, through single ssh connection to my server.


*****I just realized that these processes running through the "&" will also "stay alive" after ssh session is closed! pretty neat and useful if your connection to the server is interrupted**

Remove x-axis label/text in chart.js

(this question is a duplicate of In chart.js, Is it possible to hide x-axis label/text of bar chart if accessing from mobile?) They added the option, 2.1.4 (and maybe a little earlier) has it

var myLineChart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        scales: {
            xAxes: [{
                ticks: {
                    display: false
                }
            }]
        }
    }
}

What processes are using which ports on unix?

If you want to know all listening ports along with its details: local address, foreign address and state as well as Process ID (PID). You can use following command for it in linux.

 netstat -tulpn

iOS detect if user is on an iPad

Be Careful: If your app is targeting iPhone device only, iPad running with iphone compatible mode will return false for below statement:

#define IPAD     UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad

The right way to detect physical iPad device is:

#define IS_IPAD_DEVICE      ([(NSString *)[UIDevice currentDevice].model hasPrefix:@"iPad"])

How to iterate over a std::map full of strings in C++

Change your append calls to say

...append(iter->first)

and

... append(iter->second)

Additionally, the line

std::string* strToReturn = new std::string("");

allocates a string on the heap. If you intend to actually return a pointer to this dynamically allocated string, the return should be changed to std::string*.

Alternatively, if you don't want to worry about managing that object on the heap, change the local declaration to

std::string strToReturn("");

and change the 'append' calls to use reference syntax...

strToReturn.append(...)

instead of

strToReturn->append(...)

Be aware that this will construct the string on the stack, then copy it into the return variable. This has performance implications.

How to create a zip archive of a directory in Python?

So many answers here, and I hope I might contribute with my own version, which is based on the original answer (by the way), but with a more graphical perspective, also using context for each zipfile setup and sorting os.walk(), in order to have a ordered output.

Having these folders and them files (among other folders), I wanted to create a .zip for each cap_ folder:

$ tree -d
.
+-- cap_01
|    +-- 0101000001.json
|    +-- 0101000002.json
|    +-- 0101000003.json
|
+-- cap_02
|    +-- 0201000001.json
|    +-- 0201000002.json
|    +-- 0201001003.json
|
+-- cap_03
|    +-- 0301000001.json
|    +-- 0301000002.json
|    +-- 0301000003.json
| 
+-- docs
|    +-- map.txt
|    +-- main_data.xml
|
+-- core_files
     +-- core_master
     +-- core_slave

Here's what I applied, with comments for better understanding of the process.

$ cat zip_cap_dirs.py 
""" Zip 'cap_*' directories. """           
import os                                                                       
import zipfile as zf                                                            


for root, dirs, files in sorted(os.walk('.')):                                                                                               
    if 'cap_' in root:                                                          
        print(f"Compressing: {root}")                                           
        # Defining .zip name, according to Capítulo.                            
        cap_dir_zip = '{}.zip'.format(root)                                     
        # Opening zipfile context for current root dir.                         
        with zf.ZipFile(cap_dir_zip, 'w', zf.ZIP_DEFLATED) as new_zip:          
            # Iterating over os.walk list of files for the current root dir.    
            for f in files:                                                     
                # Defining relative path to files from current root dir.        
                f_path = os.path.join(root, f)                                  
                # Writing the file on the .zip file of the context              
                new_zip.write(f_path) 

Basically, for each iteration over os.walk(path), I'm opening a context for zipfile setup and afterwards, iterating iterating over files, which is a list of files from root directory, forming the relative path for each file based on the current root directory, appending to the zipfile context which is running.

And the output is presented like this:

$ python3 zip_cap_dirs.py
Compressing: ./cap_01
Compressing: ./cap_02
Compressing: ./cap_03

To see the contents of each .zip directory, you can use less command:

$ less cap_01.zip

Archive:  cap_01.zip
 Length   Method    Size  Cmpr    Date    Time   CRC-32   Name
--------  ------  ------- ---- ---------- ----- --------  ----
  22017  Defl:N     2471  89% 2019-09-05 08:05 7a3b5ec6  cap_01/0101000001.json
  21998  Defl:N     2471  89% 2019-09-05 08:05 155bece7  cap_01/0101000002.json
  23236  Defl:N     2573  89% 2019-09-05 08:05 55fced20  cap_01/0101000003.json
--------          ------- ---                           -------
  67251             7515  89%                            3 files

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

What is the location of mysql client ".my.cnf" in XAMPP for Windows?

Create it yourself in folder c:\xampp\mysql.

How to check if an email address is real or valid using PHP

You should check with SMTP.

That means you have to connect to that email's SMTP server.

After connecting to the SMTP server you should send these commands:

HELO somehostname.com
MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>

If you get "<[email protected]> Relay access denied" that means this email is Invalid.

There is a simple PHP class. You can use it:

http://www.phpclasses.org/package/6650-PHP-Check-if-an-e-mail-is-valid-using-SMTP.html

How do I run a single test using Jest?

npm test __tests__/filename.test.ts - to run a single file.

test.only('check single test', () => { expect(true).toBe(true)}); - to run a single test case

test.skip('to skip testcase, () => {expect(false).toBe(false_}); - to skip a test case

How to create an Excel File with Nodejs?

Use exceljs library for creating and writing into existing excel sheets.

You can check this tutorial for detailed explanation.

link

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

Recently I had same problem, but on Linux Server. Database was crashed, and I recovered it from backup, based on simply copying /var/lib/mysql/* (analog mysql DATA folder in wamp). After recovery I had to create new table and got mysql error #1146. I tried to restart mysql, and it said it could not start. I checked mysql logs, and found that mysql simply had no access rigths to its DB files. I checked owner info of /var/lib/mysql/*, and got 'myuser:myuser' (myuser is me). But it should be 'mysql:adm' (so is own developer machine), so I changed owner to 'mysql:adm'. And after this mysql started normally, and I could create tables, or do any other operations.

So after moving database files or restoring from backups check access rigths for mysql.

Hope this helps...

How to set the component size with GridLayout? Is there a better way?

Don't use GridLayout for something it wasn't meant to do. It sounds to me like GridBagLayout would be a better fit for you, either that or MigLayout (though you'll have to download that first since it's not part of standard Java). Either that or combine layout managers such as BoxLayout for the lines and GridLayout to hold all the rows.

For example, using GridBagLayout:

import java.awt.*;
import javax.swing.*;

public class LayoutEg1 extends JPanel{
    private static final int ROWS = 10;

    public LayoutEg1() {
        setLayout(new GridBagLayout());
        for (int i = 0; i < ROWS; i++) {
            GridBagConstraints gbc = makeGbc(0, i);
            JLabel label = new JLabel("Row Label " + (i + 1));
            add(label, gbc);

            JPanel panel = new JPanel();
            panel.add(new JCheckBox("check box"));
            panel.add(new JTextField(10));
            panel.add(new JButton("Button"));
            panel.setBorder(BorderFactory.createEtchedBorder());
            gbc = makeGbc(1, i);
            add(panel, gbc);
        }
    }

    private GridBagConstraints makeGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.weightx = x;
        gbc.weighty = 1.0;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = (x == 0) ? GridBagConstraints.LINE_START : GridBagConstraints.LINE_END;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        return gbc;
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("Layout Eg1");
        frame.getContentPane().add(new LayoutEg1());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

How do I work with a git repository within another repository?

I had issues with subtrees and submodules that the other answers suggest... mainly because I am using SourceTree and it seems fairly buggy.

Instead, I ended up using SymLinks and that seems to work well so I am posting it here as a possible alternative.

There is a complete guide here: http://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/

But basically you just need to mklink the two paths in an elevated command prompt. Make sure you use the /J hard link prefix. Something along these lines: mklink /J C:\projects\MainProject\plugins C:\projects\SomePlugin

You can also use relative folder paths and put it in a bat to be executed by each person when they first check out your project.

Example: mklink /J .\Assets\TaqtileTools ..\TaqtileHoloTools

Once the folder has been linked you may need to ignore the folder within your main repository that is referencing it. Otherwise you are good to go.

Note I've deleted my duplicate answer from another post as that post was marked as a duplicate question to this one.

Execute the setInterval function without delay the first time

There's a problem with immediate asynchronous call of your function, because standard setTimeout/setInterval has a minimal timeout about several milliseconds even if you directly set it to 0. It caused by a browser specific work.

An example of code with a REAL zero delay wich works in Chrome, Safari, Opera

function setZeroTimeout(callback) {
var channel = new MessageChannel();
channel.port1.onmessage = callback;
channel.port2.postMessage('');
}

You can find more information here

And after the first manual call you can create an interval with your function.

Custom height Bootstrap's navbar

your markup was a bit messed up. Here's the styles you need and proper html

CSS:

.navbar-brand,
.navbar-nav li a {
    line-height: 150px;
    height: 150px;
    padding-top: 0;
}

HTML:

<nav class="navbar navbar-default">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>

        <a class="navbar-brand" href="#"><img src="img/logo.png" /></a>
    </div>

    <div class="collapse navbar-collapse">
        <ul class="nav navbar-nav">
            <li><a href="">Portfolio</a></li>
            <li><a href="">Blog</a></li>
            <li><a href="">Contact</a></li>
        </ul>
    </div>
</nav>

Or check out the fiddle at: http://jsfiddle.net/TP5V8/1/

Is there a method for String conversion to Title Case?

There are no capitalize() or titleCase() methods in Java's String class. You have two choices:

 StringUtils.capitalize(null)  = null
 StringUtils.capitalize("")    = ""
 StringUtils.capitalize("cat") = "Cat"
 StringUtils.capitalize("cAt") = "CAt"
 StringUtils.capitalize("'cat'") = "'cat'"
  • write (yet another) static helper method toTitleCase()

Sample implementation

public static String toTitleCase(String input) {
    StringBuilder titleCase = new StringBuilder(input.length());
    boolean nextTitleCase = true;

    for (char c : input.toCharArray()) {
        if (Character.isSpaceChar(c)) {
            nextTitleCase = true;
        } else if (nextTitleCase) {
            c = Character.toTitleCase(c);
            nextTitleCase = false;
        }

        titleCase.append(c);
    }

    return titleCase.toString();
}

Testcase

    System.out.println(toTitleCase("string"));
    System.out.println(toTitleCase("another string"));
    System.out.println(toTitleCase("YET ANOTHER STRING"));

outputs:

String
Another String
YET ANOTHER STRING

Formatting Decimal places in R

Something like that :

options(digits=2)

Definition of digits option :

digits: controls the number of digits to print when printing numeric values.

AngularJS Folder Structure

I'm on my third angularjs app and the folder structure has improved every time so far. I keep mine simple right now.

index.html (or .php)
/resources
  /css
  /fonts
  /images
  /js
    /controllers
    /directives
    /filters
    /services
  /partials (views)

I find that good for single apps. I haven't really had a project yet where I'd need multiple.

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

With Python 3.8 this workes for me. For instance to execute a python script within the venv:

    import subprocess
    import sys
    res = subprocess.run([
              sys.executable,            # venv3.8/bin/python
              'main.py', '--help',], 
            stdout=PIPE, 
            text=True)
    print(res.stdout)

Iterate through Nested JavaScript Objects

- , ,

function forEachNested(O, f, cur){
    O = [ O ]; // ensure that f is called with the top-level object
    while (O.length) // keep on processing the top item on the stack
        if(
           !f( cur = O.pop() ) && // do not spider down if `f` returns true
           cur instanceof Object && // ensure cur is an object, but not null 
           [Object, Array].includes(cur.constructor) //limit search to [] and {}
        ) O.push.apply(O, Object.values(cur)); //search all values deeper inside
}

To use the above function, pass the array as the first argument and the callback function as the second argument. The callback function will receive 1 argument when called: the current item being iterated.

_x000D_
_x000D_
(function(){"use strict";

var cars = {"label":"Autos","subs":[{"label":"SUVs","subs":[]},{"label":"Trucks","subs":[{"label":"2 Wheel Drive","subs":[]},{"label":"4 Wheel Drive","subs":[{"label":"Ford","subs":[]},{"label":"Chevrolet","subs":[]}]}]},{"label":"Sedan","subs":[]}]};

var lookForCar = prompt("enter the name of the car you are looking for (e.g. 'Ford')") || 'Ford';
lookForCar = lookForCar.replace(/[^ \w]/g, ""); // incaseif the user put quotes or something around their input
lookForCar = lookForCar.toLowerCase();

var foundObject = null;
forEachNested(cars, function(currentValue){
    if(currentValue.constructor === Object &&
      currentValue.label.toLowerCase() === lookForCar) {
        foundObject = currentValue;
    }
});
if (foundObject !== null) {
    console.log("Found the object: " + JSON.stringify(foundObject, null, "\t"));
} else {
    console.log('Nothing found with a label of "' + lookForCar + '" :(');
}

function forEachNested(O, f, cur){
    O = [ O ]; // ensure that f is called with the top-level object
    while (O.length) // keep on processing the top item on the stack
        if(
           !f( cur = O.pop() ) && // do not spider down if `f` returns true
           cur instanceof Object && // ensure cur is an object, but not null 
           [Object, Array].includes(cur.constructor) //limit search to [] and {}
        ) O.push.apply(O, Object.values(cur)); //search all values deeper inside
}

})();
_x000D_
_x000D_
_x000D_

A "cheat" alternative might be to use JSON.stringify to iterate. HOWEVER, JSON.stringify will call the toString method of each object it passes over, which may produce undesirable results if you have your own special uses for the toString.

function forEachNested(O, f, v){
    typeof O === "function" ? O(v) : JSON.stringify(O,forEachNested.bind(0,f));
    return v; // so that JSON.stringify keeps on recursing
}

_x000D_
_x000D_
(function(){"use strict";

var cars = {"label":"Autos","subs":[{"label":"SUVs","subs":[]},{"label":"Trucks","subs":[{"label":"2 Wheel Drive","subs":[]},{"label":"4 Wheel Drive","subs":[{"label":"Ford","subs":[]},{"label":"Chevrolet","subs":[]}]}]},{"label":"Sedan","subs":[]}]};

var lookForCar = prompt("enter the name of the car you are looking for (e.g. 'Ford')") || 'Ford';
lookForCar = lookForCar.replace(/[^ \w]/g, ""); // incaseif the user put quotes or something around their input
lookForCar = lookForCar.toLowerCase();

var foundObject = null;
forEachNested(cars, function(currentValue){
    if(currentValue.constructor === Object &&
      currentValue.label.toLowerCase() === lookForCar) {
        foundObject = currentValue;
    }
});
if (foundObject !== null)
    console.log("Found the object: " + JSON.stringify(foundObject, null, "\t"));
else
    console.log('Nothing found with a label of "' + lookForCar + '" :(');

function forEachNested(O, f, v){
    typeof O === "function" ? O(v) : JSON.stringify(O,forEachNested.bind(0,f));
    return v; // so that JSON.stringify keeps on recursing
}
})();
_x000D_
_x000D_
_x000D_

However, while the above method might be useful for demonstration purposes, Object.values is not supported by Internet Explorer and there are many terribly illperformant places in the code:

  1. the code changes the value of input parameters (arguments) [lines 2 & 5],
  2. the code calls Array.prototype.push and Array.prototype.pop on every single item [lines 5 & 8],
  3. the code only does a pointer-comparison for the constructor which does not work on out-of-window objects [line 7],
  4. the code duplicates the array returned from Object.values [line 8],
  5. the code does not localize window.Object or window.Object.values [line 9],
  6. and the code needlessly calls Object.values on arrays [line 8].

Below is a much much faster version that should be far faster than any other solution. The solution below fixes all of the performance problems listed above. However, it iterates in a much different way: it iterates all the arrays first, then iterates all the objects. It continues to iterate its present type until complete exhaustion including iteration subvalues inside the current list of the current flavor being iterated. Then, the function iterates all of the other type. By iterating until exhaustion before switching over, the iteration loop gets hotter than otherwise and iterates even faster. This method also comes with an added advantage: the callback which is called on each value gets passed a second parameter. This second parameter is the array returned from Object.values called on the parent hash Object, or the parent Array itself.

var getValues = Object.values; // localize
var type_toString = Object.prototype.toString;
function forEachNested(objectIn, functionOnEach){
    "use strict";
    functionOnEach( objectIn );
    
    // for iterating arbitrary objects:
    var allLists = [  ];
    if (type_toString.call( objectIn ) === '[object Object]')
        allLists.push( getValues(objectIn) );
    var allListsSize = allLists.length|0; // the length of allLists
    var indexLists = 0;
    
    // for iterating arrays:
    var allArray = [  ];
    if (type_toString.call( objectIn ) === '[object Array]')
        allArray.push( objectIn );
    var allArraySize = allArray.length|0; // the length of allArray
    var indexArray = 0;
    
    do {
        // keep cycling back and forth between objects and arrays
        
        for ( ; indexArray < allArraySize; indexArray=indexArray+1|0) {
            var currentArray = allArray[indexArray];
            var currentLength = currentArray.length;
            for (var curI=0; curI < currentLength; curI=curI+1|0) {
                var arrayItemInner = currentArray[curI];
                if (arrayItemInner === undefined &&
                    !currentArray.hasOwnProperty(arrayItemInner)) {
                    continue; // the value at this position doesn't exist!
                }
                functionOnEach(arrayItemInner, currentArray);
                if (typeof arrayItemInner === 'object') {
                    var typeTag = type_toString.call( arrayItemInner );
                    if (typeTag === '[object Object]') {
                        // Array.prototype.push returns the new length
                        allListsSize=allLists.push( getValues(arrayItemInner) );
                    } else if (typeTag === '[object Array]') {
                        allArraySize=allArray.push( arrayItemInner );
                    }
                }
            }
            allArray[indexArray] = null; // free up memory to reduce overhead
        }
         
        for ( ; indexLists < allListsSize; indexLists=indexLists+1|0) {
            var currentList = allLists[indexLists];
            var currentLength = currentList.length;
            for (var curI=0; curI < currentLength; curI=curI+1|0) {
                var listItemInner = currentList[curI];
                functionOnEach(listItemInner, currentList);
                if (typeof listItemInner === 'object') {
                    var typeTag = type_toString.call( listItemInner );
                    if (typeTag === '[object Object]') {
                        // Array.prototype.push returns the new length
                        allListsSize=allLists.push( getValues(listItemInner) );
                    } else if (typeTag === '[object Array]') {
                        allArraySize=allArray.push( listItemInner );
                    }
                }
            }
            allLists[indexLists] = null; // free up memory to reduce overhead
        }
    } while (indexLists < allListsSize || indexArray < allArraySize);
}

_x000D_
_x000D_
(function(){"use strict";

var cars = {"label":"Autos","subs":[{"label":"SUVs","subs":[]},{"label":"Trucks","subs":[{"label":"2 Wheel Drive","subs":[]},{"label":"4 Wheel Drive","subs":[{"label":"Ford","subs":[]},{"label":"Chevrolet","subs":[]}]}]},{"label":"Sedan","subs":[]}]};

var lookForCar = prompt("enter the name of the car you are looking for (e.g. 'Ford')") || 'Ford';
lookForCar = lookForCar.replace(/[^ \w]/g, ""); // incaseif the user put quotes or something around their input
lookForCar = lookForCar.toLowerCase();





var getValues = Object.values; // localize
var type_toString = Object.prototype.toString;
function forEachNested(objectIn, functionOnEach){
    functionOnEach( objectIn );
    
    // for iterating arbitrary objects:
    var allLists = [  ];
    if (type_toString.call( objectIn ) === '[object Object]')
        allLists.push( getValues(objectIn) );
    var allListsSize = allLists.length|0; // the length of allLists
    var indexLists = 0;
    
    // for iterating arrays:
    var allArray = [  ];
    if (type_toString.call( objectIn ) === '[object Array]')
        allArray.push( objectIn );
    var allArraySize = allArray.length|0; // the length of allArray
    var indexArray = 0;
    
    do {
        // keep cycling back and forth between objects and arrays
        
        for ( ; indexArray < allArraySize; indexArray=indexArray+1|0) {
            var currentArray = allArray[indexArray];
            var currentLength = currentArray.length;
            for (var curI=0; curI < currentLength; curI=curI+1|0) {
                var arrayItemInner = currentArray[curI];
                if (arrayItemInner === undefined &&
                    !currentArray.hasOwnProperty(arrayItemInner)) {
                    continue; // the value at this position doesn't exist!
                }
                functionOnEach(arrayItemInner, currentArray);
                if (typeof arrayItemInner === 'object') {
                    var typeTag = type_toString.call( arrayItemInner );
                    if (typeTag === '[object Object]') {
                        // Array.prototype.push returns the new length
                        allListsSize=allLists.push( getValues(arrayItemInner) );
                    } else if (typeTag === '[object Array]') {
                        allArraySize=allArray.push( arrayItemInner );
                    }
                }
            }
            allArray[indexArray] = null; // free up memory to reduce overhead
        }
         
        for ( ; indexLists < allListsSize; indexLists=indexLists+1|0) {
            var currentList = allLists[indexLists];
            var currentLength = currentList.length;
            for (var curI=0; curI < currentLength; curI=curI+1|0) {
                var listItemInner = currentList[curI];
                functionOnEach(listItemInner, currentList);
                if (typeof listItemInner === 'object') {
                    var typeTag = type_toString.call( listItemInner );
                    if (typeTag === '[object Object]') {
                        // Array.prototype.push returns the new length
                        allListsSize=allLists.push( getValues(listItemInner) );
                    } else if (typeTag === '[object Array]') {
                        allArraySize=allArray.push( listItemInner );
                    }
                }
            }
            allLists[indexLists] = null; // free up memory to reduce overhead
        }
    } while (indexLists < allListsSize || indexArray < allArraySize);
}




var foundObject = null;
forEachNested(cars, function(currentValue){
    if(currentValue.constructor === Object &&
      currentValue.label.toLowerCase() === lookForCar) {
        foundObject = currentValue;
    }
});
if (foundObject !== null) {
    console.log("Found the object: " + JSON.stringify(foundObject, null, "\t"));
} else {
    console.log('Nothing found with a label of "' + lookForCar + '" :(');
}

})();
_x000D_
_x000D_
_x000D_

If you have a problem with circular references (e.g. having object A's values being object A itself in such as that object A contains itself), or you just need the keys then the following slower solution is available.

function forEachNested(O, f){
    O = Object.entries(O);
    var cur;
    function applyToEach(x){return cur[1][x[0]] === x[1]} 
    while (O.length){
        cur = O.pop();
        f(cur[0], cur[1]);
        if (typeof cur[1] === 'object' && cur[1].constructor === Object && 
          !O.some(applyToEach))
            O.push.apply(O, Object.entries(cur[1]));
    }
}

Because these methods do not use any recursion of any sort, these functions are well suited for areas where you might have thousands of levels of depth. The stack limit varies greatly from browser to browser, so recursion to an unknown depth is not very wise in Javascript.

How to disable and then enable onclick event on <div> with javascript

To enable use bind() method

$("#id").bind("click",eventhandler);

call this handler

 function  eventhandler(){
      alert("Bind click")
    }

To disable click useunbind()

$("#id").unbind("click");

How do I escape special characters in MySQL?

The information provided in this answer can lead to insecure programming practices.

The information provided here depends highly on MySQL configuration, including (but not limited to) the program version, the database client and character-encoding used.

See http://dev.mysql.com/doc/refman/5.0/en/string-literals.html

MySQL recognizes the following escape sequences.
\0     An ASCII NUL (0x00) character.
\'     A single quote (“'”) character.
\"     A double quote (“"”) character.
\b     A backspace character.
\n     A newline (linefeed) character.
\r     A carriage return character.
\t     A tab character.
\Z     ASCII 26 (Control-Z). See note following the table.
\\     A backslash (“\”) character.
\%     A “%” character. See note following the table.
\_     A “_” character. See note following the table.

So you need

select * from tablename where fields like "%string \"hi\" %";

Although as Bill Karwin notes below, using double quotes for string delimiters isn't standard SQL, so it's good practice to use single quotes. This simplifies things:

select * from tablename where fields like '%string "hi" %';

.toLowerCase not working, replacement function?

It's not an error. Javascript will gladly convert a number to a string when a string is expected (for example parseInt(42)), but in this case there is nothing that expect the number to be a string.

Here's a makeLowerCase function. :)

function makeLowerCase(value) {
  return value.toString().toLowerCase();
}

How to extend an existing JavaScript array with another array, without creating a new array

Update 2018: A better answer is a newer one of mine: a.push(...b). Don't upvote this one anymore, as it never really answered the question, but it was a 2015 hack around first-hit-on-Google :)


For those that simply searched for "JavaScript array extend" and got here, you can very well use Array.concat.

var a = [1, 2, 3];
a = a.concat([5, 4, 3]);

Concat will return a copy the new array, as thread starter didn't want. But you might not care (certainly for most kind of uses this will be fine).


There's also some nice ECMAScript 6 sugar for this in the form of the spread operator:

const a = [1, 2, 3];
const b = [...a, 5, 4, 3];

(It also copies.)

How can I solve the error LNK2019: unresolved external symbol - function?

It turned out I was using .c files with .cpp files. Renaming .c to .cpp solved my problem.

How to add double quotes to a string that is inside a variable?

in C# if we use "\" means that will indicate following symbol is not c# inbuild symbol that will use by developer. so in string we need double quotes means we can put "\" symbol before double quotes. string s = "\"Hi\""

Reading int values from SqlDataReader

This should work:

txtfarmersize = Convert.ToInt32(reader["farmsize"]);

How to show/hide an element on checkbox checked/unchecked states using jQuery?

    <label  onclick="chkBulk();">
    <div class="icheckbox_flat-green" style="position: relative;">
      <asp:CheckBox ID="chkBulkAssign" runat="server" class="flat" 
       Style="position: 
         absolute; opacity: 0;" />
      </div>
      Bulk Assign
     </label>



    function chkBulk() {
    if ($('[id$=chkBulkAssign]')[0].checked) {
    $('div .icheckbox_flat-green').addClass('checked');
    $("[id$=btneNoteBulkExcelUpload]").show();           
    }
   else {
   $('div .icheckbox_flat-green').removeClass('checked');
   $("[id$=btneNoteBulkExcelUpload]").hide();
   } 

How much faster is C++ than C#?

I've tested vector in C++ and C# equivalent - List and simple 2d arrays.

I'm using Visual C#/C++ 2010 Express editions. Both projects are simple console applications, I've tested them in standard (no custom settings) release and debug mode. C# lists run faster on my pc, array initialization is also faster in C#, math operations are slower.

I'm using Intel Core2Duo [email protected], C# - .NET 4.0.

I know that vector implementation is different than C# list, but I just wanted to test collections that I would use to store my objects (and being able to use index accessor).

Of course you need to clear memory (let's say for every use of new), but I wanted to keep the code simple.

C++ vector test:

static void TestVector()
{
    clock_t start,finish;
    start=clock();
    vector<vector<double>> myList=vector<vector<double>>();
    int i=0;
    for( i=0; i<500; i++)
    {
        myList.push_back(vector<double>());
        for(int j=0;j<50000;j++)
            myList[i].push_back(j+i);
    }
    finish=clock();
    cout<<(finish-start)<<endl;
    cout<<(double(finish - start)/CLOCKS_PER_SEC);
}

C# list test:

private static void TestVector()
{

    DateTime t1 = System.DateTime.Now;
    List<List<double>> myList = new List<List<double>>();
    int i = 0;
    for (i = 0; i < 500; i++)
    {
        myList.Add(new List<double>());
        for (int j = 0; j < 50000; j++)
            myList[i].Add(j *i);
    }
    DateTime t2 = System.DateTime.Now;
    Console.WriteLine(t2 - t1);
}

C++ - array:

static void TestArray()
{
    cout << "Normal array test:" << endl;
    const int rows = 5000;
    const int columns = 9000;
    clock_t start, finish;

    start = clock();
    double** arr = new double*[rows];
    for (int i = 0; i < rows; i++)
        arr[i] = new double[columns];
    finish = clock();

    cout << (finish - start) << endl;

    start = clock();
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < columns; j++)
            arr[i][j] = i * j;
    finish = clock();

    cout << (finish - start) << endl;
}

C# - array:

private static void TestArray()
{
    const int rows = 5000;
    const int columns = 9000;
    DateTime t1 = System.DateTime.Now;
    double[][] arr = new double[rows][];
    for (int i = 0; i < rows; i++)
        arr[i] = new double[columns];
    DateTime t2 = System.DateTime.Now;

    Console.WriteLine(t2 - t1);

    t1 = System.DateTime.Now;
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < columns; j++)
            arr[i][j] = i * j;
    t2 = System.DateTime.Now;

    Console.WriteLine(t2 - t1);

}

Time: (Release/Debug)

C++

  • 600 / 606 ms array init,
  • 200 / 270 ms array fill,
  • 1sec /13sec vector init & fill.

(Yes, 13 seconds, I always have problems with lists/vectors in debug mode.)

C#:

  • 20 / 20 ms array init,
  • 403 / 440 ms array fill,
  • 710 / 742 ms list init & fill.

Viewing root access files/folders of android on windows

If you have android, you can install free app on phone (Wifi file Transfer) and enable ssl, port and other options for access and send data in both directions just start application and write in pc browser phone ip and port. enjoy!

How to Migrate to WKWebView?

UIWebView will still continue to work with existing apps. WKWebView is available starting from iOS8, only WKWebView has a Nitro JavaScript engine.

To take advantage of this faster JavaScript engine in older apps you have to make code changes to use WKWebView instead of UIWebView. For iOS7 and older, you have to continue to use UIWebView, so you may have to check for iOS8 and then apply WKWebView methods / delegate methods and fallback to UIWebView methods for iOS7 and older. Also there is no Interface Builder component for WKWebView (yet), so you have to programmatically implement WKWebView.

You can implement WKWebView in Objective-C, here is simple example to initiate a WKWebView:

WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
webView.navigationDelegate = self;
NSURL *nsurl=[NSURL URLWithString:@"http://www.apple.com"];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[webView loadRequest:nsrequest];
[self.view addSubview:webView];

WKWebView rendering performance is noticeable in WebGL games and something that runs complex JavaScript algorithms, if you are using webview to load a simple html or website, you can continue to use UIWebView.

Here is a test app that can used to open any website using either UIWebView or WKWebView and you can compare performance, and then decide on upgrading your app to use WKWebView: https://itunes.apple.com/app/id928647773?mt=8&at=10ltWQ

enter image description here

SQL Add foreign key to existing column

In the future.

ALTER TABLE Employees
ADD UserID int;

ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
    REFERENCES ActiveDirectories(id);

using where and inner join in mysql

You can use as many joins as you want, however, the more you use the more it will impact performance

Find distance between two points on map using Google Map API V2

You should use the android Location

You can do:

location1.distanceTo(location2);

And also:

float[] results = new float[1];
Location.distanceBetween(latLongA.latitude, latLongA.longitude,
                         latLongB.latitude, latLongB.longitude,
                         results);

And you will get the distance in meters between location1 and location2 in meters. And beetween latLongA ant latLongB.

Using location.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When indicating HTTP Basic Authentication we return something like:

WWW-Authenticate: Basic realm="myRealm"

Whereas Basic is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.

You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.

From recollection, Windows Challenge Response uses a different scheme and different arguments.

The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.

My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.

For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.

Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.

The other alternative is burn the AJAX request but that's a poor user experience.

What do column flags mean in MySQL Workbench?

This exact question is answered on mySql workbench-faq:

Hover over an acronym to view a description, and see the Section 8.1.11.2, “The Columns Tab” and MySQL CREATE TABLE documentation for additional details.

That means hover over an acronym in the mySql Workbench table editor.

Section 8.1.11.2, “The Columns Tab”

Python: create dictionary using dict() with integer keys?

a = dict(one=1, two=2, three=3)

Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

Editing in the Chrome debugger

I came across this today, when I was playing around with someone else's website.

I realized I could attach a break-point in the debugger to some line of code before what I wanted to dynamically edit. And since break-points stay even after a reload of the page, I was able to edit the changes I wanted while paused at break-point and then continued to let the page load.

So as a quick work around, and if it works with your situation:

  1. Add a break-point at an earlier point in the script
  2. Reload page
  3. Edit your changes into the code
  4. CTRL + s (save changes)
  5. Unpause the debugger

What is the difference between a string and a byte string?

The only thing that a computer can store is bytes.

To store anything in a computer, you must first encode it, i.e. convert it to bytes. For example:

  • If you want to store music, you must first encode it using MP3, WAV, etc.
  • If you want to store a picture, you must first encode it using PNG, JPEG, etc.
  • If you want to store text, you must first encode it using ASCII, UTF-8, etc.

MP3, WAV, PNG, JPEG, ASCII and UTF-8 are examples of encodings. An encoding is a format to represent audio, images, text, etc in bytes.

In Python, a byte string is just that: a sequence of bytes. It isn't human-readable. Under the hood, everything must be converted to a byte string before it can be stored in a computer.

On the other hand, a character string, often just called a "string", is a sequence of characters. It is human-readable. A character string can't be directly stored in a computer, it has to be encoded first (converted into a byte string). There are multiple encodings through which a character string can be converted into a byte string, such as ASCII and UTF-8.

'I am a string'.encode('ASCII')

The above Python code will encode the string 'I am a string' using the encoding ASCII. The result of the above code will be a byte string. If you print it, Python will represent it as b'I am a string'. Remember, however, that byte strings aren't human-readable, it's just that Python decodes them from ASCII when you print them. In Python, a byte string is represented by a b, followed by the byte string's ASCII representation.

A byte string can be decoded back into a character string, if you know the encoding that was used to encode it.

b'I am a string'.decode('ASCII')

The above code will return the original string 'I am a string'.

Encoding and decoding are inverse operations. Everything must be encoded before it can be written to disk, and it must be decoded before it can be read by a human.

jQuery get content between <div> tags

This is probably what you need:

$('div').html();

demo

This says get the div and return all the contents inside it. See more here: http://api.jquery.com/html/

If you had many divs on the page and needed to target just one, you could set an id on the div and call it like so

$('#whatever').html();

where whatever is the id

EDIT

Now that you have clarified your question re this being a string, here is a way to do it with vanilla js:

var l = x.length;
var y = x.indexOf('<div>');
var s = x.slice(y,l);
alert(s);

Demo Here

  1. get the length of the string.
  2. find out where the first div occurs
  3. slice the content there.

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

In my case the problem was ASP.NET debugging wasn't enabled under project properties>>Web

Android view pager with page indicator

you have to do following:

1-Download the full project from here https://github.com/JakeWharton/ViewPagerIndicator ViewPager Indicator 2- Import into the Eclipse.

After importing if you want to make following type of screen then follow below steps -

Screen Shot

change in

Sample circles Default

  package com.viewpagerindicator.sample;
  import android.os.Bundle;  
  import android.support.v4.view.ViewPager;
  import com.viewpagerindicator.CirclePageIndicator;

  public class SampleCirclesDefault extends BaseSampleActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_circles);

    mAdapter = new TestFragmentAdapter(getSupportFragmentManager());

    mPager = (ViewPager)findViewById(R.id.pager);
  //  mPager.setAdapter(mAdapter);

    ImageAdapter adapter = new ImageAdapter(SampleCirclesDefault.this);
    mPager.setAdapter(adapter);


    mIndicator = (CirclePageIndicator)findViewById(R.id.indicator);
    mIndicator.setViewPager(mPager);
  }
}

ImageAdapter

 package com.viewpagerindicator.sample;

 import android.content.Context;
 import android.support.v4.view.PagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ImageView;
 import android.widget.TextView;

 public class ImageAdapter extends PagerAdapter {
 private Context mContext;

 private Integer[] mImageIds = { R.drawable.about1, R.drawable.about2,
        R.drawable.about3, R.drawable.about4, R.drawable.about5,
        R.drawable.about6, R.drawable.about7

 };

 public ImageAdapter(Context context) {
    mContext = context;
 }

 public int getCount() {
    return mImageIds.length;
 }

 public Object getItem(int position) {
    return position;
 }

 public long getItemId(int position) {
    return position;
 }

 @Override
 public Object instantiateItem(ViewGroup container, final int position) {

    LayoutInflater inflater = (LayoutInflater) container.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View convertView = inflater.inflate(R.layout.gallery_view, null);

    ImageView view_image = (ImageView) convertView
            .findViewById(R.id.view_image);
    TextView description = (TextView) convertView
            .findViewById(R.id.description);

    view_image.setImageResource(mImageIds[position]);
    view_image.setScaleType(ImageView.ScaleType.FIT_XY);

    description.setText("The natural habitat of the Niligiri tahr,Rajamala          Rajamala is 2695 Mts above sea level"
        + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level"
                    + "The natural habitat of the Niligiri tahr,Rajamala Rajamala is 2695 Mts above sea level");

    ((ViewPager) container).addView(convertView, 0);

    return convertView;
 }

 @Override
 public boolean isViewFromObject(View view, Object object) {
    return view == ((View) object);
 }

 @Override
 public void destroyItem(ViewGroup container, int position, Object object) {
    ((ViewPager) container).removeView((ViewGroup) object);
 }
}

gallery_view.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/about_bg"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/about_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1" >

    <LinearLayout
        android:id="@+id/about_layout1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".4"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/view_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent" 
            android:background="@drawable/about1">
     </ImageView>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/about_layout2"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight=".6"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SIGNATURE LANDMARK OF MALAYSIA-SINGAPORE CAUSEWAY"
            android:textColor="#000000"
            android:gravity="center"
            android:padding="18dp"
            android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearance" />


        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:fillViewport="false"
            android:orientation="vertical"
            android:scrollbars="none"
            android:layout_marginBottom="10dp"
            android:padding="10dp" >

            <TextView
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="#000000"
                android:text="TextView" />

            </ScrollView>
    </LinearLayout>
 </LinearLayout>

Compare two different files line by line in python

This solution reads both files in one pass, excludes blank lines, and prints common lines regardless of their position in the file:

with open('some_file_1.txt', 'r') as file1:
    with open('some_file_2.txt', 'r') as file2:
        same = set(file1).intersection(file2)

same.discard('\n')

with open('some_output_file.txt', 'w') as file_out:
    for line in same:
        file_out.write(line)

How to round a number to n decimal places in Java

double myNum = .912385;
int precision = 10000; //keep 4 digits
myNum= Math.floor(myNum * precision +.5)/precision;

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

Not all servers support jsonp. It requires the server to set the callback function in it's results. I use this to get json responses from sites that return pure json but don't support jsonp:

function AjaxFeed(){

    return $.ajax({
        url:            'http://somesite.com/somejsonfile.php',
        data:           {something: true},
        dataType:       'jsonp',

        /* Very important */
        contentType:    'application/json',
    });
}

function GetData() {
    AjaxFeed()

    /* Everything worked okay. Hooray */
    .done(function(data){
        return data;
    })

    /* Okay jQuery is stupid manually fix things */
    .fail(function(jqXHR) {

        /* Build HTML and update */
        var data = jQuery.parseJSON(jqXHR.responseText);

        return data;
    });
}

Use of "this" keyword in formal parameters for static methods in C#

In addition to Preet Sangha's explanation:
Intellisense displays the extension methods with a blue arrow (e.g. in front of "Aggregate<>"):

enter image description here

You need a

using the.namespace.of.the.static.class.with.the.extension.methods;

for the extension methods to appear and to be available, if they are in a different namespace than the code using them.

Weird PHP error: 'Can't use function return value in write context'

This can happen in more than one scenario, below is a list of well known scenarios :

// calling empty on a function 
empty(myFunction($myVariable)); // the return value of myFunction should be saved into a variable
// then you can use empty on your variable

// using parenthesis to access an element of an array, parenthesis are used to call a function

if (isset($_POST('sms_code') == TRUE ) { ...
// that should be if(isset($_POST['sms_code']) == TRUE)

This also could be triggered when we try to increment the result of a function like below:

$myCounter = '356';

$myCounter = intVal($myCounter)++; // we try to increment the result of the intVal...
// like the first case, the ++ needs to be called on a variable, a variable should hold the the return of the function then we can call ++ operator on it.

How to validate an e-mail address in swift?

I improved @Azik answer. I allow more special characters which are allowed by guidelines, as well as return a few extra edge cases as invalid.

The group think going on here to only allow ._%+- in the local part is not correct per guidelines. See @Anton Gogolev answer on this question or see below:

The local-part of the email address may use any of these ASCII characters:

  • uppercase and lowercase Latin letters A to Z and a to z;

  • digits 0 to 9;

  • special characters !#$%&'*+-/=?^_`{|}~;

  • dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. [email protected] is not allowed but "John..Doe"@example.com is allowed);

  • space and "(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash); comments are allowed

  • with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)[email protected] are both equivalent to [email protected];

The code I use will not allow restricted out of place special characters, but will allow many more options than the majority of answers here. I would prefer more relaxed validation to error on the side of caution.

if enteredText.contains("..") || enteredText.contains("@@") 
   || enteredText.hasPrefix(".") || enteredText.hasSuffix(".con"){
       return false
}

let emailFormat = "[A-Z0-9a-z.!#$%&'*+-/=?^_`{|}~]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)     
return emailPredicate.evaluate(with: enteredText)

How to control font sizes in pgf/tikz graphics in latex?

\begin{tikzpicture}
    \tikzstyle{every node}=[font=\fontsize{30}{30}\selectfont]
\end{tikzpicture}

How to save local data in a Swift app?

Using NSCoding and NSKeyedArchiver is another great option for data that's too complex for NSUserDefaults, but for which CoreData would be overkill. It also gives you the opportunity to manage the file structure more explicitly, which is great if you want to use encryption.

SQLAlchemy IN clause

How about

session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()

edit: Without the ORM, it would be

session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name], 
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

select() takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.

What is the role of the bias in neural networks?

Just to add my two cents.

A simpler way to understand what the bias is: it is somehow similar to the constant b of a linear function

y = ax + b

It allows you to move the line up and down to fit the prediction with the data better. Without b the line always goes through the origin (0, 0) and you may get a poorer fit.

jQuery DataTables Getting selected row values

More a comment than an answer - but I cannot add comments yet: Thanks for your help, the count was the easy part. Just for others that might come here. I hope that it will save you some time.

It took me a while to get the attributes from the rows and to understand how to access them from the data() Object (that the data() is an Array and the Attributes can be read by adding them with a dot and not with brackets:

$('#button').click( function () {
    for (var i = 0; i < table.rows('.selected').data().length; i++) { 
       console.log( table.rows('.selected').data()[i].attributeNameFromYourself);
    }
} );

(by the way: I get the data for my table using AJAX and JSON)

Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

Drawing rotated text on a HTML5 canvas

Funkodebat posted a great solution which I have referenced many times. Still, I find myself writing my own working model each time I need this. So, here is my working model... with some added clarity.

First of all, the height of the text is equal to the pixel font size. Now, this was something I read a while ago, and it has worked out in my calculations. I'm not sure if this works with all fonts, but it seems to work with Arial, sans-serif.

Also, to make sure that you fit all of the text in your canvas (and don't trim the tails off of your "p"'s) you need to set context.textBaseline*.

You will see in the code that we are rotating the text about its center. To do this, we need to set context.textAlign = "center" and the context.textBaseline to bottom, otherwise, we trim off parts of our text.

Why resize the canvas? I usually have a canvas that isn't appended to the page. I use it to draw all of my rotated text, then I draw it onto another canvas which I display. For example, you can use this canvas to draw all of the labels for a chart (one by one) and draw the hidden canvas onto the chart canvas where you need the label (context.drawImage(hiddenCanvas, 0, 0);).

IMPORTANT NOTE: Set your font before measuring your text, and re-apply all of your styling to the context after resizing your canvas. A canvas's context is completely reset when the canvas is resized.

Hope this helps!

_x000D_
_x000D_
var c = document.getElementById("myCanvas");_x000D_
var ctx = c.getContext("2d");_x000D_
var font, text, x, y;_x000D_
_x000D_
text = "Mississippi";_x000D_
_x000D_
//Set font size before measuring_x000D_
font = 20;_x000D_
ctx.font = font + 'px Arial, sans-serif';_x000D_
//Get width of text_x000D_
var metrics = ctx.measureText(text);_x000D_
//Set canvas dimensions_x000D_
c.width = font;//The height of the text. The text will be sideways._x000D_
c.height = metrics.width;//The measured width of the text_x000D_
//After a canvas resize, the context is reset. Set the font size again_x000D_
ctx.font = font + 'px Arial';_x000D_
//Set the drawing coordinates_x000D_
x = font/2;_x000D_
y = metrics.width/2;_x000D_
//Style_x000D_
ctx.fillStyle = 'black';_x000D_
ctx.textAlign = 'center';_x000D_
ctx.textBaseline = "bottom";_x000D_
//Rotate the context and draw the text_x000D_
ctx.save();_x000D_
ctx.translate(x, y);_x000D_
ctx.rotate(-Math.PI / 2);_x000D_
ctx.fillText(text, 0, font / 2);_x000D_
ctx.restore();
_x000D_
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
_x000D_
_x000D_
_x000D_

Java Programming: call an exe from Java and passing parameters

You're on the right track. The two constructors accept arguments, or you can specify them post-construction with ProcessBuilder#command(java.util.List) and ProcessBuilder#command(String...).

How to get the values of a ConfigurationSection of type NameValueSectionHandler

Suffered from exact issue. Problem was because of NameValueSectionHandler in .config file. You should use AppSettingsSection instead:

<configuration>

 <configSections>
    <section  name="DEV" type="System.Configuration.AppSettingsSection" />
    <section  name="TEST" type="System.Configuration.AppSettingsSection" />
 </configSections>

 <TEST>
    <add key="key" value="value1" />
 </TEST>

 <DEV>
    <add key="key" value="value2" />
 </DEV>

</configuration>

then in C# code:

AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST");

btw NameValueSectionHandler is not supported any more in 2.0.

Why Would I Ever Need to Use C# Nested Classes

what I don't get is why I would ever need to do this

I think you never need to do this. Given a nested class like this ...

class A
{
  //B is used to help implement A
  class B
  {
    ...etc...
  }
  ...etc...
}

... you can always move the inner/nested class to global scope, like this ...

class A
{
  ...etc...
}

//B is used to help implement A
class B
{
  ...etc...
}

However, when B is only used to help implement A, then making B an inner/nested class has two advantages:

  • It doesn't pollute the global scope (e.g. client code which can see A doesn't know that the B class even exists)
  • The methods of B implicitly have access to private members of A; whereas if B weren't nested inside A, B wouldn't be able to access members of A unless those members were internal or public; but then making those members internal or public would expose them to other classes too (not just B); so instead, keep those methods of A private and let B access them by declaring B as a nested class. If you know C++, this is like saying that in C# all nested classes are automatically a 'friend' of the class in which they're contained (and, that declaring a class as nested is the only way to declare friendship in C#, since C# doesn't have a friend keyword).

When I say that B can access private members of A, that's assuming that B has a reference to A; which it often does, since nested classes are often declared like this ...

class A
{
  //used to help implement A
  class B
  {
    A m_a;
    internal B(A a) { m_a = a; }
    ...methods of B can access private members of the m_a instance...
  }
  ...etc...
}

... and constructed from a method of A using code like this ...

//create an instance of B, whose implementation can access members of self
B b = new B(this);

You can see an example in Mehrdad's reply.

Recursive directory listing in DOS

You can get the parameters you are asking for by typing:

dir /?

For the full list, try:

dir /s /b /a:d

TypeScript: Creating an empty typed container array

Please try this which it works for me.

return [] as Criminal[];

How can I get zoom functionality for images?

This is a very late addition to this thread but I've been working on an image view that supports zoom and pan and has a couple of features I haven't found elsewhere. This started out as a way of displaying very large images without causing OutOfMemoryErrors, by subsampling the image when zoomed out and loading higher resolution tiles when zoomed in. It now supports use in a ViewPager, rotation manually or using EXIF information (90° stops), override of selected touch events using OnClickListener or your own GestureDetector or OnTouchListener, subclassing to add overlays, pan while zooming, and fling momentum.

It's not intended as a general use replacement for ImageView so doesn't extend it, and doesn't support display of images from resources, only assets and external files. It requires SDK 10.

Source is on GitHub, and there's a sample that illustrates use in a ViewPager.

https://github.com/davemorrissey/subsampling-scale-image-view

Redirect from a view to another view

It's because your statement does not produce output.

Besides all the warnings of Darin and lazy (they are right); the question still offerst something to learn.

If you want to execute methods that don't directly produce output, you do:

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

This is also true for rendering partials like:

@{ Html.RenderPartial("_MyPartial"); }

How to merge multiple dicts with same key or different key?

A compact possibility

d1={'a':1,'b':2}
d2={'c':3,'d':4}
context={**d1, **d2}
context
{'b': 2, 'c': 3, 'd': 4, 'a': 1}

How to remove items from a list while iterating?

Most of the answers here want you to create a copy of the list. I had a use case where the list was quite long (110K items) and it was smarter to keep reducing the list instead.

First of all you'll need to replace foreach loop with while loop,

i = 0
while i < len(somelist):
    if determine(somelist[i]):
         del somelist[i]
    else:
        i += 1

The value of i is not changed in the if block because you'll want to get value of the new item FROM THE SAME INDEX, once the old item is deleted.

WPF global exception handler

In addition to the posts above:

Application.Current.DispatcherUnhandledException

will not catch exceptions that are thrown from a thread other than the main thread. You have to catch those exceptions on the same thread they are thrown. But if you want to Handle them on your global exception handler you can pass it to the main thread:

 System.Threading.Thread t = new System.Threading.Thread(() =>
    {
        try
        {
            ...
            //this exception will not be catched by 
            //Application.DispatcherUnhandledException
            throw new Exception("huh..");
            ...
        }
        catch (Exception ex)
        {
            //But we can handle it in the throwing thread
            //and pass it to the main thread wehre Application.
            //DispatcherUnhandledException can handle it
            System.Windows.Application.Current.Dispatcher.Invoke(
                System.Windows.Threading.DispatcherPriority.Normal,
                new Action<Exception>((exc) =>
                    {
                      throw new Exception("Exception from another Thread", exc);
                    }), ex);
        }
    });

How to set a Postgresql default value datestamp like 'YYYYMM'?

Thanks for everyone who answered, and thanks for those who gave me the function-format idea, i'll really study it for future using.

But for this explicit case, the 'special yyyymm field' is not to be considered as a date field, but just as a tag, o whatever would be used for matching the exactly year-month researched value; there is already another date field, with the full timestamp, but if i need all the rows of january 2008, i think that is faster a select like

SELECT  [columns] FROM table WHERE yearmonth = '200801'

instead of

SELECT  [columns] FROM table WHERE date BETWEEN DATE('2008-01-01') AND DATE('2008-01-31')

Lock down Microsoft Excel macro

You can check out this new product at http://hivelink.io, it allows you to properly protect your sensitive macros.

The Excel password system is extremely weak - you can crack it in 2 minutes just using a basic HEX editor. I wouldn't recommend relying on this to protect anything.

I wrote an extensive post on this topic here: Protecting Code in an Excel Workbook?

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

Do the following.

  1. Close the sdk manager and eclipse.

  2. Go to the folder where you have stored your adt.

  3. In that adt folder you'll find a folder known as tools.

  4. Make a copy of the contents of that folder and paste it in a folder called copytools.

  5. Now go to the command prompt and go to the location of the copytools.

  6. Then execute the command android.bat the sdk manager will start.

  7. Now update all the plugins you want. It'll update your original folder.

  8. After the update delete the copy.

Enjoy. Hope this helps.

Adding days to $Date in PHP

All you have to do is use days instead of day like this:

<?php
$Date = "2010-09-17";
echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo date('Y-m-d', strtotime($Date. ' + 2 days'));
?>

And it outputs correctly:

2010-09-18
2010-09-19

Mockito How to mock only the call of a method of the superclass

The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or @Override in sub class (as public), then Mockito can mock it correctly.

public class BaseService{
  public boolean foo(){
    return true;
  }
}

public ChildService extends BaseService{
}

@Test
@Mock ChildService childService;
public void testSave() {
  Mockito.when(childService.foo()).thenReturn(false);

  // When
  assertFalse(childService.foo());
}

Naming convention - underscore in C++ and C# variables

Now the notation using "this" as in this.foobarbaz is acceptable for C# class member variables. It replaces the old "m_" or just "__" notation. It does make the code more readable because there is no doubt what is being reference.

Can I override and overload static methods in Java?

You can overload a static method but you can't override a static method. Actually you can rewrite a static method in subclasses but this is not called a override because override should be related to polymorphism and dynamic binding. The static method belongs to the class so has nothing to do with those concepts. The rewrite of static method is more like a shadowing.

How can I round a number in JavaScript? .toFixed() returns a string?

Why not use parseFloat?

var someNumber = 123.456;
someNumber = parseFloat(someNumber.toFixed(2));
alert(typeof(someNumber));
//alerts number

Android fastboot waiting for devices

The short version of the page linked by D Shu (and without the horrible popover ads) is that this "waiting for device" problem happens when the USB device node is not accessible to your current user. The USB id is different in fastboot mode, so you can easily have permission to it in adb but not in fastboot.

To fix it (on Ubuntu; other systems may be slightly different):

Run lsusb -v | less and find the relevant section which will look something like this:

Bus 001 Device 027: ID 18d1:4e30 Google Inc. 
Couldn't open device, some information will be missing
Device Descriptor:
...
  idVendor           0x18d1 Google Inc.

Now do

sudo vi /etc/udev/rules.d/11-android.rules

it's ok if that file does not yet exist; create it with a line like this, inserting your own username and vendor id:

SUBSYSTEMS=="usb", ATTRS{idVendor}=="18d1", MODE="0640", OWNER="mbp"

then

sudo service udev restart

then verify the device node permissions have changed:

ls -Rl /dev/bus/usb

The even shorter cheesy version is to just run fastboot as root. But then you need to run every command that talks to the device as root, which tends to cause other complications. Simpler just to fix the permissions in the long run.

Sending HTML mail using a shell script

cat > mail.txt <<EOL
To: <email>
Subject: <subject>
Content-Type: text/html

<html>
$(cat <report-table-*.html>)
This report in <a href="<url>">SVN</a>
</html>

EOL

And then:

sendmail -t < mail.txt

Trying to get property of non-object - CodeIgniter

To access the elements in the array, use array notation: $product['prodname']

$product->prodname is object notation, which can only be used to access object attributes and methods.

How do I POST a x-www-form-urlencoded request using Fetch?

For uploading Form-Encoded POST requests, I recommend using the FormData object.

Example code:

var params = {
    userName: '[email protected]',
    password: 'Password!',
    grant_type: 'password'
};

var formData = new FormData();

for (var k in params) {
    formData.append(k, params[k]);
}

var request = {
    method: 'POST',
    headers: headers,
    body: formData
};

fetch(url, request);

Implement an input with a mask

Below i describe my method. I set event on input in input, to call Masking() method, which will return an formatted string of that we insert in input.

Html:

<input name="phone" pattern="+373 __ ___ ___" class="masked" required>

JQ: Here we set event on input:

$('.masked').on('input', function () {
    var input = $(this);
    input.val(Masking(input.val(), input.attr('pattern')));
});

JS: Function, which will format string by pattern;

function Masking (value, pattern) {
var out = '';
var space = ' ';
var any = '_';

for (var i = 0, j = 0; j < value.length; i++, j++) {
    if (value[j] === pattern[i]) {
        out += value[j];
    }
    else if(pattern[i] === any && value[j] !== space) {
        out += value[j];
    }
    else if(pattern[i] === space && value[j] !== space) {
        out += space;
        j--;
    }
    else if(pattern[i] !== any && pattern[i] !== space) {
        out += pattern[i];
        j--;
    }
}

return out;
}

best way to create object

In my humble opinion, this is just a matter of deciding if the arguments are optional or not. If an Person object shouldn't (logically) exist without Name and Age, they should be mandatory in the constructor. If they are optional, (i.e. their absence is not a threat to the good functioning of the object), use the setters.

Here's a quote from Symfony's docs on constructor injection:

There are several advantages to using constructor injection:

  • If the dependency is a requirement and the class cannot work without it then injecting it via the constructor ensures it is present when the class is used as the class cannot be constructed without it.
  • The constructor is only ever called once when the object is created, so you can be sure that the dependency will not change during the object's lifetime.

These advantages do mean that constructor injection is not suitable for working with optional dependencies. It is also more difficult to use in combination with class hierarchies: if a class uses constructor injection then extending it and overriding the constructor becomes problematic.

(Symfony is one of the most popular and respected php frameworks)

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

replace

implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

with

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

Since the version with jre is absolute , just replace and sync the project

Official Documentation here Thanks for the link @ ROMANARMY

Happy Coding :)

Copy data from one existing row to another existing row in SQL?

Copy a value from one row to any other qualified rows within the same table (or different tables):

UPDATE `your_table` t1, `your_table` t2
SET t1.your_field = t2.your_field
WHERE t1.other_field = some_condition
AND t1.another_field = another_condition
AND t2.source_id = 'explicit_value'

Start off by aliasing the table into 2 unique references so the SQL server can tell them apart

Next, specify the field(s) to copy.

Last, specify the conditions governing the selection of the rows

Depending on the conditions you may copy from a single row to a series, or you may copy a series to a series. You may also specify different tables, and you can even use sub-selects or joins to allow using other tables to control the relationships.

PyCharm shows unresolved references error for valid code

If none of the other solutions work for you, try (backing up) and deleting your ~/.PyCharm40 folder, then reopening PyCharm. This will kill all your preferences as well.

On Mac you want to delete ~/Library/Caches/Pycharm40 and ~/Library/Preferences/PyCharm40.

And on Windows: C:\Users\$USER.PyCharm40.

How can I count the number of children?

You don't need jQuery for this. You can use JavaScript's .childNodes.length.

Just make sure to subtract 1 if you don't want to include the default text node (which is empty by default). Thus, you'd use the following:

var count = elem.childNodes.length - 1;

C++ - Decimal to binary converting

// function to convert decimal to binary
void decToBinary(int n)
{
    // array to store binary number
    int binaryNum[1000];

    // counter for binary array
    int i = 0;
    while (n > 0) {

        // storing remainder in binary array
        binaryNum[i] = n % 2;
        n = n / 2;
        i++;
    }

    // printing binary array in reverse order
    for (int j = i - 1; j >= 0; j--)
        cout << binaryNum[j];
}

refer :- https://www.geeksforgeeks.org/program-decimal-binary-conversion/

or using function :-

#include<bits/stdc++.h>
using namespace std;

int main()
{

    int n;cin>>n;
    cout<<bitset<8>(n).to_string()<<endl;


}

or using left shift

#include<bits/stdc++.h>
using namespace std;
int main()
{
    // here n is the number of bit representation we want 
    int n;cin>>n;

    // num is a number whose binary representation we want
    int num;
    cin>>num;

    for(int i=n-1;i>=0;i--)
    {
        if( num & ( 1 << i ) ) cout<<1;
        else cout<<0;
    }


}

Create directories using make file

Or, KISS.

DIRS=build build/bins

... 

$(shell mkdir -p $(DIRS))

This will create all the directories after the Makefile is parsed.

Java generics - ArrayList initialization

You have strange expectations. If you gave the chain of arguments that led you to them, we might spot the flaw in them. As it is, I can only give a short primer on generics, hoping to touch on the points you might have misunderstood.

ArrayList<? extends Object> is an ArrayList whose type parameter is known to be Object or a subtype thereof. (Yes, extends in type bounds has a meaning other than direct subclass). Since only reference types can be type parameters, this is actually equivalent to ArrayList<?>.

That is, you can put an ArrayList<String> into a variable declared with ArrayList<?>. That's why a1.add(3) is a compile time error. a1's declared type permits a1 to be an ArrayList<String>, to which no Integer can be added.

Clearly, an ArrayList<?> is not very useful, as you can only insert null into it. That might be why the Java Spec forbids it:

It is a compile-time error if any of the type arguments used in a class instance creation expression are wildcard type arguments

ArrayList<ArrayList<?>> in contrast is a functional data type. You can add all kinds of ArrayLists into it, and retrieve them. And since ArrayList<?> only contains but is not a wildcard type, the above rule does not apply.

How is Java platform-independent when it needs a JVM to run?

It means the Java programmer does not (in theory) need to know machine or OS details. These details do exist and the JVM and class libraries handle them. Further, in sharp contrast to C, Java binaries (bytecode) can often be moved to entirely different systems without modifying or recompiling.

How do you pull first 100 characters of a string in PHP

$x = '1234567';

echo substr ($x, 0, 3);  // outputs 123

echo substr ($x, 1, 1);  // outputs 2

echo substr ($x, -2);    // outputs 67

echo substr ($x, 1);     // outputs 234567

echo substr ($x, -2, 1); // outputs 6

google maps v3 marker info window on mouseover

var icon1 = "imageA.png";
var icon2 = "imageB.png";

var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: icon1,
    title: "some marker"
});

google.maps.event.addListener(marker, 'mouseover', function() {
    marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
    marker.setIcon(icon1);
});

Programmatically register a broadcast receiver

Define a broadcast receiver anywhere in Activity/Fragment like this:

mReceiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
     Log.d(TAG," onRecieve"); //do something with intent
   }
 };

Define IntentFilter in onCreate()

mIntentFilter=new IntentFilter("action_name");

Now register the BroadcastReciever in onResume() and Unregister it in onPause() [because there is no use of broadcast if the activity is paused].

@Override
protected void onResume() {
     super.onResume();
     registerReceiver(mReceiver, mIntentFilter);
}

@Override
protected void onPause() {
    if(mReceiver != null) {
            unregisterReceiver(mReceiver);
            mReceiver = null;
    }
    super.onPause();
}

For detail tutorial, have a look at broadcast receiver-two ways to implement.

How to sort the letters in a string alphabetically in Python

Sorted() solution can give you some unexpected results with other strings.

List of other solutions:

Sort letters and make them distinct:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower())))
' belou'

Sort letters and make them distinct while keeping caps:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s)))
' Bbelou'

Sort letters and keep duplicates:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(s))
' BBbbbbeellou'

If you want to get rid of the space in the result, add strip() function in any of those mentioned cases:

>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower()))).strip()
'belou'

How can I set a cookie in react?

It appears that the functionality previously present in the react-cookie npm package has been moved to universal-cookie. The relevant example from the universal-cookie repository now is:

import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('myCat', 'Pacman', { path: '/' });
console.log(cookies.get('myCat')); // Pacman

Replacing few values in a pandas dataframe column with another value

Just wanted to show that there is no performance difference between the 2 main ways of doing it:

df = pd.DataFrame(np.random.randint(0,10,size=(100, 4)), columns=list('ABCD'))

def loc():
    df1.loc[df1["A"] == 2] = 5
%timeit loc
19.9 ns ± 0.0873 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)


def replace():
    df2['A'].replace(
        to_replace=2,
        value=5,
        inplace=True
    )
%timeit replace
19.6 ns ± 0.509 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Android: disabling highlight on listView click

You only need to add: android:cacheColorHint="@android:color/transparent"

Difference between == and === in JavaScript

=== and !== are strict comparison operators:

JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two objects are strictly equal if they refer to the same Object.
  • Null and Undefined types are == (but not ===). [I.e. (Null==Undefined) is true but (Null===Undefined) is false]

Comparison Operators - MDC

What are the differences between a pointer variable and a reference variable in C++?

Taryn? said:

You can't take the address of a reference like you can with pointers.

Actually you can.

I'm quoting from an answer on another question:

The C++ FAQ says it best:

Unlike a pointer, once a reference is bound to an object, it can not be "reseated" to another object. The reference itself isn't an object (it has no identity; taking the address of a reference gives you the address of the referent; remember: the reference is its referent).

Efficient way to do batch INSERTS with JDBC

This is a mix of the two previous answers:

  PreparedStatement ps = c.prepareStatement("INSERT INTO employees VALUES (?, ?)");

  ps.setString(1, "John");
  ps.setString(2,"Doe");
  ps.addBatch();

  ps.clearParameters();
  ps.setString(1, "Dave");
  ps.setString(2,"Smith");
  ps.addBatch();

  ps.clearParameters();
  int[] results = ps.executeBatch();

Free space in a CMD shell

df.exe

Shows all your disks; total, used and free capacity. You can alter the output by various command-line options.

You can get it from http://www.paulsadowski.com/WSH/cmdprogs.htm, http://unxutils.sourceforge.net/ or somewhere else. It's a standard unix-util like du.

df -h will show all your drive's used and available disk space. For example:

M:\>df -h
Filesystem      Size  Used Avail Use% Mounted on
C:/cygwin/bin   932G   78G  855G   9% /usr/bin
C:/cygwin/lib   932G   78G  855G   9% /usr/lib
C:/cygwin       932G   78G  855G   9% /
C:              932G   78G  855G   9% /cygdrive/c
E:              1.9T  1.3T  621G  67% /cygdrive/e
F:              1.9T  201G  1.7T  11% /cygdrive/f
H:              1.5T  524G  938G  36% /cygdrive/h
M:              1.5T  524G  938G  36% /cygdrive/m
P:               98G   67G   31G  69% /cygdrive/p
R:               98G   14G   84G  15% /cygdrive/r

Cygwin is available for free from: https://www.cygwin.com/ It adds many powerful tools to the command prompt. To get just the available space on drive M (as mapped in windows to a shared drive), one could enter in:

M:\>df -h | grep M: | awk '{print $4}'

Using python map and other functional tools

Here's the solution you're looking for:

>>> foos = [1.0, 2.0, 3.0, 4.0, 5.0]
>>> bars = [1, 2, 3]
>>> [(x, bars) for x in foos]
[(1.0, [1, 2, 3]), (2.0, [1, 2, 3]), (3.0, [1, 2, 3]), (4.0, [1, 2, 3]), (5.0, [
1, 2, 3])]

I'd recommend using a list comprehension (the [(x, bars) for x in foos] part) over using map as it avoids the overhead of a function call on every iteration (which can be very significant). If you're just going to use it in a for loop, you'll get better speeds by using a generator comprehension:

>>> y = ((x, bars) for x in foos)
>>> for z in y:
...     print z
...
(1.0, [1, 2, 3])
(2.0, [1, 2, 3])
(3.0, [1, 2, 3])
(4.0, [1, 2, 3])
(5.0, [1, 2, 3])

The difference is that the generator comprehension is lazily loaded.

UPDATE In response to this comment:

Of course you know, that you don't copy bars, all entries are the same bars list. So if you modify any one of them (including original bars), you modify all of them.

I suppose this is a valid point. There are two solutions to this that I can think of. The most efficient is probably something like this:

tbars = tuple(bars)
[(x, tbars) for x in foos]

Since tuples are immutable, this will prevent bars from being modified through the results of this list comprehension (or generator comprehension if you go that route). If you really need to modify each and every one of the results, you can do this:

from copy import copy
[(x, copy(bars)) for x in foos]

However, this can be a bit expensive both in terms of memory usage and in speed, so I'd recommend against it unless you really need to add to each one of them.

How to create permanent PowerShell Aliases

Just to add to this list of possible locations...

This didn't work for me: \Users\{ME}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

However this did: \Users\{ME}\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

If you don't have a profile or you're looking to set one up, run the following command, it will create the folder/files necessary and even tell you where it lives! New-Item -path $profile -type file -force

Use Expect in a Bash script to provide a password to an SSH command

A simple Expect script:

File Remotelogin.exp

    #!/usr/bin/expect
    set user [lindex $argv 1]
    set ip [lindex $argv 0]
    set password [lindex $argv 2]
    spawn ssh $user@$ip
    expect "password"
    send "$password\r"
    interact

Example:

./Remotelogin.exp <ip> <user name> <password>

Javadoc link to method in other class

So the solution to the original problem is that you don't need both the "@see" and the "{@link...}" references on the same line. The "@link" tag is self-sufficient and, as noted, you can put it anywhere in the javadoc block. So you can mix the two approaches:

/**
 * some javadoc stuff
 * {@link com.my.package.Class#method()}
 * more stuff
 * @see com.my.package.AnotherClass
 */

How to kill a thread instantly in C#?

thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.

What is the difference between gravity and layout_gravity in Android?

Gravity: Allow you move the content inside a container. (How sub-views will be placed).

Important: (MOVE along X-axis or Y-axis within available space).

Example: Let's say if you were to work with LinearLayout (Height: match_parent, Width: match_parent) as root level element, then you will have full frame space available; and the child views says 2 TextViews (Height: wrap_content, Width: wrap_content) inside the LinearLayout can be moved around along x/y axis using corresponding values for gravity on parent.

Layout_Gravity: Allow you to override the parent gravity behavior ONLY along x-axis.

Important: (MOVE[override] along X-axis within available space).

Example: If you keep in mind the previous example, we know gravity enabled us to move along x/y axis, i.e; the place TextViews inside LinearLayout. Let's just say LinearLayout specifies gravity: center; meaning every TextView needs to be center both vertically and horizontally. Now if we want one of the TextView to go left/right, we can override the specified gravity behavior using layout_gravity on the TextView.

Bonus: if you dig deeper, you will find out that text within the TextView act as sub-view; so if you apply the gravity on TextView, the text inside the TextView will move around. (the entire concept apply here too)

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

Let's say you're using this HTML5 layout:

<html>
    <body>
        <header>
            <nav><ul>...</ul></nav>
        </header>
        <article>
            <ul>...</ul>
        </article>
        <footer>
            <ul>...</ul>
        </footer>
    </body>
</html>

You could say in your CSS:

header ul, footer ul, nav ul { list-style-type: none; }

If you're using HTML 4, assign IDs to your DIVs (instead of using the new fancy-pants elements) and change this to:

#header ul, #footer ul, #nav ul { list-style-type: none; }

If you're using a CSS reset stylesheet (like Eric Meyer's), you would actually have to give the list style back, since the reset removes the list style from all lists.

#content ul { list-style-type: disc; margin-left: 1.5em; }

Detecting the onload event of a window opened with window.open

First of all, when your first initial window is loaded, it is cached. Therefore, when creating a new window from the first window, the contents of the new window are not loaded from the server, but are loaded from the cache. Consequently, no onload event occurs when you create the new window.

However, in this case, an onpageshow event occurs. It always occurs after the onload event and even when the page is loaded from cache. Plus, it now supported by all major browsers.

 window.popup = window.open($(this).attr('href'), 'Ad', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
 $(window.popup).onpageshow = function() {
     alert("Popup has loaded a page");
 };

The w3school website elaborates more on this:

The onpageshow event is similar to the onload event, except that it occurs after the onload event when the page first loads. Also, the onpageshow event occurs every time the page is loaded, whereas the onload event does not occur when the page is loaded from the cache.

Remove commas from the string using JavaScript

Related answer, but if you want to run clean up a user inputting values into a form, here's what you can do:

const numFormatter = new Intl.NumberFormat('en-US', {
  style: "decimal",
  maximumFractionDigits: 2
})

// Good Inputs
parseFloat(numFormatter.format('1234').replace(/,/g,"")) // 1234
parseFloat(numFormatter.format('123').replace(/,/g,"")) // 123

// 3rd decimal place rounds to nearest
parseFloat(numFormatter.format('1234.233').replace(/,/g,"")); // 1234.23
parseFloat(numFormatter.format('1234.239').replace(/,/g,"")); // 1234.24

// Bad Inputs
parseFloat(numFormatter.format('1234.233a').replace(/,/g,"")); // NaN
parseFloat(numFormatter.format('$1234.23').replace(/,/g,"")); // NaN

// Edge Cases
parseFloat(numFormatter.format(true).replace(/,/g,"")) // 1
parseFloat(numFormatter.format(false).replace(/,/g,"")) // 0
parseFloat(numFormatter.format(NaN).replace(/,/g,"")) // NaN

Use the international date local via format. This cleans up any bad inputs, if there is one it returns a string of NaN you can check for. There's no way currently of removing commas as part of the locale (as of 10/12/19), so you can use a regex command to remove commas using replace.

ParseFloat converts the this type definition from string to number

If you use React, this is what your calculate function could look like:

updateCalculationInput = (e) => {
    let value;
    value = numFormatter.format(e.target.value); // 123,456.78 - 3rd decimal rounds to nearest number as expected
    if(value === 'NaN') return; // locale returns string of NaN if fail
    value = value.replace(/,/g, ""); // remove commas
    value = parseFloat(value); // now parse to float should always be clean input

    // Do the actual math and setState calls here
}

Rails - How to use a Helper Inside a Controller

Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer is the way to go.

Option 1: Probably the simplest way is to include your helper module in your controller:

class MyController < ApplicationController
  include MyHelper

  def xxxx
    @comments = []
    Comment.find_each do |comment|
      @comments << {:id => comment.id, :html => html_format(comment.content)}
    end
  end
end

Option 2: Or you can declare the helper method as a class function, and use it like so:

MyHelper.html_format(comment.content)

If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:

module MyHelper
  def self.html_format(str)
    process(str)
  end

  def html_format(str)
    MyHelper.html_format(str)
  end
end

Hope this helps!

Add and remove multiple classes in jQuery

You can separate multiple classes with the space:

$("p").addClass("myClass yourClass");

http://api.jquery.com/addClass/

Good ways to sort a queryset? - Django

I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by method accepts multiple arguments, you could easily chain them:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):

>>> auths = Author.objects.order_by('-score')[:5]
>>> for x in auths: print x
... 
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name:

>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
... 
Benjamin Harrison (467)
James Monroe (487)
Gerald Rudolph (464)
Ulysses Simpson (474)
Harry Truman (471)

And now the combined order_by call:

>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
>>> for x in myauths: print x
... 
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

As you can see it is the same result as the first one, meaning it doesn't work as you would expect.

How to create a table from select query result in SQL Server 2008

Try using SELECT INTO....

SELECT ....
INTO     TABLE_NAME(table you want to create)
FROM source_table

NodeJS - Error installing with NPM

gyp ERR! configure error gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT HON env variable.

This means the Python env. variable should point to the executable python file, in my case: SET PYTHON=C:\work\_env\Python27\python.exe

How can I convert my Java program to an .exe file?

I would say launch4j is the best tool for converting a java source code(.java) to .exe file You can even bundle a jre with it for distribution and the exe can even be iconified. Although the size of application increases, it makes sure that the application will work perfectly even if the user does not have a jre installed. It also makes sure that you are able to provide the specific jre required for your app without the user having to install it separately. But unfortunately, java loses its importance. Its multi platform support is totally ignored and the final app is only supported for windows. But that is not a big deal, if you are catering only to windows users.

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

If you look at the code for the $.click function, I'll bet there is a conditional statement that checks to see if the element has listeners registered for theclick event before it proceeds. Why not just get the href attribute from the link and manually change the page location?

 window.location.href = $('a').attr('href');

Here is why it doesn't click through. From the trigger function, jQuery source for version 1.3.2:

 // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
 if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
     event.result = false;

 // Trigger the native events (except for clicks on links)
 if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
     this.triggered = true;
     try {
         elem[ type ]();
         // Prevent Internet Explorer from throwing an error for some hidden elements
     }
     catch (e)
     {
     }
 }

After it calls handlers (if there are any), jQuery triggers an event on the object. However it only calls native handlers for click events if the element is not a link. I guess this was done purposefully for some reason. This should be true though whether an event handler is defined or not, so I'm not sure why in your case attaching an event handler caused the native onClick handler to be called. You'll have to do what I did and step through the execution to see where it is being called.

Collections sort(List<T>,Comparator<? super T>) method example

To use Collections sort(List,Comparator) , you need to create a class that implements Comparator Interface, and code for the compare() in it, through Comparator Interface

You can do something like this:

class StudentComparator implements Comparator
{
    public int compare (Student s1 Student s2)
    {
        // code to compare 2 students
    }
}

To sort do this:

 Collections.sort(List,new StudentComparator())

How to clear a chart from a canvas so that hover events cannot be triggered?

For me this worked:

_x000D_
_x000D_
  var in_canvas = document.getElementById('chart_holder');_x000D_
 //remove canvas if present_x000D_
   while (in_canvas.hasChildNodes()) {_x000D_
      in_canvas.removeChild(in_canvas.lastChild);_x000D_
    } _x000D_
 //insert canvas_x000D_
   var newDiv = document.createElement('canvas');_x000D_
   in_canvas.appendChild(newDiv);_x000D_
   newDiv.id = "myChart";
_x000D_
_x000D_
_x000D_

What is the fastest way to send 100,000 HTTP requests in Python?

Using a thread pool is a good option, and will make this fairly easy. Unfortunately, python doesn't have a standard library that makes thread pools ultra easy. But here is a decent library that should get you started: http://www.chrisarndt.de/projects/threadpool/

Code example from their site:

pool = ThreadPool(poolsize)
requests = makeRequests(some_callable, list_of_args, callback)
[pool.putRequest(req) for req in requests]
pool.wait()

Hope this helps.

Jackson JSON custom serialization for certain fields

jackson-annotations provides @JsonFormat which can handle a lot of customizations without the need to write the custom serializer.

For example, requesting a STRING shape for a field with numeric type will output the numeric value as string

public class Person {
    public String name;
    public int age;
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    public int favoriteNumber;
}

will result in the desired output

{"name":"Joe","age":25,"favoriteNumber":"123"}

How to access URL segment(s) in blade in Laravel 5?

Try this

{{ Request::segment(1) }}

Get image data url in JavaScript?

shiv / shim / sham

If your image(s) are already loaded (or not), this "tool" may come in handy:

Object.defineProperty
(
    HTMLImageElement.prototype,'toDataURL',
    {enumerable:false,configurable:false,writable:false,value:function(m,q)
    {
        let c=document.createElement('canvas');
        c.width=this.naturalWidth; c.height=this.naturalHeight;
        c.getContext('2d').drawImage(this,0,0); return c.toDataURL(m,q);
    }}
);

.. but why?

This has the advantage of using the "already loaded" image data, so no extra request in needed. Aditionally it lets the end-user (programmer like you) decide the CORS and/or mime-type and quality -OR- you can leave out these arguments/parameters as described in the MDN specification here.

If you have this JS loaded (prior to when it's needed), then converting to dataURL is as simple as:

examples

HTML
<img src="/yo.jpg" onload="console.log(this.toDataURL('image/jpeg'))">
JS
console.log(document.getElementById("someImgID").toDataURL());

GPU fingerprinting

If you are concerned about the "preciseness" of the bits then you can alter this tool to suit your needs as provided by @Kaiido's answer.

Android: How can I get the current foreground activity (from a service)?

I could not find a solution that our team would be happy with so we rolled our own. We use ActivityLifecycleCallbacks to keep track of current activity and then expose it through a service:

public interface ContextProvider {
    Context getActivityContext();
}

public class MyApplication extends Application implements ContextProvider {
    private Activity currentActivity;

    @Override
    public Context getActivityContext() {
         return currentActivity;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                MyApplication.this.currentActivity = activity;
            }

            @Override
            public void onActivityStarted(Activity activity) {
                MyApplication.this.currentActivity = activity;
            }

            @Override
            public void onActivityResumed(Activity activity) {
                MyApplication.this.currentActivity = activity;
            }

            @Override
            public void onActivityPaused(Activity activity) {
                MyApplication.this.currentActivity = null;
            }

            @Override
            public void onActivityStopped(Activity activity) {
                // don't clear current activity because activity may get stopped after
                // the new activity is resumed
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                // don't clear current activity because activity may get destroyed after
                // the new activity is resumed
            }
        });
    }
}

Then configure your DI container to return instance of MyApplication for ContextProvider, e.g.

public class ApplicationModule extends AbstractModule {    
    @Provides
    ContextProvider provideMainActivity() {
        return MyApplication.getCurrent();
    }
}

(Note that implementation of getCurrent() is omitted from the code above. It's just a static variable that's set from the application constructor)

Send array with Ajax to PHP script

If you have been trying to send a one dimentional array and jquery was converting it to comma separated values >:( then follow the code below and an actual array will be submitted to php and not all the comma separated bull**it.

Say you have to attach a single dimentional array named myvals.

jQuery('#someform').on('submit', function (e) {
    e.preventDefault();
    var data = $(this).serializeArray();

    var myvals = [21, 52, 13, 24, 75]; // This array could come from anywhere you choose 
    for (i = 0; i < myvals.length; i++) {
        data.push({
            name: "myvals[]", // These blank empty brackets are imp!
            value: myvals[i]
        });
    }

jQuery.ajax({
    type: "post",
    url: jQuery(this).attr('action'),
    dataType: "json",
    data: data, // You have to just pass our data variable plain and simple no Rube Goldberg sh*t.
    success: function (r) {
...

Now inside php when you do this

print_r($_POST);

You will get ..

Array
(
    [someinputinsidetheform] => 023
    [anotherforminput] => 111
    [myvals] => Array
        (
            [0] => 21
            [1] => 52
            [2] => 13
            [3] => 24
            [4] => 75
        )
)

Pardon my language, but there are hell lot of Rube-Goldberg solutions scattered all over the web and specially on SO, but none of them are elegant or solve the problem of actually posting a one dimensional array to php via ajax post. Don't forget to spread this solution.

Using CookieContainer with WebClient class

The HttpWebRequest modifies the CookieContainer assigned to it. There is no need to process returned cookies. Simply assign your cookie container to every web request.

public class CookieAwareWebClient : WebClient
{
    public CookieContainer CookieContainer { get; set; } = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri uri)
    {
        WebRequest request = base.GetWebRequest(uri);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = CookieContainer;
        }
        return request;
    }
}

Run PowerShell command from command prompt (no ps1 script)

This works from my Windows 10's cmd.exe prompt

powershell -ExecutionPolicy Bypass -Command "Import-Module C:\Users\william\ps1\TravelBook; Get-TravelBook Hawaii"

This example shows

  1. how to chain multiple commands
  2. how to import module with module path
  3. how to run a function defined in the module
  4. No need for those fancy "&".

Get element inside element by class and ID - JavaScript

THe easiest way to do so is:

function findChild(idOfElement, idOfChild){
  let element = document.getElementById(idOfElement);
  return element.querySelector('[id=' + idOfChild + ']');
}

or better readable:

findChild = (idOfElement, idOfChild) => {
    let element = document.getElementById(idOfElement);
    return element.querySelector(`[id=${idOfChild}]`);
}

C compiling - "undefined reference to"?

Make sure your declare the tolayer5 function as a prototype, or define the full function definition, earlier in the file where you use it.

SameSite warning Chrome 77

If you are testing on localhost and you have no control of the response headers, you can disable it with a chrome flag.

Visit the url and disable it: chrome://flags/#same-site-by-default-cookies SameSite by default cookies screenshot

I need to disable it because Chrome Canary just started enforcing this rule as of approximately V 82.0.4078.2 and now it's not setting these cookies.

Note: I only turn this flag on in Chrome Canary that I use for development. It's best not to turn the flag on for everyday Chrome browsing for the same reasons that google is introducing it.

T-SQL Format integer to 2-digit string

Another example:

select 
case when teamId < 10 then '0' + cast(teamId as char(1)) 
else cast(teamId as char(2)) end      
as 'pretty id',
* from team

What is the easiest way to push an element to the beginning of the array?

You can use insert:

a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]

Where the first argument is the index to insert at and the second is the value.

How to count frequency of characters in a string?

Since there was no Java 8 solution, thought of posting one. Also, this solution is much neater, readable and concise than some of the other solutions mentioned here.

String string = "aasjjikkk";

Map<Character, Long> characterFrequency = string.chars()  // creates an IntStream
    .mapToObj(c -> (char) c) // converts the IntStream to Stream<Character>
    .collect(Collectors.groupingBy(c -> c, Collectors.counting())); // creates a
                                                                    // Map<Character, Long> 
                                                                    // where the Long is
                                                                    // the frequency

how to get domain name from URL

So if you just have a string and not a window.location you could use...

String.prototype.toUrl = function(){

if(!this && 0 < this.length)
{
    return undefined;
}
var original = this.toString();
var s = original;
if(!original.toLowerCase().startsWith('http'))
{
    s = 'http://' + original;
}

s = this.split('/');

var protocol = s[0];
var host = s[2];
var relativePath = '';

if(s.length > 3){
    for(var i=3;i< s.length;i++)
    {
        relativePath += '/' + s[i];
    }
}

s = host.split('.');
var domain = s[s.length-2] + '.' + s[s.length-1];    

return {
    original: original,
    protocol: protocol,
    domain: domain,
    host: host,
    relativePath: relativePath,
    getParameter: function(param)
    {
        return this.getParameters()[param];
    },
    getParameters: function(){
        var vars = [], hash;
        var hashes = this.original.slice(this.original.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
};};

How to use.

var str = "http://en.wikipedia.org/wiki/Knopf?q=1&t=2";
var url = str.toUrl;

var host = url.host;
var domain = url.domain;
var original = url.original;
var relativePath = url.relativePath;
var paramQ = url.getParameter('q');
var paramT = url.getParamter('t');

Removing legend on charts with chart.js v2

The options object can be added to the chart when the new Chart object is created.

var chart1 = new Chart(canvas, {
    type: "pie",
    data: data,
    options: {
         legend: {
            display: false
         },
         tooltips: {
            enabled: false
         }
    }
});

JQuery addclass to selected div, remove class if another div is selected

I had to transform the divs to list items otherwise all my divs would get that class and only the generated ones should get it Thanks everyone, I love this site and the helpful people on it !!!! You can follow the newbie school project at http://low-budgetwebservice.be/project/webbuilder.html suggestions are always welcome :). So this worked for me:

            /* Add Class Heading*/
            $(document).ready(function() {
            $( document ).on( 'click', 'ul#items li', function () { 
            $('ul#items li').removeClass('active'); 
            $(this).addClass('active');
            });
            });

Simple URL GET/POST function in Python

requests

https://github.com/kennethreitz/requests/

Here's a few common ways to use it:

import requests
url = 'https://...'
payload = {'key1': 'value1', 'key2': 'value2'}

# GET
r = requests.get(url)

# GET with params in URL
r = requests.get(url, params=payload)

# POST with form-encoded data
r = requests.post(url, data=payload)

# POST with JSON 
import json
r = requests.post(url, data=json.dumps(payload))

# Response, status etc
r.text
r.status_code

httplib2

https://github.com/jcgregorio/httplib2

>>> from httplib2 import Http
>>> from urllib import urlencode
>>> h = Http()
>>> data = dict(name="Joe", comment="A test comment")
>>> resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))
>>> resp
{'status': '200', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding,User-Agent',
 'server': 'Apache', 'connection': 'close', 'date': 'Tue, 31 Jul 2007 15:29:52 GMT', 
 'content-type': 'text/html'}

JavaScript CSS how to add and remove multiple CSS classes to an element

Try doing this...

document.getElementById("MyElement").className += " MyClass";

Got this here...

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

Charts for Android

SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.

SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.

Some useful links can be found below:

enter image description here

Disclosure: I am the tech lead on the SciChart project!

Call Class Method From Another Class

update: Just saw the reference to call_user_func_array in your post. that's different. use getattr to get the function object and then call it with your arguments

class A(object):
    def method1(self, a, b, c):
        # foo

method = A.method1

method is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1 with one of the two decorators discussed below, pass it an instance of A as the first argument or access the method on an instance of A.

a = A()
method = a.method1
method(1, 2)

You have three options for doing this

  1. Use an instance of A to call method1 (using two possible forms)
  2. apply the classmethod decorator to method1: you will no longer be able to reference self in method1 but you will get passed a cls instance in it's place which is A in this case.
  3. apply the staticmethod decorator to method1: you will no longer be able to reference self, or cls in staticmethod1 but you can hardcode references to A into it, though obviously, these references will be inherited by all subclasses of A unless they specifically override method1 and do not call super.

Some examples:

class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
    def method1(self, a, b):
        return a + b

    @staticmethod
    def method2(a, b):
        return a + b

    @classmethod
    def method3(cls, a, b):
        return cls.method2(a, b)

t = Test1()  # same as doing it in another class

Test1.method1(t, 1, 2) #form one of calling a method on an instance
t.method1(1, 2)        # form two (the common one) essentially reduces to form one

Test1.method2(1, 2)  #the static method can be called with just arguments
t.method2(1, 2)      # on an instance or the class

Test1.method3(1, 2)  # ditto for the class method. It will have access to the class
t.method3(1, 2)      # that it's called on (the subclass if called on a subclass) 
                     # but will not have access to the instance it's called on 
                     # (if it is called on an instance)

Note that in the same way that the name of the self variable is entirely up to you, so is the name of the cls variable but those are the customary values.

Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.

Call async/await functions in parallel

I vote for:

await Promise.all([someCall(), anotherCall()]);

Be aware of the moment you call functions, it may cause unexpected result:

// Supposing anotherCall() will trigger a request to create a new User

if (callFirst) {
  await someCall();
} else {
  await Promise.all([someCall(), anotherCall()]); // --> create new User here
}

But following always triggers request to create new User

// Supposing anotherCall() will trigger a request to create a new User

const someResult = someCall();
const anotherResult = anotherCall(); // ->> This always creates new User

if (callFirst) {
  await someCall();
} else {
  const finalResult = [await someResult, await anotherResult]
}

File name without extension name VBA

Answer is here: I think this answer is good, please try it http://mariaevert.dk/vba/?p=162

How to change values in a tuple?

i did this:

list = [1,2,3,4,5]
tuple = (list)

and to change, just do

list[0]=6

and u can change a tuple :D

here is it copied exactly from IDLE

>>> list=[1,2,3,4,5,6,7,8,9]

>>> tuple=(list)

>>> print(tuple)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list[0]=6

>>> print(tuple)

[6, 2, 3, 4, 5, 6, 7, 8, 9]

Self-reference for cell, column and row in worksheet functions

In a VBA worksheet function UDF you use Application.Caller to get the range of cell(s) that contain the formula that called the UDF.

What is SELF JOIN and when would you use it?

Well, one classic example is where you wanted to get a list of employees and their immediate managers:

select e.employee as employee, b.employee as boss
from emptable e, emptable b
where e.manager_id = b.empolyee_id
order by 1

It's basically used where there is any relationship between rows stored in the same table.

  • employees.
  • multi-level marketing.
  • machine parts.

And so on...

Run all SQL files in a directory

You can create a single script that calls all the others.

Put the following into a batch file:

@echo off
echo.>"%~dp0all.sql"
for %%i in ("%~dp0"*.sql) do echo @"%%~fi" >> "%~dp0all.sql"

When you run that batch file it will create a new script named all.sql in the same directory where the batch file is located. It will look for all files with the extension .sql in the same directory where the batch file is located.

You can then run all scripts by using sqlplus user/pwd @all.sql (or extend the batch file to call sqlplus after creating the all.sql script)

How to set web.config file to show full error message

If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

How to change the text on the action bar

Kotlin

You can do it programmatically in Kotlin this way. You just ignore it if "supportActionBar" is null:

    supportActionBar?.setTitle(R.string.my_text)
    supportActionBar?.title = "My text"

Or this way. It throws an exception if "supportActionBar" is null.

    supportActionBar!!.setTitle(R.string.my_text)
    supportActionBar!!.title = "My text"

How can I view the source code for a function?

It gets revealed when you debug using the debug() function. Suppose you want to see the underlying code in t() transpose function. Just typing 't', doesn't reveal much.

>t 
function (x) 
UseMethod("t")
<bytecode: 0x000000003085c010>
<environment: namespace:base>

But, Using the 'debug(functionName)', it reveals the underlying code, sans the internals.

> debug(t)
> t(co2)
debugging in: t(co2)
debug: UseMethod("t")
Browse[2]> 
debugging in: t.ts(co2)
debug: {
    cl <- oldClass(x)
    other <- !(cl %in% c("ts", "mts"))
    class(x) <- if (any(other)) 
        cl[other]
    attr(x, "tsp") <- NULL
    t(x)
}
Browse[3]> 
debug: cl <- oldClass(x)
Browse[3]> 
debug: other <- !(cl %in% c("ts", "mts"))
Browse[3]> 
debug: class(x) <- if (any(other)) cl[other]
Browse[3]>  
debug: attr(x, "tsp") <- NULL
Browse[3]> 
debug: t(x)

EDIT: debugonce() accomplishes the same without having to use undebug()

Gradle finds wrong JAVA_HOME even though it's correctly set

Try installing latest version of gradle,

sudo add-apt-repository ppa:cwchien/gradle

sudo apt-get update

sudo apt-get install gradle

If we install from ubuntu repo, it will install the old version , (for me it was gradle 1.4). In older version, it sets java home from gradle as export JAVA_HOME=/usr/lib/jvm/default-java. Latest version don't have this issue.

Replace String in all files in Eclipse

ctrl + H  will show the option to replace in the bottom . 

enter image description here

Once you click on replace it will show as below

enter image description here

How to execute python file in linux

yes there is. add

#!/usr/bin/env python

to the beginning of the file and do

chmod u+rx <file>

assuming your user owns the file, otherwise maybe adjust the group or world permissions.

.py files under windows are associated with python as the program to run when opening them just like MS word is run when opening a .docx for example.

How do I get an OAuth 2.0 authentication token in C#

This example get token thouth HttpWebRequest

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pathapi);
        request.Method = "POST";
        string postData = "grant_type=password";
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] byte1 = encoding.GetBytes(postData);

        request.ContentType = "application/x-www-form-urlencoded";

        request.ContentLength = byte1.Length;
        Stream newStream = request.GetRequestStream();
        newStream.Write(byte1, 0, byte1.Length);

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;            
        using (Stream responseStream = response.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            getreaderjson = reader.ReadToEnd();
        }

Is there a Python equivalent of the C# null-coalescing operator?

Regarding answers by @Hugh Bothwell, @mortehu and @glglgl.

Setup Dataset for testing

import random

dataset = [random.randint(0,15) if random.random() > .6 else None for i in range(1000)]

Define implementations

def not_none(x, y=None):
    if x is None:
        return y
    return x

def coalesce1(*arg):
  return reduce(lambda x, y: x if x is not None else y, arg)

def coalesce2(*args):
    return next((i for i in args if i is not None), None)

Make test function

def test_func(dataset, func):
    default = 1
    for i in dataset:
        func(i, default)

Results on mac i7 @2.7Ghz using python 2.7

>>> %timeit test_func(dataset, not_none)
1000 loops, best of 3: 224 µs per loop

>>> %timeit test_func(dataset, coalesce1)
1000 loops, best of 3: 471 µs per loop

>>> %timeit test_func(dataset, coalesce2)
1000 loops, best of 3: 782 µs per loop

Clearly the not_none function answers the OP's question correctly and handles the "falsy" problem. It is also the fastest and easiest to read. If applying the logic in many places, it is clearly the best way to go.

If you have a problem where you want to find the 1st non-null value in a iterable, then @mortehu's response is the way to go. But it is a solution to a different problem than OP, although it can partially handle that case. It cannot take an iterable AND a default value. The last argument would be the default value returned, but then you wouldn't be passing in an iterable in that case as well as it isn't explicit that the last argument is a default to value.

You could then do below, but I'd still use not_null for the single value use case.

def coalesce(*args, **kwargs):
    default = kwargs.get('default')
    return next((a for a in arg if a is not None), default)

Make child div stretch across width of page

Just set the width to 100vw like this:

<div id="container" style="width: 100vw">
 <div id="help_panel" style="width: 100%; margin: 0 auto;">
  Content goes here.
 </div> 
</div>

Deleting objects from an ArrayList in Java

Most performant would, I guess, be using the listIterator method and do a reverse iteration:

for (ListIterator<E> iter = list.listIterator(list.size()); iter.hasPrevious();){
    if (weWantToDelete(iter.previous()))  iter.remove();
}

Edit: Much later, one might also want to add the Java 8 way of removing elements from a list (or any collection!) using a lambda or method reference. An in-place filter for collections, if you like:

list.removeIf(e -> e.isBad() && e.shouldGoAway());

This is probably the best way to clean up a collection. Since it uses internal iteration, the collection implementation could take shortcuts to make it as fast as possible (for ArrayLists, it could minimize the amount of copying needed).

Angular 6: How to set response type as text while making http call

Have you tried not setting the responseType and just type casting the response?

This is what worked for me:

/**
 * Client for consuming recordings HTTP API endpoint.
 */
@Injectable({
  providedIn: 'root'
})
export class DownloadUrlClientService {
  private _log = Log.create('DownloadUrlClientService');


  constructor(
    private _http: HttpClient,
  ) {}

  private async _getUrl(url: string): Promise<string> {
    const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
    // const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
    const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
    // const res = await (this._http.get(url, httpOptions)).toPromise();
    return res;
  }
}

Format JavaScript date as yyyy-mm-dd

_x000D_
_x000D_
const today = new Date(); // or whatever _x000D_
_x000D_
const yearFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[0]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}`;_x000D_
}_x000D_
_x000D_
const monthFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[0]}`;_x000D_
}_x000D_
_x000D_
const dayFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[0]}`;_x000D_
}_x000D_
_x000D_
console.log(yearFirstFormater(today));_x000D_
console.log(monthFirstFormater(today));_x000D_
console.log(dayFirstFormater(today));
_x000D_
_x000D_
_x000D_

Facebook page automatic "like" URL (for QR Code)

I'm not an attorney, but clicking the like button without the express permission of a facebook user might be a violation of facebook policy. You should have your corporate attorney check out the facebook policy.

You should encode the url to a page with a like button, so when scanned by the phone, it opens up a browser window to the like page, where now the user has the option to like it or not.

How to compare different branches in Visual Studio Code

UPDATE

Now it's available:

https://marketplace.visualstudio.com/items?itemName=donjayamanne.githistory

Until now it isn't supported, but you can follow the thread for it: GitHub

Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

Most of the other answers point to eager loading, but I found another solution.

In my case I had an EF object InventoryItem with a collection of InvActivity child objects.

class InventoryItem {
...
   // EF code first declaration of a cross table relationship
   public virtual List<InvActivity> ItemsActivity { get; set; }

   public GetLatestActivity()
   {
       return ItemActivity?.OrderByDescending(x => x.DateEntered).SingleOrDefault();
   }
...
}

And since I was pulling from the child object collection instead of a context query (with IQueryable), the Include() function was not available to implement eager loading. So instead my solution was to create a context from where I utilized GetLatestActivity() and attach() the returned object:

using (DBContext ctx = new DBContext())
{
    var latestAct = _item.GetLatestActivity();

    // attach the Entity object back to a usable database context
    ctx.InventoryActivity.Attach(latestAct);

    // your code that would make use of the latestAct's lazy loading
    // ie   latestAct.lazyLoadedChild.name = "foo";
}

Thus you aren't stuck with eager loading.

How should I escape strings in JSON?

Try this org.codehaus.jettison.json.JSONObject.quote("your string").

Download it here: http://mvnrepository.com/artifact/org.codehaus.jettison/jettison

Fatal error: [] operator not supported for strings

Solved!

$a['index'] = [];
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

I sorted this problem as verifying the json from JSONLint.com and then, correcting it. And this is code for the same.

String jsonStr = "[{\r\n" + "\"name\":\"New York\",\r\n" + "\"number\": \"732921\",\r\n"+ "\"center\": {\r\n" + "\"latitude\": 38.895111,\r\n"  + " \"longitude\": -77.036667\r\n" + "}\r\n" + "},\r\n" + " {\r\n"+ "\"name\": \"San Francisco\",\r\n" +\"number\":\"298732\",\r\n"+ "\"center\": {\r\n" + "    \"latitude\": 37.783333,\r\n"+ "\"longitude\": -122.416667\r\n" + "}\r\n" + "}\r\n" + "]";

ObjectMapper mapper = new ObjectMapper();
MyPojo[] jsonObj = mapper.readValue(jsonStr, MyPojo[].class);

for (MyPojo itr : jsonObj) {
    System.out.println("Val of name is: " + itr.getName());
    System.out.println("Val of number is: " + itr.getNumber());
    System.out.println("Val of latitude is: " + 
        itr.getCenter().getLatitude());
    System.out.println("Val of longitude is: " + 
        itr.getCenter().getLongitude() + "\n");
}

Note: MyPojo[].class is the class having getter and setter of json properties.

Result:

Val of name is: New York
Val of number is: 732921
Val of latitude is: 38.895111
Val of longitude is: -77.036667
Val of name is: San Francisco
Val of number is: 298732
Val of latitude is: 37.783333
Val of longitude is: -122.416667

Getting the source HTML of the current page from chrome extension

Here is my solution:

chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            this.pageSource = request.source;
            var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
            alert(title)
        }
    });

    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
        chrome.tabs.executeScript(
            tabs[0].id,
            { code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
        );
    });

convert array into DataFrame in Python

In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

Use CSS to remove the space between images

I found that the only option that worked for me was

font-size:0;

I was also using overflow and white-space: nowrap; float: left; seems to mess things up

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

You can easily use Node.JS in your web app only for real-time communication. Node.JS is really powerful when it's about WebSockets. Therefore "PHP Notifications via Node.js" would be a great concept.

See this example: Creating a Real-Time Chat App with PHP and Node.js

use jQuery's find() on JSON object

For one dimension json you can use this:

function exist (json, modulid) {
    var ret = 0;
    $(json).each(function(index, data){
        if(data.modulId == modulid)
            ret++;
    })
    return ret > 0;
}

How do I parse a URL into hostname and path in javascript?

Why do not use it?

        $scope.get_location=function(url_str){
        var parser = document.createElement('a');
        parser.href =url_str;//"http://example.com:3000/pathname/?search=test#hash";
        var info={
            protocol:parser.protocol,   
            hostname:parser.hostname, // => "example.com"
            port:parser.port,     // => "3000"
            pathname:parser.pathname, // => "/pathname/"
            search:parser.search,   // => "?search=test"
            hash:parser.hash,     // => "#hash"
            host:parser.host, // => "example.com:3000"      
        }
        return info;
    }
    alert( JSON.stringify( $scope.get_location("http://localhost:257/index.php/deploy/?asd=asd#asd"),null,4 ) );

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

I used to curse this error, but it can be helpful to remind you to escape user input.

For instance, if you thought this was clever, shorthand code:

// Echo whatever the hell this is
<?=$_POST['something']?>

...Think again! A better solution is:

// If this is set, echo a filtered version
<?=isset($_POST['something']) ? html($_POST['something']) : ''?>

(I use a custom html() function to escape characters, your mileage may vary)

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

you can try something like this, or just copy and past below piece.

boolean exception = true;
Charset charset = Charset.defaultCharset(); //Try the default one first.        
int index = 0;

while(exception) {
    try {
        lines = Files.readAllLines(f.toPath(),charset);
          for (String line: lines) {
              line= line.trim();
              if(line.contains(keyword))
                  values.add(line);
              }           
        //No exception, just returns
        exception = false; 
    } catch (IOException e) {
        exception = true;
        //Try the next charset
        if(index<Charset.availableCharsets().values().size())
            charset = (Charset) Charset.availableCharsets().values().toArray()[index];
        index ++;
    }
}

Multi-key dictionary in c#?

I think you would need a Tuple2 like class. Be sure that it's GetHashCode() and Equals() is based upon the two contained elements.

See Tuples in C#

T-SQL get SELECTed value of stored procedure

there are three ways you can use: the RETURN value, and OUTPUT parameter and a result set

ALSO, watch out if you use the pattern: SELECT @Variable=column FROM table ...

if there are multiple rows returned from the query, your @Variable will only contain the value from the last row returned by the query.

RETURN VALUE
since your query returns an int field, at least based on how you named it. you can use this trick:

CREATE PROCEDURE GetMyInt
( @Param int)
AS
DECLARE @ReturnValue int

SELECT @ReturnValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN @ReturnValue
GO

and now call your procedure like:

DECLARE @SelectedValue int
       ,@Param         int
SET @Param=1
EXEC @SelectedValue = GetMyInt @Param
PRINT @SelectedValue

this will only work for INTs, because RETURN can only return a single int value and nulls are converted to a zero.

OUTPUT PARAMETER
you can use an output parameter:

CREATE PROCEDURE GetMyInt
( @Param     int
 ,@OutValue  int OUTPUT)
AS
SELECT @OutValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO

and now call your procedure like:

DECLARE @SelectedValue int
       ,@Param         int
SET @Param=1
EXEC GetMyInt @Param, @SelectedValue OUTPUT
PRINT @SelectedValue 

Output parameters can only return one value, but can be any data type

RESULT SET for a result set make the procedure like:

CREATE PROCEDURE GetMyInt
( @Param     int)
AS
SELECT MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO

use it like:

DECLARE @ResultSet table (SelectedValue int)
DECLARE @Param int
SET @Param=1
INSERT INTO @ResultSet (SelectedValue)
    EXEC GetMyInt @Param
SELECT * FROM @ResultSet 

result sets can have many rows and many columns of any data type

Android Endless List

Here is a solution that also makes it easy to show a loading view in the end of the ListView while it's loading.

You can see the classes here:

https://github.com/CyberEagle/OpenProjects/blob/master/android-projects/widgets/src/main/java/br/com/cybereagle/androidwidgets/helper/ListViewWithLoadingIndicatorHelper.java - Helper to make it possible to use the features without extending from SimpleListViewWithLoadingIndicator.

https://github.com/CyberEagle/OpenProjects/blob/master/android-projects/widgets/src/main/java/br/com/cybereagle/androidwidgets/listener/EndlessScrollListener.java - Listener that starts loading data when the user is about to reach the bottom of the ListView.

https://github.com/CyberEagle/OpenProjects/blob/master/android-projects/widgets/src/main/java/br/com/cybereagle/androidwidgets/view/SimpleListViewWithLoadingIndicator.java - The EndlessListView. You can use this class directly or extend from it.

In JavaScript can I make a "click" event fire programmatically for a file input element?

You cannot do that in all browsers, supposedly IE does allow it, but Mozilla and Opera do not.

When you compose a message in GMail, the 'attach files' feature is implemented one way for IE and any browser that supports this, and then implemented another way for Firefox and those browsers that do not.

I don't know why you cannot do it, but one thing that is a security risk, and which you are not allowed to do in any browser, is programmatically set the file name on the HTML File element.

How to find elements by class

The following should work

soup.find('span', attrs={'class':'totalcount'})

replace 'totalcount' with your class name and 'span' with tag you are looking for. Also, if your class contains multiple names with space, just choose one and use.

P.S. This finds the first element with given criteria. If you want to find all elements then replace 'find' with 'find_all'.