Programs & Examples On #Request timed out

How to center a label text in WPF?

The Control class has HorizontalContentAlignment and VerticalContentAlignment properties. These properties determine how a control’s content fills the space within the control.
Set HorizontalContentAlignment and VerticalContentAlignment to Center.

How and when to use ‘async’ and ‘await’

The answers here are useful as a general guidance about await/async. They also contain some detail about how await/async is wired. I would like to share some practical experience with you that you should know before using this design pattern.

The term "await" is literal, so whatever thread you call it on will wait for the result of the method before continuing. On the foreground thread, this is a disaster. The foreground thread carries the burden of constructing your app, including views, view models, initial animations, and whatever else you have boot-strapped with those elements. So when you await the foreground thread, you stop the app. The user waits and waits when nothing appears to happen. This provides a negative user experience.

You can certainly await a background thread using a variety of means:

Device.BeginInvokeOnMainThread(async () => { await AnyAwaitableMethod(); });

// Notice that we do not await the following call, 
// as that would tie it to the foreground thread.
try
{
Task.Run(async () => { await AnyAwaitableMethod(); });
}
catch
{}

The complete code for these remarks is at https://github.com/marcusts/xamarin-forms-annoyances. See the solution called AwaitAsyncAntipattern.sln.

The GitHub site also provides links to a more detailed discussion on this topic.

How can I clear the content of a file?

Try using something like

File.Create

Creates or overwrites a file in the specified path.

Hash table in JavaScript

The Javascript interpreter natively stores objects in a hash table. If you're worried about contamination from the prototype chain, you can always do something like this:

// Simple ECMA5 hash table
Hash = function(oSource){
  for(sKey in oSource) if(Object.prototype.hasOwnProperty.call(oSource, sKey)) this[sKey] = oSource[sKey];
};
Hash.prototype = Object.create(null);

var oHash = new Hash({foo: 'bar'});
oHash.foo === 'bar'; // true
oHash['foo'] === 'bar'; // true
oHash['meow'] = 'another prop'; // true
oHash.hasOwnProperty === undefined; // true
Object.keys(oHash); // ['foo', 'meow']
oHash instanceof Hash; // true

problem with <select> and :after with CSS in WebKit

To my experience it simply does not work, unless you are willing to wrap your <select> in some wrapper. But what you can do instead is to use background image SVG. E.g.

    .archive .options select.opt {
    -moz-appearance: none;
    -webkit-appearance: none;
    padding-right: 1.25EM;
    appearance: none;
    position: relative;
    background-color: transparent;
    background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1.1' height='10px' width='15px'%3E%3Ctext x='0' y='10' fill='gray'%3E%E2%96%BE%3C/text%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-size: 1.5EM 1EM;
    background-position: right center;
    background-clip: border-box;
    -moz-background-clip: border-box;
    -webkit-background-clip: border-box;
}

    .archive .options select.opt::-ms-expand {
        display: none;
    }

Just be careful with proper URL-encoding because of IE. You must use charset=utf8 (not just utf8), don't use double-quotes (") to delimit SVG attribute values, use apostrophes (') instead to simplify your life. URL-encode s (%3E). In case you havee to print any non-ASCII characters you have to obtain their UTF-8 representation (e.g. BabelMap can help you with that) and then provide that representation in URL-encoded form - e.g. for ? (U+25BE BLACK DOWN-POINTING SMALL TRIANGLE) UTF-8 representation is \xE2\x96\xBE which is %E2%96%BE when URL-encoded.

ParseError: not well-formed (invalid token) using cElementTree

I have been in stuck with similar problem. Finally figured out the what was the root cause in my particular case. If you read the data from multiple XML files that lie in same folder you will parse also .DS_Store file. Before parsing add this condition

for file in files:
    if file.endswith('.xml'):
       run_your_code...

This trick helped me as well

Add column with constant value to pandas dataframe

Here is another one liner using lambdas (create column with constant value = 10)

df['newCol'] = df.apply(lambda x: 10, axis=1)

before

df
    A           B           C
1   1.764052    0.400157    0.978738
2   2.240893    1.867558    -0.977278
3   0.950088    -0.151357   -0.103219

after

df
        A           B           C           newCol
    1   1.764052    0.400157    0.978738    10
    2   2.240893    1.867558    -0.977278   10
    3   0.950088    -0.151357   -0.103219   10

How to validate an email address in PHP

I think you might be better off using PHP's inbuilt filters - in this particular case:

It can return a true or false when supplied with the FILTER_VALIDATE_EMAIL param.

How to retrieve element value of XML using Java?

There are various APIs available to read/write XML files through Java. I would refer using StaX

Also This can be useful - Java XML APIs

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:

SHOW GRANTS;

You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with

mysql

login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:

[mysqld]
skip-grant-tables
skip-networking

Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql

mysql

Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

The developers of this app have not set up this app properly for Facebook Login?

Now, You need to add a "Privacy Policy URL" in the App Details tab (developers.facebook.com). This is a new Policy of Facebook.

How to hide scrollbar in Firefox?

I got it working for me in ReactJS using create-react-app by putting this in my App.css:

@-moz-document url-prefix() {
  html,
  body {
    scrollbar-width: none;
  }
}

Also, the body element has overflow: auto

Running command line silently with VbScript and getting output?

You can redirect output to a file and then read the file:

return = WshShell.Run("cmd /c C:\snmpset -c ... > c:\temp\output.txt", 0, true)

Set fso  = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("c:\temp\output.txt", 1)
text = file.ReadAll
file.Close

Javascript / Chrome - How to copy an object from the webkit inspector as code

Add this to your console and execute

copy(JSON.stringify(foo));

This copies your JSON to clipboard

try/catch blocks with async/await

A cleaner alternative would be the following:

Due to the fact that every async function is technically a promise

You can add catches to functions when calling them with await

async function a(){
    let error;

    // log the error on the parent
    await b().catch((err)=>console.log('b.failed'))

    // change an error variable
    await c().catch((err)=>{error=true; console.log(err)})

    // return whatever you want
    return error ? d() : null;
}
a().catch(()=>console.log('main program failed'))

No need for try catch, as all promises errors are handled, and you have no code errors, you can omit that in the parent!!

Lets say you are working with mongodb, if there is an error you might prefer to handle it in the function calling it than making wrappers, or using try catches.

NodeJS - What does "socket hang up" actually mean?

I think worth noting...

I was creating tests for Google APIs. I was intercepting the request with a makeshift server, then forwarding those to the real api. I was attempting to just pass along the headers in the request, but a few headers were causing a problem with express on the other end.

Namely, I had to delete connection, accept, and content-length headers before using the request module to forward along.

let headers = Object.assign({}, req.headers);
delete headers['connection']
delete headers['accept']
delete headers['content-length']
res.end() // We don't need the incoming connection anymore
request({
  method: 'post',
  body: req.body,
  headers: headers,
  json: true,
  url: `http://myapi/${req.url}`
}, (err, _res, body)=>{
  if(err) return done(err);
  // Test my api response here as if Google sent it.
})

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

TL;DR

For JDK 11 try this:

To handle this problem in a clean way, I suggest to use brew and jenv.

For Java 11 follow this 2 steps, first :

JAVA_VERSION=11
brew reinstall jenv 
brew reinstall openjdk@${JAVA_VERSION}
jenv add /usr/local/opt/openjdk@${JAVA_VERSION}/
jenv global ${JAVA_VERSION}

And add this at end of your shell config scripts
~/.bashrc or ~/.zshrc

export PATH="$HOME/.jenv/bin:$PATH"
eval "$(jenv init -)"
export JAVA_HOME="$HOME/.jenv/versions/`jenv version-name`"

Problem solved!

Then restart your shell and try to execute java -version

Note: If you have this problem, your current JDK version is not existent or misconfigured (or may be you have only JRE).

How can I increment a date by one day in Java?

Something like this should do the trick:

String dt = "2008-01-01";  // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1);  // number of days to add
dt = sdf.format(c.getTime());  // dt is now the new date

How do I compare version numbers in Python?

There is packaging package available, which will allow you to compare versions as per PEP-440, as well as legacy versions.

>>> from packaging.version import Version, LegacyVersion
>>> Version('1.1') < Version('1.2')
True
>>> Version('1.2.dev4+deadbeef') < Version('1.2')
True
>>> Version('1.2.8.5') <= Version('1.2')
False
>>> Version('1.2.8.5') <= Version('1.2.8.6')
True

Legacy version support:

>>> LegacyVersion('1.2.8.5-5-gdeadbeef')
<LegacyVersion('1.2.8.5-5-gdeadbeef')>

Comparing legacy version with PEP-440 version.

>>> LegacyVersion('1.2.8.5-5-gdeadbeef') < Version('1.2.8.6')
True

Can I return the 'id' field after a LINQ insert?

Try this:

MyContext Context = new MyContext(); 
Context.YourEntity.Add(obj);
Context.SaveChanges();
int ID = obj._ID;

Convert string to JSON array

Input String

[
   {
      "userName": "sandeep",
      "age": 30
   }, 
   {
      "userName": "vivan",
      "age": 5
   }
]

Simple Way to Convert String to JSON

public class Test
{

    public static void main(String[] args) throws JSONException
    {
        String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}]  ";
        JSONArray jsonArr = new JSONArray(data);

        for (int i = 0; i < jsonArr.length(); i++)
        {
            JSONObject jsonObj = jsonArr.getJSONObject(i);

            System.out.println(jsonObj);
        }

    }
}

Output

{"userName":"sandeep","age":30}
{"userName":"vivan","age":5}

How to create a dump with Oracle PL/SQL Developer?

Export (or datapump if you have 10g/11g) is the way to do it. Why not ask how to fix your problems with that rather than trying to find another way to do it?

Why does my Eclipse keep not responding?

I just restarted the adb (Android Debug Bridge) this way:

  1. adb kill-server
  2. adb start-server

and it works again!

Replacing a character from a certain index

As strings are immutable in Python, just create a new string which includes the value at the desired index.

Assuming you have a string s, perhaps s = "mystring"

You can quickly (and obviously) replace a portion at a desired index by placing it between "slices" of the original.

s = s[:index] + newstring + s[index + 1:]

You can find the middle by dividing your string length by 2 len(s)/2

If you're getting mystery inputs, you should take care to handle indices outside the expected range

def replacer(s, newstring, index, nofail=False):
    # raise an error if index is outside of the string
    if not nofail and index not in range(len(s)):
        raise ValueError("index outside given string")

    # if not erroring, but the index is still not in the correct range..
    if index < 0:  # add it to the beginning
        return newstring + s
    if index > len(s):  # add it to the end
        return s + newstring

    # insert the new string between "slices" of the original
    return s[:index] + newstring + s[index + 1:]

This will work as

replacer("mystring", "12", 4)
'myst12ing'

webpack is not recognized as a internal or external command,operable program or batch file

I've had same issue and just added the code block into my package.json file;

 "scripts": {
   "build": "webpack -d --progress --colors"
 }

and then run command on terminal;

npm run build

Adding a guideline to the editor in Visual Studio

Visual Studio 2017 / 2019

For anyone looking for an answer for a newer version of Visual Studio, install the Editor Guidelines plugin, then right-click in the editor and select this:

Add guidelines in Visual Studio 2017

How can I check MySQL engine type for a specific table?

To show a list of all the tables in a database and their engines, use this SQL query:

SELECT TABLE_NAME,
       ENGINE
FROM   information_schema.TABLES
WHERE  TABLE_SCHEMA = 'dbname';

Replace dbname with your database name.

Change placeholder text

I have been facing the same problem.

In JS, first you have to clear the textbox of the text input. Otherwise the placeholder text won't show.

Here's my solution.

document.getElementsByName("email")[0].value="";
document.getElementsByName("email")[0].placeholder="your message";

MongoDB "root" user

While out of the box, MongoDb has no authentication, you can create the equivalent of a root/superuser by using the "any" roles to a specific user to the admin database.

Something like this:

use admin
db.addUser( { user: "<username>",
          pwd: "<password>",
          roles: [ "userAdminAnyDatabase",
                   "dbAdminAnyDatabase",
                   "readWriteAnyDatabase"

] } )

Update for 2.6+

While there is a new root user in 2.6, you may find that it doesn't meet your needs, as it still has a few limitations:

Provides access to the operations and all the resources of the readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase and clusterAdmin roles combined.

root does not include any access to collections that begin with the system. prefix.

Update for 3.0+

Use db.createUser as db.addUser was removed.

Update for 3.0.7+

root no longer has the limitations stated above.

The root has the validate privilege action on system. collections. Previously, root does not include any access to collections that begin with the system. prefix other than system.indexes and system.namespaces.

How to use @Nullable and @Nonnull annotations more effectively?

I agree that the annotations "don't propagate very far". However, I see the mistake on the programmer's side.

I understand the Nonnull annotation as documentation. The following method expresses that is requires (as a precondition) a non-null argument x.

    public void directPathToA(@Nonnull Integer x){
        x.toString(); // do stuff to x        
    }

The following code snippet then contains a bug. The method calls directPathToA() without enforcing that y is non-null (that is, it does not guarantee the precondition of the called method). One possibility is to add a Nonnull annotation as well to indirectPathToA() (propagating the precondition). Possibility two is to check for the nullity of y in indirectPathToA() and avoid the call to directPathToA() when y is null.

    public void indirectPathToA(Integer y){
        directPathToA(y);
    }

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

Trigger a keypress/keydown/keyup event in JS/jQuery?

You can trigger any of the events with a direct call to them, like this:

$(function() {
    $('item').keydown();
    $('item').keypress();
    $('item').keyup();
    $('item').blur();
});

Does that do what you're trying to do?

You should probably also trigger .focus() and potentially .change()

If you want to trigger the key-events with specific keys, you can do so like this:

$(function() {
    var e = $.Event('keypress');
    e.which = 65; // Character 'A'
    $('item').trigger(e);
});

There is some interesting discussion of the keypress events here: jQuery Event Keypress: Which key was pressed?, specifically regarding cross-browser compatability with the .which property.

Import Google Play Services library in Android Studio

After hours of having the same problem, notice that if your jar is on the libs folder will cause problem once you set it upon the "Dependencies ", so i just comment the file tree dependencies and keep the one using

dependencies

//compile fileTree(dir: 'libs', include: ['*.jar'])  <-------- commented one 
compile 'com.google.android.gms:play-services:8.1.0'
compile 'com.android.support:appcompat-v7:22.2.1'

and the problem was solved.

How to upgrade scikit-learn package in anaconda

Following Worked for me for scikit-learn on Anaconda-Jupyter Notebook.

Upgrading my scikit-learn from 0.19.1 to 0.19.2 in anaconda installed on Ubuntu on Google VM instance:

Run the following commands in the terminal:

First, check existing available packages with versions by using:

conda list    

It will show different packages and their installed versions in the output. Here check for scikit-learn. e.g. for me, the output was:

scikit-learn              0.19.1           py36hedc7406_0  

Now I want to Upgrade to 0.19.2 July 2018 release i.e. latest available version.

conda config --append channels conda-forge
conda install scikit-learn=0.19.2

As you are trying to upgrade to 0.17 version try the following command:

conda install scikit-learn=0.17

Now check the required version of the scikit-learn is installed correctly or not by using:

conda list 

For me the Output was:

scikit-learn              0.19.2          py36_blas_openblasha84fab4_201  [blas_openblas]  conda-forge

Note: Don't use pip command if you are using Anaconda or Miniconda

I tried following commands:

!conda update conda 
!pip install -U scikit-learn

It will install the required packages also will show in the conda list but if you try to import that package it will not work.

On the website http://scikit-learn.org/stable/install.html it is mentioned as: Warning To upgrade or uninstall scikit-learn installed with Anaconda or conda you should not use the pip.

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

Select your terminal Command prompt instead of Power shell. That should work.

What is the facade design pattern?

One additional use of Façade pattern could be to reduce the learning curve of your team. Let me give you an example:

Let us assume that your application needs to interact with MS Excel by making use of the COM object model provided by the Excel. One of your team members knows all the Excel APIs and he creates a Facade on top of it, which fulfills all the basic scenarios of the application. No other member on the team need to spend time on learning Excel API. The team can use the facade without knowing the internals or all the MS Excel objects involved in fulfilling a scenario. Is not it great?

Thus, it provides a simplified and unified interface on top of a complex sub-system.

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

i had this issue before and the comments here helped in the past but this time it did not. i checked my proguard configuration and i removed the following lines and then it worked so proguard can have something to do with this error:

 -optimizationpasses 5
        -overloadaggressively
        -repackageclasses ''
        -allowaccessmodification
        -dontskipnonpubliclibraryclassmembers

forEach loop Java 8 for Map entry set

String ss = "Pawan kavita kiyansh Patidar Patidar";
    StringBuilder ress = new StringBuilder();
    
    Map<Character, Integer> fre = ss.chars().boxed()
            .collect(Collectors.toMap(k->Character.valueOf((char) k.intValue()),k->1,Integer::sum));
    
      //fre.forEach((k, v) -> System.out.println((k + ":" + v)));
    
    fre.entrySet().forEach(e ->{
            //System.out.println(e.getKey() + ":" + e.getValue());
            //ress.append(String.valueOf(e.getKey())+e.getValue());
        }); 

    fre.forEach((k,v)->{
        //System.out.println("Item : " + k + " Count : " + v);
        ress.append(String.valueOf(k)+String.valueOf(v));
    });
    
    System.out.println(ress.toString());

Javascript get object key name

Assuming that you have access to Prototype, this could work. I wrote this code for myself just a few minutes ago; I only needed a single key at a time, so this isn't time efficient for big lists of key:value pairs or for spitting out multiple key names.

function key(int) {
    var j = -1;
    for(var i in this) {
        j++;
        if(j==int) {
            return i;
        } else {
            continue;
        }
    }
}
Object.prototype.key = key;

This is numbered to work the same way that arrays do, to save headaches. In the case of your code:

buttons.key(0) // Should result in "button1"

How do I open a URL from C++?

C isn't as high-level as the scripting language you mention. But if you want to stay away from socket-based programming, try Curl. Curl is a great C library and has many features. I have used it for years and always recommend it. It also includes some stand alone programs for testing or shell use.

INFO: No Spring WebApplicationInitializer types detected on classpath

I had this info message "No Spring WebApplicationInitializer types detected on classpath" while deploying a WAR with spring integration beans in WebLogic server. Actually, I could observe that the servlet URL returned 404 Not Found and beside that info message with a negative tone "No Spring ...etc" in Server logs, nothing else was seemingly in error in my spring config; no build or deployment errors, no complaints. Indeed, I suspected that the beans.xml (spring context XML) was actually not picked up at all and that was bound to the very specific organizing of artefacts in Oracle's jDeveloper. The solution is to play carefully with the 'contributors' and 'filters' for the WEB-INF/classes category when you edit your deployment profile under the 'deployment' topic in project properties.

Precisely, I would advise to name your spring context by the jDeveloper default "beans.xml" and place it side by side to the WEB-INF subdirectory itself (under your web Apllication source path, e.g. like <...your project path>/public_html/). Then in the WEB-INF/classes category (when editing the deployment profile) your can check the Project HTML root directory in the 'contributor' list, and then select the beans.xml in filters, and then ensure your web.xml features a context-param value like classpath:beans.xml.

Once that was fixed, I was able to progress and after some more bean config changes and implementations, the message "No Spring WebApplicationInitializer types detected on classpath" came back! Actually, I did not notice when and why exactly it came back. This second time, I added a

public class HttpGatewayInit implements WebApplicationInitializer { ... }

which implements empty inherited methods, and the whole application works fine!

...If you feel that java EE development has been getting a bit too crazy with cascades of XML configuration files (some edited manually, others through wizards) intepreted by cascades of variant initializers, let me insist that I fully share your point.

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

    SELECT art.* , sec.section.title, cat.title, use1.name, use2.name as modifiedby
FROM article art
INNER JOIN section sec ON art.section_id = sec.section.id
INNER JOIN category cat ON art.category_id = cat.id
INNER JOIN user use1 ON art.author_id = use1.id
LEFT JOIN user use2 ON art.modified_by = use2.id
WHERE art.id = '1';

Hope This Might Help

Why shouldn't I use mysql_* functions in PHP?

PHP offers three different APIs to connect to MySQL. These are the mysql(removed as of PHP 7), mysqli, and PDO extensions.

The mysql_* functions used to be very popular, but their use is not encouraged anymore. The documentation team is discussing the database security situation, and educating users to move away from the commonly used ext/mysql extension is part of this (check php.internals: deprecating ext/mysql).

And the later PHP developer team has taken the decision to generate E_DEPRECATED errors when users connect to MySQL, whether through mysql_connect(), mysql_pconnect() or the implicit connection functionality built into ext/mysql.

ext/mysql was officially deprecated as of PHP 5.5 and has been removed as of PHP 7.

See the Red Box?

When you go on any mysql_* function manual page, you see a red box, explaining it should not be used anymore.

Why


Moving away from ext/mysql is not only about security, but also about having access to all the features of the MySQL database.

ext/mysql was built for MySQL 3.23 and only got very few additions since then while mostly keeping compatibility with this old version which makes the code a bit harder to maintain. Missing features that is not supported by ext/mysql include: (from PHP manual).

Reason to not use mysql_* function:

  • Not under active development
  • Removed as of PHP 7
  • Lacks an OO interface
  • Doesn't support non-blocking, asynchronous queries
  • Doesn't support prepared statements or parameterized queries
  • Doesn't support stored procedures
  • Doesn't support multiple statements
  • Doesn't support transactions
  • Doesn't support all of the functionality in MySQL 5.1

Above point quoted from Quentin's answer

Lack of support for prepared statements is particularly important as they provide a clearer, less error prone method of escaping and quoting external data than manually escaping it with a separate function call.

See the comparison of SQL extensions.


Suppressing deprecation warnings

While code is being converted to MySQLi/PDO, E_DEPRECATED errors can be suppressed by setting error_reporting in php.ini to exclude E_DEPRECATED:

error_reporting = E_ALL ^ E_DEPRECATED

Note that this will also hide other deprecation warnings, which, however, may be for things other than MySQL. (from PHP manual)

The article PDO vs. MySQLi: Which Should You Use? by Dejan Marjanovic will help you to choose.

And a better way is PDO, and I am now writing a simple PDO tutorial.


A simple and short PDO tutorial


Q. First question in my mind was: what is `PDO`?

A. “PDO – PHP Data Objects – is a database access layer providing a uniform method of access to multiple databases.”

alt text


Connecting to MySQL

With mysql_* function or we can say it the old way (deprecated in PHP 5.5 and above)

$link = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('testdb', $link);
mysql_set_charset('UTF-8', $link);

With PDO: All you need to do is create a new PDO object. The constructor accepts parameters for specifying the database source PDO's constructor mostly takes four parameters which are DSN (data source name) and optionally username, password.

Here I think you are familiar with all except DSN; this is new in PDO. A DSN is basically a string of options that tell PDO which driver to use, and connection details. For further reference, check PDO MySQL DSN.

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');

Note: you can also use charset=UTF-8, but sometimes it causes an error, so it's better to use utf8.

If there is any connection error, it will throw a PDOException object that can be caught to handle Exception further.

Good read: Connections and Connection management ¶

You can also pass in several driver options as an array to the fourth parameter. I recommend passing the parameter which puts PDO into exception mode. Because some PDO drivers don't support native prepared statements, so PDO performs emulation of the prepare. It also lets you manually enable this emulation. To use the native server-side prepared statements, you should explicitly set it false.

The other is to turn off prepare emulation which is enabled in the MySQL driver by default, but prepare emulation should be turned off to use PDO safely.

I will later explain why prepare emulation should be turned off. To find reason please check this post.

It is only usable if you are using an old version of MySQL which I do not recommended.

Below is an example of how you can do it:

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 
              'username', 
              'password',
              array(PDO::ATTR_EMULATE_PREPARES => false,
              PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

Can we set attributes after PDO construction?

Yes, we can also set some attributes after PDO construction with the setAttribute method:

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 
              'username', 
              'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

Error Handling


Error handling is much easier in PDO than mysql_*.

A common practice when using mysql_* is:

//Connected to MySQL
$result = mysql_query("SELECT * FROM table", $link) or die(mysql_error($link));

OR die() is not a good way to handle the error since we can not handle the thing in die. It will just end the script abruptly and then echo the error to the screen which you usually do NOT want to show to your end users, and let bloody hackers discover your schema. Alternately, the return values of mysql_* functions can often be used in conjunction with mysql_error() to handle errors.

PDO offers a better solution: exceptions. Anything we do with PDO should be wrapped in a try-catch block. We can force PDO into one of three error modes by setting the error mode attribute. Three error handling modes are below.

  • PDO::ERRMODE_SILENT. It's just setting error codes and acts pretty much the same as mysql_* where you must check each result and then look at $db->errorInfo(); to get the error details.
  • PDO::ERRMODE_WARNING Raise E_WARNING. (Run-time warnings (non-fatal errors). Execution of the script is not halted.)
  • PDO::ERRMODE_EXCEPTION: Throw exceptions. It represents an error raised by PDO. You should not throw a PDOException from your own code. See Exceptions for more information about exceptions in PHP. It acts very much like or die(mysql_error());, when it isn't caught. But unlike or die(), the PDOException can be caught and handled gracefully if you choose to do so.

Good read:

Like:

$stmt->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
$stmt->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$stmt->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

And you can wrap it in try-catch, like below:

try {
    //Connect as appropriate as above
    $db->query('hi'); //Invalid query!
} 
catch (PDOException $ex) {
    echo "An Error occured!"; //User friendly message/message you want to show to user
    some_logging_function($ex->getMessage());
}

You do not have to handle with try-catch right now. You can catch it at any time appropriate, but I strongly recommend you to use try-catch. Also it may make more sense to catch it at outside the function that calls the PDO stuff:

function data_fun($db) {
    $stmt = $db->query("SELECT * FROM table");
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

//Then later
try {
    data_fun($db);
}
catch(PDOException $ex) {
    //Here you can handle error and show message/perform action you want.
}

Also, you can handle by or die() or we can say like mysql_*, but it will be really varied. You can hide the dangerous error messages in production by turning display_errors off and just reading your error log.

Now, after reading all the things above, you are probably thinking: what the heck is that when I just want to start leaning simple SELECT, INSERT, UPDATE, or DELETE statements? Don't worry, here we go:


Selecting Data

PDO select image

So what you are doing in mysql_* is:

<?php
$result = mysql_query('SELECT * from table') or die(mysql_error());

$num_rows = mysql_num_rows($result);

while($row = mysql_fetch_assoc($result)) {
    echo $row['field1'];
}

Now in PDO, you can do this like:

<?php
$stmt = $db->query('SELECT * FROM table');

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['field1'];
}

Or

<?php
$stmt = $db->query('SELECT * FROM table');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

//Use $results

Note: If you are using the method like below (query()), this method returns a PDOStatement object. So if you want to fetch the result, use it like above.

<?php
foreach($db->query('SELECT * FROM table') as $row) {
    echo $row['field1'];
}

In PDO Data, it is obtained via the ->fetch(), a method of your statement handle. Before calling fetch, the best approach would be telling PDO how you’d like the data to be fetched. In the below section I am explaining this.

Fetch Modes

Note the use of PDO::FETCH_ASSOC in the fetch() and fetchAll() code above. This tells PDO to return the rows as an associative array with the field names as keys. There are many other fetch modes too which I will explain one by one.

First of all, I explain how to select fetch mode:

 $stmt->fetch(PDO::FETCH_ASSOC)

In the above, I have been using fetch(). You can also use:

Now I come to fetch mode:

  • PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
  • PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

There are even more choices! Read about them all in PDOStatement Fetch documentation..

Getting the row count:

Instead of using mysql_num_rows to get the number of returned rows, you can get a PDOStatement and do rowCount(), like:

<?php
$stmt = $db->query('SELECT * FROM table');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';

Getting the Last Inserted ID

<?php
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();

Insert and Update or Delete statements

Insert and update PDO image

What we are doing in mysql_* function is:

<?php
$results = mysql_query("UPDATE table SET field='value'") or die(mysql_error());
echo mysql_affected_rows($result);

And in pdo, this same thing can be done by:

<?php
$affected_rows = $db->exec("UPDATE table SET field='value'");
echo $affected_rows;

In the above query PDO::exec execute an SQL statement and returns the number of affected rows.

Insert and delete will be covered later.

The above method is only useful when you are not using variable in query. But when you need to use a variable in a query, do not ever ever try like the above and there for prepared statement or parameterized statement is.


Prepared Statements

Q. What is a prepared statement and why do I need them?
A. A prepared statement is a pre-compiled SQL statement that can be executed multiple times by sending only the data to the server.

The typical workflow of using a prepared statement is as follows (quoted from Wikipedia three 3 point):

  1. Prepare: The statement template is created by the application and sent to the database management system (DBMS). Certain values are left unspecified, called parameters, placeholders or bind variables (labelled ? below):

    INSERT INTO PRODUCT (name, price) VALUES (?, ?)

  2. The DBMS parses, compiles, and performs query optimization on the statement template, and stores the result without executing it.

  3. Execute: At a later time, the application supplies (or binds) values for the parameters, and the DBMS executes the statement (possibly returning a result). The application may execute the statement as many times as it wants with different values. In this example, it might supply 'Bread' for the first parameter and 1.00 for the second parameter.

You can use a prepared statement by including placeholders in your SQL. There are basically three ones without placeholders (don't try this with variable its above one), one with unnamed placeholders, and one with named placeholders.

Q. So now, what are named placeholders and how do I use them?
A. Named placeholders. Use descriptive names preceded by a colon, instead of question marks. We don't care about position/order of value in name place holder:

 $stmt->bindParam(':bla', $bla);

bindParam(parameter,variable,data_type,length,driver_options)

You can also bind using an execute array as well:

<?php
$stmt = $db->prepare("SELECT * FROM table WHERE id=:id AND name=:name");
$stmt->execute(array(':name' => $name, ':id' => $id));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Another nice feature for OOP friends is that named placeholders have the ability to insert objects directly into your database, assuming the properties match the named fields. For example:

class person {
    public $name;
    public $add;
    function __construct($a,$b) {
        $this->name = $a;
        $this->add = $b;
    }

}
$demo = new person('john','29 bla district');
$stmt = $db->prepare("INSERT INTO table (name, add) value (:name, :add)");
$stmt->execute((array)$demo);

Q. So now, what are unnamed placeholders and how do I use them?
A. Let's have an example:

<?php
$stmt = $db->prepare("INSERT INTO folks (name, add) values (?, ?)");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->bindValue(2, $add, PDO::PARAM_STR);
$stmt->execute();

and

$stmt = $db->prepare("INSERT INTO folks (name, add) values (?, ?)");
$stmt->execute(array('john', '29 bla district'));

In the above, you can see those ? instead of a name like in a name place holder. Now in the first example, we assign variables to the various placeholders ($stmt->bindValue(1, $name, PDO::PARAM_STR);). Then, we assign values to those placeholders and execute the statement. In the second example, the first array element goes to the first ? and the second to the second ?.

NOTE: In unnamed placeholders we must take care of the proper order of the elements in the array that we are passing to the PDOStatement::execute() method.


SELECT, INSERT, UPDATE, DELETE prepared queries

  1. SELECT:

    $stmt = $db->prepare("SELECT * FROM table WHERE id=:id AND name=:name");
    $stmt->execute(array(':name' => $name, ':id' => $id));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
  2. INSERT:

    $stmt = $db->prepare("INSERT INTO table(field1,field2) VALUES(:field1,:field2)");
    $stmt->execute(array(':field1' => $field1, ':field2' => $field2));
    $affected_rows = $stmt->rowCount();
    
  3. DELETE:

    $stmt = $db->prepare("DELETE FROM table WHERE id=:id");
    $stmt->bindValue(':id', $id, PDO::PARAM_STR);
    $stmt->execute();
    $affected_rows = $stmt->rowCount();
    
  4. UPDATE:

    $stmt = $db->prepare("UPDATE table SET name=? WHERE id=?");
    $stmt->execute(array($name, $id));
    $affected_rows = $stmt->rowCount();
    

NOTE:

However PDO and/or MySQLi are not completely safe. Check the answer Are PDO prepared statements sufficient to prevent SQL injection? by ircmaxell. Also, I am quoting some part from his answer:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->query('SET NAMES GBK');
$stmt = $pdo->prepare("SELECT * FROM test WHERE name = ? LIMIT 1");
$stmt->execute(array(chr(0xbf) . chr(0x27) . " OR 1=1 /*"));

Test if a vector contains a given element

I really like grep() and grepl() for this purpose.

grep() returns a vector of integers, which indicate where matches are.

yo <- c("a", "a", "b", "b", "c", "c")

grep("b", yo)
[1] 3 4

grepl() returns a logical vector, with "TRUE" at the location of matches.

yo <- c("a", "a", "b", "b", "c", "c")

grepl("b", yo)
[1] FALSE FALSE  TRUE  TRUE FALSE FALSE

These functions are case-sensitive.

Check for special characters (/*-+_@&$#%) in a string?

The easiest way it to use a regular expression:

Regular Expression for alphanumeric and underscores

Using regular expressions in .net:

http://www.regular-expressions.info/dotnet.html

MSDN Regular Expression

Regex.IsMatch

var regexItem = new Regex("^[a-zA-Z0-9 ]*$");

if(regexItem.IsMatch(YOUR_STRING)){..}

Get list of certificates from the certificate store in C#

Yes -- the X509Store.Certificates property returns a snapshot of the X.509 certificate store.

JavaScript Chart.js - Custom data formatting to display on tooltip

In Chart.Js 2.8.0, the configuration for custom tooltips can be found here: https://www.chartjs.org/docs/latest/configuration/tooltip.html#label-callback (Thanks to @prokaktus)

If you want to e.g. show some values with a prefix or postfix (In the example, the script adds a unit of kWh to the values in the chart), you could do this like:

options: {
  rotation: 1 * Math.PI,
  circumference: 1 * Math.PI,
  tooltips: {
    callbacks: {
      label: function(tooltipItem, data) {
        console.log(data);
        console.log(tooltipItem);

        var label = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] || '';

        if (label) {
          label += ' kWh';
        }

        return label;
      }
    }
  }
}

An example fiddle is here, too: https://jsfiddle.net/y3petw58/1/

How to convert string to string[]?

A string holds one value, but a string[] holds many strings, as it's an array of string.

See more here

How to use jQuery in chrome extension?

In my case got a working solution through Cross-document Messaging (XDM) and Executing Chrome extension onclick instead of page load.

manifest.json

{
  "name": "JQuery Light",
  "version": "1",
  "manifest_version": 2,

  "browser_action": {
    "default_icon": "icon.png"
  },

  "content_scripts": [
    {
      "matches": [
        "https://*.google.com/*"
      ],
      "js": [
        "jquery-3.3.1.min.js",
        "myscript.js"
      ]
    }
  ],

  "background": {
    "scripts": [
      "background.js"
    ]
  }

}

background.js

chrome.browserAction.onClicked.addListener(function (tab) {
  chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
  });
});

myscript.js

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.message === "clicked_browser_action") {
        console.log('Hello world!')
        }
    }
);

How do I connect to a SQL Server 2008 database using JDBC?

If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.

Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).

Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.

Python - How do you run a .py file?

Your command should include the url parameter as stated in the script usage comments. The main function has 2 parameters, url and out (which is set to a default value) C:\python23\python "C:\PathToYourScript\SCRIPT.py" http://yoururl.com "C:\OptionalOutput\"

Sum of two input value by jquery

Your code is correct, except you are adding (concatenating) strings, not adding integers. Just change your code into:

function compute() {
    if ( $('input[name=type]:checked').val() != undefined ) {
        var a = parseInt($('input[name=service_price]').val());
        var b = parseInt($('input[name=modem_price]').val());
        var total = a+b;
        $('#total_price').val(a+b);
    }
}

and this should work.

Here is some working example that updates the sum when the value when checkbox is checked (and if this is checked, the value is also updated when one of the fields is changed): jsfiddle.

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

This cannot work because ppCombined is a collection of objects in memory and you cannot join a set of data in the database with another set of data that is in memory. You can try instead to extract the filtered items personProtocol of the ppCombined collection in memory after you have retrieved the other properties from the database:

var persons = db.Favorites
    .Where(f => f.userId == userId)
    .Join(db.Person, f => f.personId, p => p.personId, (f, p) =>
        new // anonymous object
        {
            personId = p.personId,
            addressId = p.addressId,   
            favoriteId = f.favoriteId,
        })
    .AsEnumerable() // database query ends here, the rest is a query in memory
    .Select(x =>
        new PersonDTO
        {
            personId = x.personId,
            addressId = x.addressId,   
            favoriteId = x.favoriteId,
            personProtocol = ppCombined
                .Where(p => p.personId == x.personId)
                .Select(p => new PersonProtocol
                {
                    personProtocolId = p.personProtocolId,
                    activateDt = p.activateDt,
                    personId = p.personId
                })
                .ToList()
        });

Access a JavaScript variable from PHP

JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.

Android Studio installation on Windows 7 fails, no JDK found

  1. Add JAVA_HOME and JDK_HOME system environment variables.
  2. Right-click android studio (the 64 version if that's your OS and JDK) and go to compatibility tab and set "Run as administrator" to true.
  3. Run android studio and high-five me virtually when it works.
  4. If that fails, try "where java" in cmd.exe. If it lists c:\system32\java.exe first, then rename the file and try again.

Print directly from browser without print popup window

For IE browsers, the "VBScript solution" works.

But as mentioned by @purefusion at Bypass Printdialog in IE9, Use Print() rather than window.print()

How to detect a route change in Angular?

Angular 7, if you want to subscribe to router

import { Router, NavigationEnd } from '@angular/router';

import { filter } from 'rxjs/operators';

constructor(
  private router: Router
) {
  router.events.pipe(
    filter(event => event instanceof NavigationEnd)  
  ).subscribe((event: NavigationEnd) => {
    console.log(event.url);
  });
}

jQuery changing font family and font size

If you only want to change the font in the TEXTAREA then you only need to change the changeFont() function in the original code to:

function changeFont(_name) {
    document.getElementById("mytextarea").style.fontFamily = _name;
}

Then selecting a font will change on the font only in the TEXTAREA.

How to run C program on Mac OS X using Terminal?

First make sure you correct your program:

#include <stdio.h>

int main(void) {
   printf("Hello, world!\n"); //printf instead of pintf
   return 0;
}

Save the file as HelloWorld.c and type in the terminal:

gcc -o HelloWorld HelloWorld.c

Afterwards just run the executable like this:

./HelloWorld

You should be seeing Hello World!

Can't connect to local MySQL server through socket homebrew

I manually started mysql in the system preferences pane by initialising the database and then starting it. This solved my problem.

Removing a Fragment from the back stack

You add to the back state from the FragmentTransaction and remove from the backstack using FragmentManager pop methods:

FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove(myFrag);
trans.commit();
manager.popBackStack();

Enable IIS7 gzip

You will need to enable the feature in the Windows Features control panel:

IIS feature screenshot

How to create python bytes object from long hex string?

result = bytes.fromhex(some_hex_string)

Check if datetime instance falls in between other two datetime objects

DateTime.Ticks will account for the time. Use .Ticks on the DateTime to convert your dates into longs. Then just use a simple if stmt to see if your target date falls between.

// Assuming you know d2 > d1
if (targetDt.Ticks > d1.Ticks && targetDt.Ticks < d2.Ticks)
{
    // targetDt is in between d1 and d2
}  

jQuery equivalent to Prototype array.last()

url : www.mydomain.com/user1/1234

$.params = window.location.href.split("/"); $.params[$.params.length-1];

You can split based on your query string separator

How to make a new line or tab in <string> XML (eclipse/android)?

You can use \n for new line and \t for tabs. Also, extra spaces/tabs are just copied the way you write them in Strings.xml so just give a couple of spaces where ever you want them.

A better way to reach this would probably be using padding/margin in your view xml and splitting up your long text in different strings in your string.xml

setTimeout or setInterval?

I've made simple test of setInterval(func, milisec), because I was curious what happens when function time consumption is greater than interval duration.

setInterval will generally schedule next iteration just after the start of the previous iteration, unless the function is still ongoing. If so, setInterval will wait, till the function ends. As soon as it happens, the function is immediately fired again - there is no waiting for next iteration according to schedule (as it would be under conditions without time exceeded function). There is also no situation with parallel iterations running.

I've tested this on Chrome v23. I hope it is deterministic implementation across all modern browsers.

window.setInterval(function(start) {
    console.log('fired: ' + (new Date().getTime() - start));
    wait();
  }, 1000, new Date().getTime());

Console output:

fired: 1000    + ~2500 ajax call -.
fired: 3522    <------------------'
fired: 6032
fired: 8540
fired: 11048

The wait function is just a thread blocking helper - synchronous ajax call which takes exactly 2500 milliseconds of processing at the server side:

function wait() {
    $.ajax({
        url: "...",
        async: false
    });
}

What are the most-used vim commands/keypresses?

Here's a tip sheet I wrote up once, with the commands I actually use regularly:

References

General

  • Nearly all commands can be preceded by a number for a repeat count. eg. 5dd delete 5 lines
  • <Esc> gets you out of any mode and back to command mode
  • Commands preceded by : are executed on the command line at the bottom of the screen
  • :help help with any command

Navigation

  • Cursor movement: ?h ?j ?k l?
  • By words:
    • w next word (by punctuation); W next word (by spaces)
    • b back word (by punctuation); B back word (by spaces)
    • e end word (by punctuation); E end word (by spaces)
  • By line:
    • 0 start of line; ^ first non-whitespace
    • $ end of line
  • By paragraph:
    • { previous blank line; } next blank line
  • By file:
    • gg start of file; G end of file
    • 123G go to specific line number
  • By marker:
    • mx set mark x; 'x go to mark x
    • '. go to position of last edit
    • ' ' go back to last point before jump
  • Scrolling:
    • ^F forward full screen; ^B backward full screen
    • ^D down half screen; ^U up half screen
    • ^E scroll one line up; ^Y scroll one line down
    • zz centre cursor line

Editing

  • u undo; ^R redo
  • . repeat last editing command

Inserting

All insertion commands are terminated with <Esc> to return to command mode.

  • i insert text at cursor; I insert text at start of line
  • a append text after cursor; A append text after end of line
  • o open new line below; O open new line above

Changing

  • r replace single character; R replace multiple characters
  • s change single character
  • cw change word; C change to end of line; cc change whole line
  • c<motion> changes text in the direction of the motion
  • ci( change inside parentheses (see text object selection for more examples)

Deleting

  • x delete char
  • dw delete word; D delete to end of line; dd delete whole line
  • d<motion> deletes in the direction of the motion

Cut and paste

  • yy copy line into paste buffer; dd cut line into paste buffer
  • p paste buffer below cursor line; P paste buffer above cursor line
  • xp swap two characters (x to delete one character, then p to put it back after the cursor position)

Blocks

  • v visual block stream; V visual block line; ^V visual block column
    • most motion commands extend the block to the new cursor position
    • o moves the cursor to the other end of the block
  • d or x cut block into paste buffer
  • y copy block into paste buffer
  • > indent block; < unindent block
  • gv reselect last visual block

Global

  • :%s/foo/bar/g substitute all occurrences of "foo" to "bar"
    • % is a range that indicates every line in the file
    • /g is a flag that changes all occurrences on a line instead of just the first one

Searching

  • / search forward; ? search backward
  • * search forward for word under cursor; # search backward for word under cursor
  • n next match in same direction; N next match in opposite direction
  • fx forward to next character x; Fx backward to previous character x
  • ; move again to same character in same direction; , move again to same character in opposite direction

Files

  • :w write file to disk
  • :w name write file to disk as name
  • ZZ write file to disk and quit
  • :n edit a new file; :n! edit a new file without saving current changes
  • :q quit editing a file; :q! quit editing without saving changes
  • :e edit same file again (if changed outside vim)
  • :e . directory explorer

Windows

  • ^Wn new window
  • ^Wj down to next window; ^Wk up to previous window
  • ^W_ maximise current window; ^W= make all windows equal size
  • ^W+ increase window size; ^W- decrease window size

Source Navigation

  • % jump to matching parenthesis/bracket/brace, or language block if language module loaded
  • gd go to definition of local symbol under cursor; ^O return to previous position
  • ^] jump to definition of global symbol (requires tags file); ^T return to previous position (arbitrary stack of positions maintained)
  • ^N (in insert mode) automatic word completion

Show local changes

Vim has some features that make it easy to highlight lines that have been changed from a base version in source control. I have created a small vim script that makes this easy: http://github.com/ghewgill/vim-scmdiff

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

  • The execution of maven command required pom.xml file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects.

  • Make sure that porject should contains pom.xml at the root level.

Regex expressions in Java, \\s vs. \\s+

Those two replaceAll calls will always produce the same result, regardless of what x is. However, it is important to note that the two regular expressions are not the same:

  • \\s - matches single whitespace character
  • \\s+ - matches sequence of one or more whitespace characters.

In this case, it makes no difference, since you are replacing everything with an empty string (although it would be better to use \\s+ from an efficiency point of view). If you were replacing with a non-empty string, the two would behave differently.

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

Performing a Stress Test on Web Application?

For simple usage, I perfer ab(apache benchmark) and siege, later one is needed as ab don't support cookie and would create endless sessions from dynamic site.

both are simple to start:

ab -c n -t 30 url

siege -b -c n -t 30s url

siege can run with more urls.

last siege version turn verbose on in siegerc, which is annoy. you can only disable it by edit that file(/usr/local/etc/siegerc).

excel delete row if column contains value from to-remove-list

I've found a more reliable method (at least on Excel 2016 for Mac) is:

Assuming your long list is in column A, and the list of things to be removed from this is in column B, then paste this into all the rows of column C:

= IF(COUNTIF($B$2:$B$99999,A2)>0,"Delete","Keep")

Then just sort the list by column C to find what you have to delete.

Wrapping a react-router Link in an html button

Many of the solutions have focused on complicating things.

Using withRouter is a really long solution for something as simple as a button that links to somewhere else in the App.

If you are going for S.P.A. (single page application), the easiest answer I have found is to use with the button's equivalent className.

This ensures you are maintaining shared state / context without reloading your entire app as is done with

import { NavLink } from 'react-router-dom'; // 14.6K (gzipped: 5.2 K)

// Where link.{something} is the imported data
<NavLink className={`bx--btn bx--btn--primary ${link.className}`} to={link.href} activeClassName={'active'}>
    {link.label}
</NavLink>

// Simplified version:
<NavLink className={'bx--btn bx--btn--primary'} to={'/myLocalPath'}>
    Button without using withRouter
</NavLink>

Android - R cannot be resolved to a variable

Agree it is probably due to a problem in resources that is preventing build of R.Java in gen. In my case a cut n paste had given a duplicate app name in string. Sort the fault, delete gen directory and clean.

How to extract the hostname portion of a URL in JavaScript

Try

document.location.host

or

document.location.hostname

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

The ~ selector is in fact the General sibling combinator (renamed to Subsequent-sibling combinator in selectors Level 4):

The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

Consider the following example:

_x000D_
_x000D_
.a ~ .b {_x000D_
  background-color: powderblue;_x000D_
}
_x000D_
<ul>_x000D_
  <li class="b">1st</li>_x000D_
  <li class="a">2nd</li>_x000D_
  <li>3rd</li>_x000D_
  <li class="b">4th</li>_x000D_
  <li class="b">5th</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

.a ~ .b matches the 4th and 5th list item because they:

  • Are .b elements
  • Are siblings of .a
  • Appear after .a in HTML source order.

Likewise, .check:checked ~ .content matches all .content elements that are siblings of .check:checked and appear after it.

Convert an int to ASCII character

"I have int i = 6; and I want char c = '6' by conversion. Any simple way to suggest?"

There are only 10 numbers. So write a function that takes an int from 0-9 and returns the ascii code. Just look it up in an ascii table and write a function with ifs or a select case.

Fitting a Normal distribution to 1D data

There is a much simpler way to do it using seaborn:

import seaborn as sns
from scipy.stats import norm

data = norm.rvs(5,0.4,size=1000) # you can use a pandas series or a list if you want

sns.distplot(data)
plt.show()

output:

enter image description here

for more information:seaborn.distplot

Determining whether an object is a member of a collection in VBA

this version works for primitive types and for classes (short test-method included)

' TODO: change this to the name of your module
Private Const sMODULE As String = "MVbaUtils"

Public Function ExistsInCollection(oCollection As Collection, sKey As String) As Boolean
    Const scSOURCE As String = "ExistsInCollection"

    Dim lErrNumber As Long
    Dim sErrDescription As String

    lErrNumber = 0
    sErrDescription = "unknown error occurred"
    Err.Clear
    On Error Resume Next
        ' note: just access the item - no need to assign it to a dummy value
        ' and this would not be so easy, because we would need different
        ' code depending on the type of object
        ' e.g.
        '   Dim vItem as Variant
        '   If VarType(oCollection.Item(sKey)) = vbObject Then
        '       Set vItem = oCollection.Item(sKey)
        '   Else
        '       vItem = oCollection.Item(sKey)
        '   End If
        oCollection.Item sKey
        lErrNumber = CLng(Err.Number)
        sErrDescription = Err.Description
    On Error GoTo 0

    If lErrNumber = 5 Then ' 5 = not in collection
        ExistsInCollection = False
    ElseIf (lErrNumber = 0) Then
        ExistsInCollection = True
    Else
        ' Re-raise error
        Err.Raise lErrNumber, mscMODULE & ":" & scSOURCE, sErrDescription
    End If
End Function

Private Sub Test_ExistsInCollection()
    Dim asTest As New Collection

    Debug.Assert Not ExistsInCollection(asTest, "")
    Debug.Assert Not ExistsInCollection(asTest, "xx")

    asTest.Add "item1", "key1"
    asTest.Add "item2", "key2"
    asTest.Add New Collection, "key3"
    asTest.Add Nothing, "key4"
    Debug.Assert ExistsInCollection(asTest, "key1")
    Debug.Assert ExistsInCollection(asTest, "key2")
    Debug.Assert ExistsInCollection(asTest, "key3")
    Debug.Assert ExistsInCollection(asTest, "key4")
    Debug.Assert Not ExistsInCollection(asTest, "abcx")

    Debug.Print "ExistsInCollection is okay"
End Sub

Table column sizing

Using d-flex class works well but some other attributes don't work anymore like vertical-align: middle property.

The best way I found to size columns very easily is to use the width attribute with percentage only in thead cells.

<table class="table">
    <thead>
        <tr>
            <th width="25%">25%</th>
            <th width="25%">25%</th>
            <th width="50%">50%</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>25%</td>
            <td>25%</td>
            <td>50%</td>
        </tr>
    </tbody>
</table>

Can not connect to local PostgreSQL

This really looks like a file permissions error. Unix domain sockets are files and have user permissions just like any other. It looks as though the OSX user attempting to access the database does not have file permissions to access the socket file. To confirm this I've done some tests on Ubuntu and psql to try to generate the same error (included below).

You need to check the permissions on the socket file and its directories /var and /var/pgsql_socket. Your Rails app (OSX user) must have execute (x) permissions on these directories (preferably grant everyone permissions) and the socket should have full permissions (wrx). You can use ls -lAd <file> to check these, and if any of them are a symlink you need to check the file or dir the link points to.

You can change the permissions on the dir for youself, but the socket is configured by postgres in postgresql.conf. This can be found in the same directory as pg_hba.conf (You'll have to figure out which one). Once you've set the permissions you will need to restart postgresql.

# postgresql.conf should contain...
unix_socket_directory = '/var/run/postgresql'       # dont worry if yours is different
#unix_socket_group = ''                             # default is fine here
#unix_socket_permissions = 0777                     # check this one and uncomment if necessary.

EDIT:

I've done a quick search on google which you may wish to look into to see if it is relavent. This might well result in any attempt to find your config file failing.

http://www.postgresqlformac.com/server/howto_edit_postgresql_confi.html


Error messages:

User not found in pg_hba.conf

psql: FATAL:  no pg_hba.conf entry for host "[local]", user "couling", database "main", SSL off

User failed password auth:

psql: FATAL:  password authentication failed for user "couling"

Missing unix socket file:

psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Unix socket exists, but server not listening to it.

psql: could not connect to server: Connection refused
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Bad file permissions on unix socket file:

psql: could not connect to server: Permission denied
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

How to generate different random numbers in a loop in C++?

Do not use rand(); use new C++11 facilities (e.g. std::mt19937, std::uniform_int_distribution, etc.) instead.

You can use code like this (live here on Ideone):

#include <iostream>
#include <random>
using namespace std;

int main()
{
    // Random seed
    random_device rd;

    // Initialize Mersenne Twister pseudo-random number generator
    mt19937 gen(rd());

    // Generate pseudo-random numbers
    // uniformly distributed in range (1, 100)
    uniform_int_distribution<> dis(1, 100);

    // Generate ten pseudo-random numbers
    for (int i = 0; i < 10; i++)
    {
        int randomX = dis(gen);
        cout << "\nRandom X = " << randomX;
    }
}

P.S.

Consider watching this video from Going Native 2013 conference for more details about rand()-related problems:

rand() Considered Harmful

How do I send an HTML email?

Set content type. Look at this method.

message.setContent("<h1>Hello</h1>", "text/html");

Python coding standards/best practices

To add to bhadra's list of idiomatic guides:

Checkout Anthony Baxter's presentation on Effective Python Programming (from OSON 2005).

An excerpt:

# dict's setdefault method turns this:
if key in dictobj:
    dictobj[key].append(val)
else:
    dictobj[key] = [val]
# into this:
dictobj.setdefault(key,[]).append(val)

Python Pandas merge only certain columns

You could merge the sub-DataFrame (with just those columns):

df2[list('xab')]  # df2 but only with columns x, a, and b

df1.merge(df2[list('xab')])

Select elements by attribute in CSS

Is it possible to select elements in CSS by their HTML5 data attributes? This can easily be answered just by trying it, and the answer is, of course, yes. But this invariably leads us to the next question, 'Should we select elements in CSS by their HTML5 data attributes?' There are conflicting opinions on this.

In the 'no' camp is (or at least was, back in 2014) CSS legend Harry Roberts. In the article, Naming UI components in OOCSS, he wrote:

It’s important to note that although we can style HTML via its data-* attributes, we probably shouldn’t. data-* attributes are meant for holding data in markup, not for selecting on. This, from the HTML Living Standard (emphasis mine):

"Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements."

The W3C spec was frustratingly vague on this point, but based purely on what it did and didn't say, I think Harry's conclusion was perfectly reasonable.

Since then, plenty of articles have suggested that it's perfectly appropriate to use custom data attributes as styling hooks, including MDN's guide, Using data attributes. There's even a CSS methodology called CUBE CSS which has adopted the data attribute hook as the preferred way of adding styles to component 'exceptions' (known as modifiers in BEM).

Thankfully, the WHATWG HTML Living Standard has since added a few more words and even some examples (emphasis mine):

Custom data attributes are intended to store custom data, state, annotations, and similar, private to the page or application, for which there are no more appropriate attributes or elements.

In this example, custom data attributes are used to store the result of a feature detection for PaymentRequest, which could be used in CSS to style a checkout page differently.

Authors should carefully design such extensions so that when the attributes are ignored and any associated CSS dropped, the page is still usable.


TL;DR: Yes, it's okay to use data-* attributes in CSS selectors, provided the page is still usable without them.

Xcode couldn't find any provisioning profiles matching

I am now able to successfully build. Not sure exactly which step "fixed" things, but this was the sequence:

  • Tried automatic signing again. No go, so reverted to manual.
  • After reverting, I had no Eligible Profiles, all were ineligible. Strange.
  • I created a new certificate and profile, imported both. This too was "ineligible".
  • Removed the iOS platform and re-added it. I had tried this previously without luck.
  • After doing this, Xcode on its own defaulted to automatic signing. And this worked! Success!

While I am not sure exactly which parts were necessary, I think the previous certificates were the problem. I hate Xcode :(

Thanks for help.

Problem with converting int to string in Linq to entities

My understanding is that you have to create a partial class to "extend" your model and add a property that is readonly that can utilize the rest of the class's properties.

public partial class Contact{

   public string ContactIdString
   {
      get{ 
            return this.ContactId.ToString();
      }
   } 
}

Then

var items = from c in contacts
select new ListItem
{
    Value = c.ContactIdString, 
    Text = c.Name
};

Is it possible to modify a string of char in C?

A lot of folks get confused about the difference between char* and char[] in conjunction with string literals in C. When you write:

char *foo = "hello world";

...you are actually pointing foo to a constant block of memory (in fact, what the compiler does with "hello world" in this instance is implementation-dependent.)

Using char[] instead tells the compiler that you want to create an array and fill it with the contents, "hello world". foo is the a pointer to the first index of the char array. They both are char pointers, but only char[] will point to a locally allocated and mutable block of memory.

django templates: include and extends

This should do the trick for you: put include tag inside of a block section.

page1.html:

{% extends "base1.html" %}

{% block foo %}
   {% include "commondata.html" %}
{% endblock %}

page2.html:

{% extends "base2.html" %}

{% block bar %}
   {% include "commondata.html" %}
{% endblock %}

Using SSH keys inside docker container

Expanding Peter Grainger's answer I was able to use multi-stage build available since Docker 17.05. Official page states:

With multi-stage builds, you use multiple FROM statements in your Dockerfile. Each FROM instruction can use a different base, and each of them begins a new stage of the build. You can selectively copy artifacts from one stage to another, leaving behind everything you don’t want in the final image.

Keeping this in mind here is my example of Dockerfile including three build stages. It's meant to create a production image of client web application.

# Stage 1: get sources from npm and git over ssh
FROM node:carbon AS sources
ARG SSH_KEY
ARG SSH_KEY_PASSPHRASE
RUN mkdir -p /root/.ssh && \
    chmod 0700 /root/.ssh && \
    ssh-keyscan bitbucket.org > /root/.ssh/known_hosts && \
    echo "${SSH_KEY}" > /root/.ssh/id_rsa && \
    chmod 600 /root/.ssh/id_rsa
WORKDIR /app/
COPY package*.json yarn.lock /app/
RUN eval `ssh-agent -s` && \
    printf "${SSH_KEY_PASSPHRASE}\n" | ssh-add $HOME/.ssh/id_rsa && \
    yarn --pure-lockfile --mutex file --network-concurrency 1 && \
    rm -rf /root/.ssh/

# Stage 2: build minified production code
FROM node:carbon AS production
WORKDIR /app/
COPY --from=sources /app/ /app/
COPY . /app/
RUN yarn build:prod

# Stage 3: include only built production files and host them with Node Express server
FROM node:carbon
WORKDIR /app/
RUN yarn add express
COPY --from=production /app/dist/ /app/dist/
COPY server.js /app/
EXPOSE 33330
CMD ["node", "server.js"]

.dockerignore repeats contents of .gitignore file (it prevents node_modules and resulting dist directories of the project from being copied):

.idea
dist
node_modules
*.log

Command example to build an image:

$ docker build -t ezze/geoport:0.6.0 \
  --build-arg SSH_KEY="$(cat ~/.ssh/id_rsa)" \
  --build-arg SSH_KEY_PASSPHRASE="my_super_secret" \
  ./

If your private SSH key doesn't have a passphrase just specify empty SSH_KEY_PASSPHRASE argument.

This is how it works:

1). On the first stage only package.json, yarn.lock files and private SSH key are copied to the first intermediate image named sources. In order to avoid further SSH key passphrase prompts it is automatically added to ssh-agent. Finally yarn command installs all required dependencies from NPM and clones private git repositories from Bitbucket over SSH.

2). The second stage builds and minifies source code of web application and places it in dist directory of the next intermediate image named production. Note that source code of installed node_modules is copied from the image named sources produced on the first stage by this line:

COPY --from=sources /app/ /app/

Probably it also could be the following line:

COPY --from=sources /app/node_modules/ /app/node_modules/

We have only node_modules directory from the first intermediate image here, no SSH_KEY and SSH_KEY_PASSPHRASE arguments anymore. All the rest required for build is copied from our project directory.

3). On the third stage we reduce a size of the final image that will be tagged as ezze/geoport:0.6.0 by including only dist directory from the second intermediate image named production and installing Node Express for starting a web server.

Listing images gives an output like this:

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ezze/geoport        0.6.0               8e8809c4e996        3 hours ago         717MB
<none>              <none>              1f6518644324        3 hours ago         1.1GB
<none>              <none>              fa00f1182917        4 hours ago         1.63GB
node                carbon              b87c2ad8344d        4 weeks ago         676MB

where non-tagged images correpsond to the first and the second intermediate build stages.

If you run

$ docker history ezze/geoport:0.6.0 --no-trunc

you will not see any mentions of SSH_KEY and SSH_KEY_PASSPHRASE in the final image.

How can I extract a number from a string in JavaScript?

please check below javaScripts, there you can get only number

_x000D_
_x000D_
var txt = "abc1234char5678#!9";_x000D_
var str = txt.match(/\d+/g, "")+'';_x000D_
var s = str.split(',').join('');_x000D_
alert(Number(s));
_x000D_
_x000D_
_x000D_

output : 1234567789

Echo tab characters in bash script

Using echo to print values of variables is a common Bash pitfall. Reference link:

http://mywiki.wooledge.org/BashPitfalls#echo_.24foo

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

You can download older versions of XAMPP here. PHP 5.3 was added in version 1.7.2, so anything older would be good.

PDO with INSERT INTO through prepared statements

I have just rewritten the code to the following:

    $dbhost = "localhost";
    $dbname = "pdo";
    $dbusername = "root";
    $dbpassword = "845625";

    $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $statement = $link->prepare("INSERT INTO testtable(name, lastname, age)
        VALUES(?,?,?)");

    $statement->execute(array("Bob","Desaunois",18));

And it seems to work now. BUT. if I on purpose cause an error to occur, it does not say there is any. The code works, but still; should I encounter more errors, I will not know why.

Convert date field into text in Excel

You don't need to convert the original entry - you can use TEXT function in the concatenation formula, e.g. with date in A1 use a formula like this

="Today is "&TEXT(A1,"dd-mm-yyyy")

You can change the "dd-mm-yyyy" part as required

Return index of greatest value in an array

A stable version of this function looks like this:

// not defined for empty array
function max_index(elements) {
    var i = 1;
    var mi = 0;
    while (i < elements.length) {
        if (!(elements[i] < elements[mi]))
            mi = i;
        i += 1;
    }
    return mi;
}

YouTube Video Embedded via iframe Ignoring z-index?

The answers abow didnt really work for me, i had a click event on the wrapper and ie 7,8,9,10 ignored the z-index, so my fix was giving the wrapper a background-color and it all of a sudden worked. Al though it was suppose to be transparent, so i defined the wrapper with the background-color white, and then opacity 0.01, and now it works. I also have the functions above, so it could be a combination.

I dont know why it works, im just happy it does.

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

string hex = "#FFFFFF";
Color _color = System.Drawing.ColorTranslator.FromHtml(hex);

Note: the hash is important!

Allow all remote connections, MySQL

Also you need to disable below line in configuration file: bind-address = 127.0.0.1

Check for database connection, otherwise display message

Try this:

<?php
$servername   = "localhost";
$database = "database";
$username = "user";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
  echo "Connected successfully";
?>

How do you append rows to a table using jQuery?

You should append to the table and not the rows.

<script type="text/javascript">
$('a').click(function() {
    $('#myTable').append('<tr class="child"><td>blahblah<\/td></tr>');
});
</script>

Java: Why is the Date constructor deprecated, and what do I use instead?

The java.util.Date class isn't actually deprecated, just that constructor, along with a couple other constructors/methods are deprecated. It was deprecated because that sort of usage doesn't work well with internationalization. The Calendar class should be used instead:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1988);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date dateRepresentation = cal.getTime();

Take a look at the date Javadoc:

http://download.oracle.com/javase/6/docs/api/java/util/Date.html

How to set the JSTL variable value in javascript?

It is not possible because they are executed in different environments (JSP at server side, JavaScript at client side). So they are not executed in the sequence you see in your code.

var val1 = document.getElementById('userName').value; 

<c:set var="user" value=""/>  // how do i set val1 here? 

Here JSTL code is executed at server side and the server sees the JavaScript/Html codes as simple texts. The generated contents from JSTL code (if any) will be rendered in the resulting HTML along with your other JavaScript/HTML codes. Now the browser renders HTML along with executing the Javascript codes. Now remember there is no JSTL code available for the browser.

Now for example,

<script type="text/javascript">
<c:set var="message" value="Hello"/> 
var message = '<c:out value="${message}"/>';
</script>

Now for the browser, this content is rendered,

<script type="text/javascript">
var message = 'Hello';
</script>

Hope this helps.

How to see the changes between two commits without commits in-between?

For checking complete changes:

  git diff <commit_Id_1> <commit_Id_2>

For checking only the changed/added/deleted files:

  git diff <commit_Id_1> <commit_Id_2> --name-only

NOTE: For checking diff without commit in between, you don't need to put the commit ids.

Get current URL from IFRAME

Hope this will help some how in your case, I suffered with the exact same problem, and just used localstorage to share the data between parent window and iframe. So in parent window you can:

localStorage.setItem("url", myUrl);

And in code where iframe source is just get this data from localstorage:

localStorage.getItem('url');

Saved me a lot of time. As far as i can see the only condition is access to the parent page code. Hope this will help someone.

Remove special symbols and extra spaces and replace with underscore using the replace method

Remove the \s from your new regex and it should work - whitespace is already included in "anything but alphanumerics".

Note that you may want to add a + after the ] so you don't get sequences of more than one underscore. You can also chain onto .replace(/^_+|_+$/g,'') to trim off underscores at the start or end of the string.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

The Pythonic way of summing an array is using sum. For other purposes, you can sometimes use some combination of reduce (from the functools module) and the operator module, e.g.:

def product(xs):
    return reduce(operator.mul, xs, 1)

Be aware that reduce is actually a foldl, in Haskell terms. There is no special syntax to perform folds, there's no builtin foldr, and actually using reduce with non-associative operators is considered bad style.

Using higher-order functions is quite pythonic; it makes good use of Python's principle that everything is an object, including functions and classes. You are right that lambdas are frowned upon by some Pythonistas, but mostly because they tend not to be very readable when they get complex.

What is the purpose of Android's <merge> tag in XML layouts?

To have a more in-depth knowledge of what's happening, I created the following example. Have a look at the activity_main.xml and content_profile.xml files.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/content_profile" />

</LinearLayout>

content_profile.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Howdy" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hi there" />

</LinearLayout>

In here, the entire layout file when inflated looks like this.

<LinearLayout>
    <LinearLayout>
        <TextView />
        <TextView />
    </LinearLayout>
</LinearLayout>

See that there is a LinearLayout inside the parent LinearLayout which doesn't serve any purpose and is redundant. A look at the layout through Layout Inspector tool clearly explains this.

enter image description here

content_profile.xml after updating the code to use merge instead of a ViewGroup like LinearLayout.

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Howdy" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hi there" />

</merge>

Now our layout looks like this

<LinearLayout>
    <TextView />
    <TextView />
</LinearLayout>

Here we see that the redundant LinearLayout ViewGroup is removed. Now Layout Inspector tool gives the following layout hierarchy.

enter image description here

So always try to use merge when your parent layout can position your child layouts, or more precisely use merge when you understand that there is going to be a redundant view group in the hierarchy.

When to use MyISAM and InnoDB?

Read about Storage Engines.

MyISAM:

The MyISAM storage engine in MySQL.

  • Simpler to design and create, thus better for beginners. No worries about the foreign relationships between tables.
  • Faster than InnoDB on the whole as a result of the simpler structure thus much less costs of server resources. -- Mostly no longer true.
  • Full-text indexing. -- InnoDB has it now
  • Especially good for read-intensive (select) tables. -- Mostly no longer true.
  • Disk footprint is 2x-3x less than InnoDB's. -- As of Version 5.7, this is perhaps the only real advantage of MyISAM.

InnoDB:

The InnoDB storage engine in MySQL.

  • Support for transactions (giving you support for the ACID property).
  • Row-level locking. Having a more fine grained locking-mechanism gives you higher concurrency compared to, for instance, MyISAM.
  • Foreign key constraints. Allowing you to let the database ensure the integrity of the state of the database, and the relationships between tables.
  • InnoDB is more resistant to table corruption than MyISAM.
  • Support for large buffer pool for both data and indexes. MyISAM key buffer is only for indexes.
  • MyISAM is stagnant; all future enhancements will be in InnoDB. This was made abundantly clear with the roll out of Version 8.0.

MyISAM Limitations:

  • No foreign keys and cascading deletes/updates
  • No transactional integrity (ACID compliance)
  • No rollback abilities
  • 4,284,867,296 row limit (2^32) -- This is old default. The configurable limit (for many versions) has been 2**56 bytes.
  • Maximum of 64 indexes per table

InnoDB Limitations:

  • No full text indexing (Below-5.6 mysql version)
  • Cannot be compressed for fast, read-only (5.5.14 introduced ROW_FORMAT=COMPRESSED)
  • You cannot repair an InnoDB table

For brief understanding read below links:

  1. MySQL Engines: InnoDB vs. MyISAM – A Comparison of Pros and Cons
  2. MySQL Engines: MyISAM vs. InnoDB
  3. What are the main differences between InnoDB and MyISAM?
  4. MyISAM versus InnoDB
  5. What's the difference between MyISAM and InnoDB?
  6. MySql: MyISAM vs. Inno DB!

Get connection string from App.config

string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;

Get current scroll position of ScrollView in React Native

Brad Oyler's answer is correct. But you will only receive one event. If you need to get constant updates of the scroll position, you should set the scrollEventThrottle prop, like so:

<ScrollView onScroll={this.handleScroll} scrollEventThrottle={16} >
  <Text>
    Be like water my friend …
  </Text>
</ScrollView>

And the event handler:

handleScroll: function(event: Object) {
  console.log(event.nativeEvent.contentOffset.y);
},

Be aware that you might run into performance issues. Adjust the throttle accordingly. 16 gives you the most updates. 0 only one.

hidden field in php

You absolutely can, I use this approach a lot w/ both JavaScript and PHP.

Field definition:

<input type="hidden" name="foo" value="<?php echo $var;?>" />

Access w/ PHP:

$_GET['foo'] or $_POST['foo']

Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php

Cheers!

Function to convert column number to letter?

This function returns the column letter for a given column number.

Function Col_Letter(lngCol As Long) As String
    Dim vArr
    vArr = Split(Cells(1, lngCol).Address(True, False), "$")
    Col_Letter = vArr(0)
End Function

testing code for column 100

Sub Test()
    MsgBox Col_Letter(100)
End Sub

How does Google calculate my location on a desktop?

I know you can look up IP address to get approximate location, but it's not always accurate. Perhaps they're using that?

update:

Typically, your browser uses information about the Wi-Fi access points around you to estimate your location. If no Wi-Fi access points are in range, or your computer doesn't have Wi-Fi, it may resort to using your computer's IP address to get an approximate location.

Adding content to a linear layout dynamically?

You can achieve LinearLayout cascading like this:

LinearLayout root = (LinearLayout) findViewById(R.id.my_root);    
LinearLayout llay1 = new LinearLayout(this);    
root.addView(llay1);
LinearLayout llay2 = new LinearLayout(this);    
llay1.addView(llay2);

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

No, there is no conversion. The JVM just iterates over the array using an index in the background.

Quote from Effective Java 2nd Ed., Item 46:

Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once.

So you can't get an Iterator for an array (unless of course by converting it to a List first).

How do I add Git version control (Bitbucket) to an existing source code folder?

You can init a Git directory in an directory containing other files. After that you can add files to the repository and commit there.

Create a project with some code:

$ mkdir my_project
$ cd my_project
$ echo "foobar" > some_file

Then, while inside the project's folder, do an initial commit:

$ git init
$ git add some_file
$ git commit -m "Initial commit"

Then for using Bitbucket or such you add a remote and push up:

$ git remote add some_name user@host:repo
$ git push some_name

You also might then want to configure tracking branches, etc. See git remote set-branches and related commands for that.

JavaScript: clone a function

Here is an updated answer

var newFunc = oldFunc.bind({}); //clones the function with '{}' acting as it's new 'this' parameter

However .bind is a modern ( >=iE9 ) feature of JavaScript (with a compatibility workaround from MDN)

Notes

  1. It does not clone the function object additional attached properties, including the prototype property. Credit to @jchook

  2. The new function this variable is stuck with the argument given on bind(), even on new function apply() calls. Credit to @Kevin

function oldFunc() {
  console.log(this.msg);
}
var newFunc = oldFunc.bind({ msg: "You shall not pass!" }); // this object is binded
newFunc.apply({ msg: "hello world" }); //logs "You shall not pass!" instead
  1. Bound function object, instanceof treats newFunc/oldFunc as the same. Credit to @Christopher
(new newFunc()) instanceof oldFunc; //gives true
(new oldFunc()) instanceof newFunc; //gives true as well
newFunc == oldFunc; //gives false however

Is there a JavaScript strcmp()?

What about

str1.localeCompare(str2)

How to use ConfigurationManager

I found some answers, but I don't know if it is the right way.This is my solution for now. Fortunatelly it didn´t broke my design mode.

    `
    /// <summary>
    /// set config, if key is not in file, create
    /// </summary>
    /// <param name="key">Nome do parâmetro</param>
    /// <param name="value">Valor do parâmetro</param>
    public static void SetConfig(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }

    /// <summary>
    /// Get key value, if not found, return null
    /// </summary>
    /// <param name="key"></param>
    /// <returns>null if key is not found, else string with value</returns>
    public static string GetConfig(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }`

How to update/upgrade a package using pip?

tl;dr script to update all installed packages

If you only want to upgrade one package, refer to @borgr's answer. I often find it necessary, or at least pleasing, to upgrade all my packages at once. Currently, pip doesn't natively support that action, but with sh scripting it is simple enough. You use pip list, awk (or cut and tail), and command substitution. My normal one-liner is:

for i in $(pip list -o | awk 'NR > 2 {print $1}'); do sudo pip install -U $i; done

This will ask for the root password. If you do not have access to that, the --user option of pip or virtualenv may be something to look into.

How do I create a table based on another table

There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT does exist in PDW. In SQL Server you can use this query to create an empty table:

SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;

(If you want to make a copy of the table including all of the data, then leave out the WHERE clause.)

Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.

In MS DOS copying several files to one file

make sure you have mapped the y: drive, or copy all the files to local dir c:/local

c:/local> copy *.* c:/newfile.txt

How do I make my string comparison case insensitive?

  • The best would be using s1.equalsIgnoreCase(s2): (see javadoc)
  • You can also convert them both to upper/lower case and use s1.equals(s2)

How to create a DataFrame from a text file in Spark

I have given different ways to create DataFrame from text file

val conf = new SparkConf().setAppName(appName).setMaster("local")
val sc = SparkContext(conf)

raw text file

val file = sc.textFile("C:\\vikas\\spark\\Interview\\text.txt")
val fileToDf = file.map(_.split(",")).map{case Array(a,b,c) => 
(a,b.toInt,c)}.toDF("name","age","city")
fileToDf.foreach(println(_))

spark session without schema

import org.apache.spark.sql.SparkSession
val sparkSess = 
SparkSession.builder().appName("SparkSessionZipsExample")
.config(conf).getOrCreate()

val df = sparkSess.read.option("header", 
"false").csv("C:\\vikas\\spark\\Interview\\text.txt")
df.show()

spark session with schema

import org.apache.spark.sql.types._
val schemaString = "name age city"
val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, 
StringType, nullable=true))
val schema = StructType(fields)

val dfWithSchema = sparkSess.read.option("header", 
"false").schema(schema).csv("C:\\vikas\\spark\\Interview\\text.txt")
dfWithSchema.show()

using sql context

import org.apache.spark.sql.SQLContext

val fileRdd = 
sc.textFile("C:\\vikas\\spark\\Interview\\text.txt").map(_.split(",")).map{x 
=> org.apache.spark.sql.Row(x:_*)}
val sqlDf = sqlCtx.createDataFrame(fileRdd,schema)
sqlDf.show()

ASP.NET MVC - Set custom IIdentity or IPrincipal

Here is a solution if you need to hook up some methods to @User for use in your views. No solution for any serious membership customization, but if the original question was needed for views alone then this perhaps would be enough. The below was used for checking a variable returned from a authorizefilter, used to verify if some links wehere to be presented or not(not for any kind of authorization logic or access granting).

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Security.Principal;

    namespace SomeSite.Web.Helpers
    {
        public static class UserHelpers
        {
            public static bool IsEditor(this IPrincipal user)
            {
                return null; //Do some stuff
            }
        }
    }

Then just add a reference in the areas web.config, and call it like below in the view.

@User.IsEditor()

Fetch: reject promise and catch the error if status is not OK?

For me, fny answers really got it all. since fetch is not throwing error, we need to throw/handle the error ourselves. Posting my solution with async/await. I think it's more strait forward and readable

Solution 1: Not throwing an error, handle the error ourselves

  async _fetch(request) {
    const fetchResult = await fetch(request); //Making the req
    const result = await fetchResult.json(); // parsing the response

    if (fetchResult.ok) {
      return result; // return success object
    }


    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    const error = new Error();
    error.info = responseError;

    return (error);
  }

Here if we getting an error, we are building an error object, plain JS object and returning it, the con is that we need to handle it outside. How to use:

  const userSaved = await apiCall(data); // calling fetch
  if (userSaved instanceof Error) {
    debug.log('Failed saving user', userSaved); // handle error

    return;
  }
  debug.log('Success saving user', userSaved); // handle success

Solution 2: Throwing an error, using try/catch

async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    let error = new Error();
    error = { ...error, ...responseError };
    throw (error);
  }

Here we are throwing and error that we created, since Error ctor approve only string, Im creating the plain Error js object, and the use will be:

  try {
    const userSaved = await apiCall(data); // calling fetch
    debug.log('Success saving user', userSaved); // handle success
  } catch (e) {
    debug.log('Failed saving user', userSaved); // handle error
  }

Solution 3: Using customer error

  async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    throw new ClassError(result.message, result.data, result.code);
  }

And:

class ClassError extends Error {

  constructor(message = 'Something went wrong', data = '', code = '') {
    super();
    this.message = message;
    this.data = data;
    this.code = code;
  }

}

Hope it helped.

Creating multiple log files of different content with log4j

This should get you started:

log4j.rootLogger=QuietAppender, LoudAppender, TRACE
# setup A1
log4j.appender.QuietAppender=org.apache.log4j.RollingFileAppender
log4j.appender.QuietAppender.Threshold=INFO
log4j.appender.QuietAppender.File=quiet.log
...


# setup A2
log4j.appender.LoudAppender=org.apache.log4j.RollingFileAppender
log4j.appender.LoudAppender.Threshold=DEBUG
log4j.appender.LoudAppender.File=loud.log
...

log4j.logger.com.yourpackage.yourclazz=TRACE

How to run Node.js as a background process and never die?

another solution disown the job

$ nohup node server.js &
[1] 1711
$ disown -h %1

Windows batch files: .bat vs .cmd?

.cmd and .bat file execution is different because in a .cmd errorlevel variable it can change on a command that is affected by command extensions. That's about it really.

Git Ignores and Maven targets

The .gitignore file in the root directory does apply to all subdirectories. Mine looks like this:

.classpath
.project
.settings/
target/

This is in a multi-module maven project. All the submodules are imported as individual eclipse projects using m2eclipse. I have no further .gitignore files. Indeed, if you look in the gitignore man page:

Patterns read from a .gitignore file in the same directory as the path, or in any parent directory

So this should work for you.

allowing only alphabets in text box using java script

:::::HTML:::::

<input type="text" onkeypress="return lettersValidate(event)" />

Only letters no spaces

::::JS::::::::

// ===================== Allow - Only Letters ===============================================================

function lettersValidate(key) {
    var keycode = (key.which) ? key.which : key.keyCode;

    if ((keycode > 64 && keycode < 91) || (keycode > 96 && keycode < 123))  
    {     
           return true;    
    }
    else
    {
        return false;
    }
         
}
 

How to Find Item in Dictionary Collection?

thisTag = _tags.FirstOrDefault(t => t.Key == tag);

is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.

The basic solution would be:

if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }

But that requires 2 lookups.

TryGetValue(key, out value) is more concise and efficient, it only does 1 lookup. And that answers the last part of your question, the best way to do a lookup is:

string myValue;
if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }

VS 2017 update, for C# 7 and beyond we can declare the result variable inline:

if (_tags.TryGetValue(tag, out string myValue))
{
    // use myValue;
}
// use myValue, still in scope, null if not found

Error message: "'chromedriver' executable needs to be available in the path"

Check the path of your chrome driver, it might not get it from there. Simply Copy paste the driver location into the code.

What are OLTP and OLAP. What is the difference between them?

Here you will find a better solution OLTP vs. OLAP

  • OLTP (On-line Transaction Processing) is involved in the operation of a particular system. OLTP is characterized by a large number of short on-line transactions (INSERT, UPDATE, DELETE). The main emphasis for OLTP systems is put on very fast query processing, maintaining data integrity in multi-access environments and an effectiveness measured by number of transactions per second. In OLTP database there is detailed and current data, and schema used to store transactional databases is the entity model (usually 3NF). It involves Queries accessing individual record like Update your Email in Company database.

  • OLAP (On-line Analytical Processing) deals with Historical Data or Archival Data. OLAP is characterized by relatively low volume of transactions. Queries are often very complex and involve aggregations. For OLAP systems a response time is an effectiveness measure. OLAP applications are widely used by Data Mining techniques. In OLAP database there is aggregated, historical data, stored in multi-dimensional schemas (usually star schema). Sometime query need to access large amount of data in Management records like what was the profit of your company in last year.

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.

Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.

Try something like this:

var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
    method: 'JSONP',
    url: url
}).
success(function(status) {
    //your code when success
}).
error(function(status) {
    //your code when fails
});

Converting a string to a date in a cell

Have you tried the =DateValue() function?

To include time value, just add the functions together:

=DateValue(A1)+TimeValue(A1)

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

I've seen this error too when the code stopped at the line:

Dim myNode As MSXML2.IXMLDOMNode

I found out that I had to add "Microsoft XML, v6.0" via Tools > Preferences.

Then it worked for me.

How do write IF ELSE statement in a MySQL query

SELECT col1, col2, IF( action = 2 AND state = 0, 1, 0 ) AS state from tbl1;

OR

SELECT col1, col2, (case when (action = 2 and state = 0) then 1 else 0 end) as state from tbl1;

both results will same....

.NET Global exception handler in console application

I just inherited an old VB.NET console application and needed to set up a Global Exception Handler. Since this question mentions VB.NET a few times and is tagged with VB.NET, but all the other answers here are in C#, I thought I would add the exact syntax for a VB.NET application as well.

Public Sub Main()
    REM Set up Global Unhandled Exception Handler.
    AddHandler System.AppDomain.CurrentDomain.UnhandledException, AddressOf MyUnhandledExceptionEvent

    REM Do other stuff
End Sub

Public Sub MyUnhandledExceptionEvent(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
    REM Log Exception here and do whatever else is needed
End Sub

I used the REM comment marker instead of the single quote here because Stack Overflow seemed to handle the syntax highlighting a bit better with REM.

Trying to add adb to PATH variable OSX

Add to PATH for every login

Total control version:

in your terminal, navigate to home directory

cd

create file .bash_profile

touch .bash_profile

open file with TextEdit

open -e .bash_profile

insert line into TextEdit

export PATH=$PATH:/Users/username/Library/Android/sdk/platform-tools/

save file and reload file

source ~/.bash_profile

check if adb was set into path

adb version


One liner version

Echo your export command and redirect the output to be appended to .bash_profile file and restart terminal. (have not verified this but should work)

echo "export PATH=$PATH:/Users/username/Library/Android/sdk/platform-tools/ sdk/platform-tools/" >> ~/.bash_profile

PHP equivalent of .NET/Java's toString()

I use variableToString. It handles every PHP type and is flexible (you can extend it if you want).

Sorting string array in C#

Actually I don't see any nulls:

given:

static void Main()
        {
            string[] testArray = new string[]
            {
                "aa",
                "ab",
                "ac",
                "ad",
                "ab",
                "af"
            };

            Array.Sort(testArray, StringComparer.InvariantCulture);

            Array.ForEach(testArray, x => Console.WriteLine(x));
        }

I obtained:

enter image description here

Using $_POST to get select option value from HTML


-- html file --

<select name='city[]'> 
                <option name='Kabul' value="Kabul" > Kabul </option>
                <option name='Herat' value='Herat' selected="selected">             Herat </option>
                <option name='Mazar' value='Mazar'>Mazar </option>
</select>

-- php file --

$city = (isset($_POST['city']) ? $_POST['city']: null);
print("city is: ".$city[0]);

How do I use raw_input in Python 3

Timmerman's solution works great when running the code, but if you don't want to get Undefined name errors when using pyflakes or a similar linter you could use the following instead:

try:
    import __builtin__
    input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
    pass

Concatenate two NumPy arrays vertically

a = np.array([1,2,3])
b = np.array([4,5,6])
np.array((a,b))

works just as well as

np.array([[1,2,3], [4,5,6]])

Regardless of whether it is a list of lists or a list of 1d arrays, np.array tries to create a 2d array.

But it's also a good idea to understand how np.concatenate and its family of stack functions work. In this context concatenate needs a list of 2d arrays (or any anything that np.array will turn into a 2d array) as inputs.

np.vstack first loops though the inputs making sure they are at least 2d, then does concatenate. Functionally it's the same as expanding the dimensions of the arrays yourself.

np.stack is a new function that joins the arrays on a new dimension. Default behaves just like np.array.

Look at the code for these functions. If written in Python you can learn quite a bit. For vstack:

return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)

Updating the list view when the adapter data changes

invalidate(); calls the list view to invalidate itself (ie. background color)
invalidateViews(); calls all of its children to be invalidated. allowing you to update the children views

I assume its some type of efficiency thing preventing all of the items to constantly have to be redraw if not necessary.

Add A Year To Today's Date

Use the Date.prototype.setFullYear method to set the year to what you want it to be.

For example:

var aYearFromNow = new Date();
aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);

There really isn't another way to work with dates in JavaScript if these methods aren't present in the environment you are working with.

Scala how can I count the number of occurrences in a list

scala> val list = List(1,2,4,2,4,7,3,2,4)
list: List[Int] = List(1, 2, 4, 2, 4, 7, 3, 2, 4)

scala> println(list.filter(_ == 2).size)
3

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

Since Ruby 2.5.0, Array ships with the prepend method (which is just an alias for the unshift method).

angularjs: ng-src equivalent for background-image:url(...)

Since you mentioned ng-src and it seems as though you want the page to finish rendering before loading your image, you may modify jaime's answer to run the native directive after the browser finishes rendering.

This blog post explains this pretty well; essentially, you insert the $timeout wrapper for window.setTimeout before the callback function wherein you make those modifications to the CSS.

javascript regex - look behind alternative?

If you can look ahead but back, you could reverse the string first and then do a lookahead. Some more work will need to be done, of course.

Applying function with multiple arguments to create a new pandas column

If you need to create multiple columns at once:

  1. Create the dataframe:

    import pandas as pd
    df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]})
    
  2. Create the function:

    def fab(row):                                                  
        return row['A'] * row['B'], row['A'] + row['B']
    
  3. Assign the new columns:

    df['newcolumn'], df['newcolumn2'] = zip(*df.apply(fab, axis=1))
    

Node.js server that accepts POST requests

Receive POST and GET request in nodejs :

1).Server

    var http = require('http');
    var server = http.createServer ( function(request,response){

    response.writeHead(200,{"Content-Type":"text\plain"});
    if(request.method == "GET")
        {
            response.end("received GET request.")
        }
    else if(request.method == "POST")
        {
            response.end("received POST request.");
        }
    else
        {
            response.end("Undefined request .");
        }
});

server.listen(8000);
console.log("Server running on port 8000");

2). Client :

var http = require('http');

var option = {
    hostname : "localhost" ,
    port : 8000 ,
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       }) 
    })
    request.end();

Disabling and enabling a html input button

Without jQuery disable input will be simpler

Button.disabled=1;

_x000D_
_x000D_
function dis() {_x000D_
  Button.disabled= !Button.disabled;_x000D_
}
_x000D_
<input id="Button" type="button" value="+" style="background-color:grey" onclick="Me();"/>_x000D_
_x000D_
<button onclick="dis()">Toggle disable</button>
_x000D_
_x000D_
_x000D_

Hide particular div onload and then show div after click

The second time you're referring to div2, you're not using the # id selector.

There's no element named div2.

create a white rgba / CSS3

I believe

rgba( 0, 0, 0, 0.8 )

is equivalent in shade with #333.

Live demo: http://jsfiddle.net/8MVC5/1/

When to use std::size_t?

size_t is unsigned int. so whenever you want unsigned int you can use it.

I use it when i want to specify size of the array , counter ect...

void * operator new (size_t size); is a good use of it.

How to get datetime in JavaScript?

try this:

_x000D_
_x000D_
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours()+':'+today.getMinutes()+':'+today.getSeconds();
console.log(date + ' '+ time);
_x000D_
_x000D_
_x000D_

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

If you are working on Root Directory then you can use this approach

res.sendFile(__dirname + '/FOLDER_IN_ROOT_DIRECTORY/index.html');

but if you are using Routes which is inside a folder lets say /Routes/someRoute.js then you will need to do something like this

const path = require("path");
...
route.get("/some_route", (req, res) => {
   res.sendFile(path.resolve('FOLDER_IN_ROOT_DIRECTORY/index.html')
});

How to properly compare two Integers in Java?

No, == between Integer, Long etc will check for reference equality - i.e.

Integer x = ...;
Integer y = ...;

System.out.println(x == y);

this will check whether x and y refer to the same object rather than equal objects.

So

Integer x = new Integer(10);
Integer y = new Integer(10);

System.out.println(x == y);

is guaranteed to print false. Interning of "small" autoboxed values can lead to tricky results:

Integer x = 10;
Integer y = 10;

System.out.println(x == y);

This will print true, due to the rules of boxing (JLS section 5.1.7). It's still reference equality being used, but the references genuinely are equal.

If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.

Personally I'd use:

if (x.intValue() == y.intValue())

or

if (x.equals(y))

As you say, for any comparison between a wrapper type (Integer, Long etc) and a numeric type (int, long etc) the wrapper type value is unboxed and the test is applied to the primitive values involved.

This occurs as part of binary numeric promotion (JLS section 5.6.2). Look at each individual operator's documentation to see whether it's applied. For example, from the docs for == and != (JLS 15.21.1):

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

and for <, <=, > and >= (JLS 15.20.1)

The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then signed integer comparison is performed; if this promoted type is float or double, then floating-point comparison is performed.

Note how none of this is considered as part of the situation where neither type is a numeric type.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)

Or when you deal with text in Python if it is a Unicode text, make a note it is Unicode.

Set text=u'unicode text' instead just text='unicode text'.

This worked in my case.

How to write a large buffer into a binary file in C++, fast?

Try using open()/write()/close() API calls and experiment with the output buffer size. I mean do not pass the whole "many-many-bytes" buffer at once, do a couple of writes (i.e., TotalNumBytes / OutBufferSize). OutBufferSize can be from 4096 bytes to megabyte.

Another try - use WinAPI OpenFile/CreateFile and use this MSDN article to turn off buffering (FILE_FLAG_NO_BUFFERING). And this MSDN article on WriteFile() shows how to get the block size for the drive to know the optimal buffer size.

Anyway, std::ofstream is a wrapper and there might be blocking on I/O operations. Keep in mind that traversing the entire N-gigabyte array also takes some time. While you are writing a small buffer, it gets to the cache and works faster.

How to write into a file in PHP?

$text = "Cats chase mice";
$filename = "somefile.txt";
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);

You use fwrite()

Add a string of text into an input field when user clicks a button

this will do it with just javascript - you can also put the function in a .js file and call it with onclick

//button
<div onclick="
   document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>

When is layoutSubviews called?

Building on the previous answer by @BadPirate, I experimented a bit further and came up with some clarifications/corrections. I found that layoutSubviews: will be called on a view if and only if:

  • Its own bounds (not frame) changed.
  • The bounds of one of its direct subviews changed.
  • A subview is added to the view or removed from the view.

Some relevant details:

  • The bounds are considered changed only if the new value is different, including a different origin. Note specifically that is why layoutSubviews: is called whenever a UIScrollView scrolls, as it performs the scrolling by changing its bounds' origin.
  • Changing the frame will only change the bounds if the size has changed, as this is the only thing propagated to the bounds property.
  • A change in bounds of a view that is not yet in a view hierarchy will result in a call to layoutSubviews: when the view is eventually added to a view hierarchy.
  • And just for completeness: these triggers do not directly call layoutSubviews, but rather call setNeedsLayout, which sets/raises a flag. Each iteration of the run loop, for all views in the view hierarchy, this flag is checked. For each view where the flag is found raised, layoutSubviews: is called on it and the flag is reset. Views higher up the hierarchy will be checked/called first.

How to read a value from the Windows registry

#include <windows.h>
#include <map>
#include <string>
#include <stdio.h>
#include <string.h>
#include <tr1/stdint.h>

using namespace std;

void printerr(DWORD dwerror) {
    LPVOID lpMsgBuf;
    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dwerror,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        (LPTSTR) &lpMsgBuf,
        0,
        NULL
    );
    // Process any inserts in lpMsgBuf.
    // ...
    // Display the string.
    if (isOut) {
        fprintf(fout, "%s\n", lpMsgBuf);
    } else {
        printf("%s\n", lpMsgBuf);
    }
    // Free the buffer.
    LocalFree(lpMsgBuf);
}



bool regreadSZ(string& hkey, string& subkey, string& value, string& returnvalue, string& regValueType) {
    char s[128000];
    map<string,HKEY> keys;
    keys["HKEY_CLASSES_ROOT"]=HKEY_CLASSES_ROOT;
    keys["HKEY_CURRENT_CONFIG"]=HKEY_CURRENT_CONFIG; //DID NOT SURVIVE?
    keys["HKEY_CURRENT_USER"]=HKEY_CURRENT_USER;
    keys["HKEY_LOCAL_MACHINE"]=HKEY_LOCAL_MACHINE;
    keys["HKEY_USERS"]=HKEY_USERS;
    HKEY mykey;

    map<string,DWORD> valuetypes;
    valuetypes["REG_SZ"]=REG_SZ;
    valuetypes["REG_EXPAND_SZ"]=REG_EXPAND_SZ;
    valuetypes["REG_MULTI_SZ"]=REG_MULTI_SZ; //probably can't use this.

    LONG retval=RegOpenKeyEx(
        keys[hkey],         // handle to open key
        subkey.c_str(),  // subkey name
        0,   // reserved
        KEY_READ, // security access mask
        &mykey    // handle to open key
    );
    if (ERROR_SUCCESS != retval) {printerr(retval); return false;}
    DWORD slen=128000;
    DWORD valuetype = valuetypes[regValueType];
    retval=RegQueryValueEx(
      mykey,            // handle to key
      value.c_str(),  // value name
      NULL,   // reserved
      (LPDWORD) &valuetype,       // type buffer
      (LPBYTE)s,        // data buffer
      (LPDWORD) &slen      // size of data buffer
    );
    switch(retval) {
        case ERROR_SUCCESS:
            //if (isOut) {
            //    fprintf(fout,"RegQueryValueEx():ERROR_SUCCESS:succeeded.\n");
            //} else {
            //    printf("RegQueryValueEx():ERROR_SUCCESS:succeeded.\n");
            //}
            break;
        case ERROR_MORE_DATA:
            //what do I do now?  data buffer is too small.
            if (isOut) {
                fprintf(fout,"RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\n");
            } else {
                printf("RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\n");
            }
            return false;
        case ERROR_FILE_NOT_FOUND:
            if (isOut) {
                fprintf(fout,"RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\n");
            } else {
                printf("RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\n");
            }
            return false;
        default:
            if (isOut) {
                fprintf(fout,"RegQueryValueEx():unknown error type 0x%lx.\n", retval);
            } else {
                printf("RegQueryValueEx():unknown error type 0x%lx.\n", retval);
            }
            return false;

    }
    retval=RegCloseKey(mykey);
    if (ERROR_SUCCESS != retval) {printerr(retval); return false;}

    returnvalue = s;
    return true;
}

Limit Decimal Places in Android EditText

The InputFilter I came up with allows you to configure the number of digits before and after the decimal place. Additionally, it disallows leading zeroes.

public class DecimalDigitsInputFilter implements InputFilter
{
    Pattern pattern;

    public DecimalDigitsInputFilter(int digitsBeforeDecimal, int digitsAfterDecimal)
    {
        pattern = Pattern.compile("(([1-9]{1}[0-9]{0," + (digitsBeforeDecimal - 1) + "})?||[0]{1})((\\.[0-9]{0," + digitsAfterDecimal + "})?)||(\\.)?");
    }

    @Override public CharSequence filter(CharSequence source, int sourceStart, int sourceEnd, Spanned destination, int destinationStart, int destinationEnd)
    {
        // Remove the string out of destination that is to be replaced.
        String newString = destination.toString().substring(0, destinationStart) + destination.toString().substring(destinationEnd, destination.toString().length());

        // Add the new string in.
        newString = newString.substring(0, destinationStart) + source.toString() + newString.substring(destinationStart, newString.length());

        // Now check if the new string is valid.
        Matcher matcher = pattern.matcher(newString);

        if(matcher.matches())
        {
            // Returning null indicates that the input is valid.
            return null;
        }

        // Returning the empty string indicates the input is invalid.
        return "";
    }
}

// To use this InputFilter, attach it to your EditText like so:
final EditText editText = (EditText) findViewById(R.id.editText);

EditText.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(4, 4)});

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

Can you load the GUIDs into a scratch table then do a

... WHERE var IN SELECT guid FROM #scratchtable

How to read the output from git diff?

It's unclear from your question which part of the diffs you find confusing: the actually diff, or the extra header information git prints. Just in case, here's a quick overview of the header.

The first line is something like diff --git a/path/to/file b/path/to/file - obviously it's just telling you what file this section of the diff is for. If you set the boolean config variable diff.mnemonic prefix, the a and b will be changed to more descriptive letters like c and w (commit and work tree).

Next, there are "mode lines" - lines giving you a description of any changes that don't involve changing the content of the file. This includes new/deleted files, renamed/copied files, and permissions changes.

Finally, there's a line like index 789bd4..0afb621 100644. You'll probably never care about it, but those 6-digit hex numbers are the abbreviated SHA1 hashes of the old and new blobs for this file (a blob is a git object storing raw data like a file's contents). And of course, the 100644 is the file's mode - the last three digits are obviously permissions; the first three give extra file metadata information (SO post describing that).

After that, you're on to standard unified diff output (just like the classic diff -U). It's split up into hunks - a hunk is a section of the file containing changes and their context. Each hunk is preceded by a pair of --- and +++ lines denoting the file in question, then the actual diff is (by default) three lines of context on either side of the - and + lines showing the removed/added lines.

Is there a way to add a gif to a Markdown file?

Upload from local:

  1. Add your .gif file to the root of Github repository and push the change.
  2. Go to README.md
  3. Add this ![Alt text](name-of-gif-file.gif) / ![](name-of-gif-file.gif)
  4. Commit and gif should be seen.

Show the gif using url:

  1. Go to README.md
  2. Add in this format ![Alt text](https://sample/url/name-of-gif-file.gif)
  3. Commit and gif should be seen.

Hope this helps.

Is having an 'OR' in an INNER JOIN condition a bad idea?

You can use UNION ALL instead.

SELECT mt.ID, mt.ParentID, ot.MasterID FROM dbo.MainTable AS mt Union ALL SELECT mt.ID, mt.ParentID, ot.MasterID FROM dbo.OtherTable AS ot

How to add additional fields to form before submit?

This works:

var form = $(this).closest('form');

form = form.serializeArray();

form = form.concat([
    {name: "customer_id", value: window.username},
    {name: "post_action", value: "Update Information"}
]);

$.post('/change-user-details', form, function(d) {
    if (d.error) {
        alert("There was a problem updating your user details")
    } 
});

Oracle DB : java.sql.SQLException: Closed Connection

It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.

How get permission for camera in android.(Specifically Marshmallow)

Requesting Permissions In the following code, we will ask for camera permission:

in java

EasyPermissions is a wrapper library to simplify basic system permissions logic when targeting Android M or higher.

Installation EasyPermissions is installed by adding the following dependency to your build.gradle file:

dependencies {

    // For developers using AndroidX in their applications
    implementation 'pub.devrel:easypermissions:3.0.0'

    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'

}


private void askAboutCamera(){

        EasyPermissions.requestPermissions(
                this,
                "A partir deste ponto a permissão de câmera é necessária.",
                CAMERA_REQUEST_CODE,
                Manifest.permission.CAMERA );
}

Iterating through all nodes in XML file

You can use XmlDocument. Also some XPath can be useful.

Just a simple example

XmlDocument doc = new XmlDocument();
doc.Load("sample.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here
foreach (XmlNode node in nodes)
{
   // use node variable here for your beeds
}

How to set a session variable when clicking a <a> link

    session_start();
    if(isset($_SESSION['current'])){
         $_SESSION['oldlink']=$_SESSION['current'];
    }else{
         $_SESSION['oldlink']='no previous page';
    }
    $_SESSION['current']=$_SERVER['PHP_SELF'];

Maybe this is what you're looking for? It will remember the old link/page you're coming from (within your website).

Put that piece on top of each page.

If you want to make it 'refresh proof' you can add another check:

   if(isset($_SESSION['current']) && $_SESSION['current']!=$_SERVER['PHP_SELF'])

This will make the page not remember itself.

UPDATE: Almost the same as @Brandon though... Just use a php variable, I know this looks like a security risk, but when done correct it isn't.

 <a href="home.php?a=register">Register Now!</a>

PHP:

 if(isset($_GET['a']) /*you can validate the link here*/){
    $_SESSION['link']=$_GET['a'];
 }

Why even store the GET in a session? Just use it. Please tell me why you do not want to use GET. « Validate for more security. I maybe can help you with a better script.

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

you can use this method just pass your date to it

-(NSString *)getDateFromString:(NSString *)string
{

    NSString * dateString = [NSString stringWithFormat: @"%@",string];

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"your current date format"];
    NSDate* myDate = [dateFormatter dateFromString:dateString];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"your desired format"];
    NSString *stringFromDate = [formatter stringFromDate:myDate];

    NSLog(@"%@", stringFromDate);
    return stringFromDate;
}

mysql server port number

default port of mysql is 3306

default pot of sql server is 1433

How to get text of an element in Selenium WebDriver, without including child element text?

In the HTML which you have shared:

<div id="a">This is some
   <div id="b">text</div>
</div>

The text This is some is within a text node. To depict the text node in a structured way:

<div id="a">
    This is some
   <div id="b">text</div>
</div>

This Usecase

To extract and print the text This is some from the text node using Selenium's client you have 2 ways as follows:

  • Using splitlines(): You can identify the parent element i.e. <div id="a">, extract the innerHTML and then use splitlines() as follows:

    • using xpath:

      print(driver.find_element_by_xpath("//div[@id='a']").get_attribute("innerHTML").splitlines()[0])
      
    • using xpath:

      print(driver.find_element_by_css_selector("div#a").get_attribute("innerHTML").splitlines()[0])
      
  • Using execute_script(): You can also use the execute_script() method which can synchronously execute JavaScript in the current window/frame as follows:

    • using xpath and firstChild:

      parent_element = driver.find_element_by_xpath("//div[@id='a']")
      print(driver.execute_script('return arguments[0].firstChild.textContent;', parent_element).strip())
      
    • using xpath and childNodes[n]:

      parent_element = driver.find_element_by_xpath("//div[@id='a']")
      print(driver.execute_script('return arguments[0].childNodes[1].textContent;', parent_element).strip())
      

How Do I Uninstall Yarn

If you installed with brew, try brew uninstall yarn at terminal prompt. Also remember to remove yarn path info in your .bash_profile.

How can I test an AngularJS service from the console?

Angularjs Dependency Injection framework is responsible for injecting the dependancies of you app module to your controllers. This is possible through its injector.

You need to first identify the ng-app and get the associated injector. The below query works to find your ng-app in the DOM and retrieve the injector.

angular.element('*[ng-app]').injector()

In chrome, however, you can point to target ng-app as shown below. and use the $0 hack and issue angular.element($0).injector()

Once you have the injector, get any dependency injected service as below

injector = angular.element($0).injector();
injector.get('$mdToast');

enter image description here

How to select first parent DIV using jQuery?

two of the best options are

$(this).parent("div:first")

$(this).parent().closest('div')

and of course you can find the class attr by

$(this).parent("div:first").attr("class")

$(this).parent().closest('div').attr("class")

Selecting Folder Destination in Java?

I found a good example of what you need in this link.

import javax.swing.JFileChooser;

public class Main {
  public static void main(String s[]) {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("choosertitle");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
      System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
    } else {
      System.out.println("No Selection ");
    }
  }
}

Python extract pattern matches

You could use something like this:

import re
s = #that big string
# the parenthesis create a group with what was matched
# and '\w' matches only alphanumeric charactes
p = re.compile("name +(\w+) +is valid", re.flags)
# use search(), so the match doesn't have to happen 
# at the beginning of "big string"
m = p.search(s)
# search() returns a Match object with information about what was matched
if m:
    name = m.group(1)
else:
    raise Exception('name not found')

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Unfortunately this error is not descriptive for a range of different problems related to the same issue - a binding error. It also does not specify where the error is, and so your problem is not necessarily in the execution, but the sql statement that was already 'prepared'.

These are the possible errors and their solutions:

  1. There is a parameter mismatch - the number of fields does not match the parameters that have been bound. Watch out for arrays in arrays. To double check - use var_dump($var). "print_r" doesn't necessarily show you if the index in an array is another array (if the array has one value in it), whereas var_dump will.

  2. You have tried to bind using the same binding value, for example: ":hash" and ":hash". Every index has to be unique, even if logically it makes sense to use the same for two different parts, even if it's the same value. (it's similar to a constant but more like a placeholder)

  3. If you're binding more than one value in a statement (as is often the case with an "INSERT"), you need to bindParam and then bindValue to the parameters. The process here is to bind the parameters to the fields, and then bind the values to the parameters.

    // Code snippet
    $column_names = array();
    $stmt->bindParam(':'.$i, $column_names[$i], $param_type);
    $stmt->bindValue(':'.$i, $values[$i], $param_type);
    $i++;
    //.....
    
  4. When binding values to column_names or table_names you can use `` but its not necessary, but make sure to be consistent.

  5. Any value in '' single quotes is always treated as a string and will not be read as a column/table name or placeholder to bind to.

selecting an entire row based on a variable excel vba

You need to add quotes. VBA is translating

Rows(copyToRow & ":" & copyToRow).Select`

into

 Rows(52:52).Select

Try changing

Rows(""" & copyToRow & ":" & copyToRow & """).Select

Linux shell script for database backup

You might consider this Open Source tool, matiri, https://github.com/AAFC-MBB/matiri which is a concurrent mysql backup script with metadata in Sqlite3. Features:

  • Multi-Server: Multiple MySQL servers are supported whether they are co-located on the same or separate physical servers.
  • Parallel: Each database on the server to be backed up is done separately, in parallel (concurrency settable: default: 3)
  • Compressed: Each database backup compressed
  • Checksummed: SHA256 of each compressed backup file stored and the archive of all files
  • Archived: All database backups tar'ed together into single file
  • Recorded: Backup information stored in Sqlite3 database

Full disclosure: original matiri author.

How to select/get drop down option in Selenium 2

This method will return the selected value for the drop down,

public static String getSelected_visibleText(WebDriver driver, String elementType, String value)
  {
    WebElement element = Webelement_Finder.webElement_Finder(driver, elementType, value);
   Select Selector = new Select(element);
    Selector.getFirstSelectedOption();
    String textval=Selector.getFirstSelectedOption().getText();
    return textval;
  }

Meanwhile

String textval=Selector.getFirstSelectedOption();

element.getText();

Will return all the elements in the drop down.

Difference between private, public, and protected inheritance

Accessors    | Base Class | Derived Class | World
—————————————+————————————+———————————————+———————
public       |      y     |       y       |   y
—————————————+————————————+———————————————+———————
protected    |      y     |       y       |   n
—————————————+————————————+———————————————+———————
private      |            |               |    
  or         |      y     |       n       |   n
no accessor  |            |               |

y: accessible
n: not accessible

Based on this example for java... I think a little table worth a thousand words :)