Programs & Examples On #Mission critical

Mission-Critical is a term that refers to something that is indispensable.

Globally catch exceptions in a WPF application?

AppDomain.UnhandledException Event

This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.

   public App()
   {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);    
   }

   static void MyHandler(object sender, UnhandledExceptionEventArgs args) 
   {
      Exception e = (Exception) args.ExceptionObject;
      Console.WriteLine("MyHandler caught : " + e.Message);
      Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
   }

If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.

For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. The first application domain in which the UnhandledException event can be raised is "AD1". If that application domain is not the default application domain, the event can also be raised in the default application domain.

How to retrieve records for last 30 minutes in MS SQL?

SQL Server uses Julian dates so your 30 means "30 calendar days". getdate() - 0.02083 means "30 minutes ago".

How to create a file in a directory in java?

You need to ensure that the parent directories exist before writing. You can do this by File#mkdirs().

File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...

How to check edittext's text is email address or not?

here email is your email-id.

  public boolean validateEmail(String email) {

    Pattern pattern;
    Matcher matcher;
    String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    pattern = Pattern.compile(EMAIL_PATTERN);
    matcher = pattern.matcher(email);
    return matcher.matches();

    }

"This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded"

I have a .NET 4.0 dll project that is being called by a .NET 2.0 project. Is there a way to reconcile the difference in framework?

Not that way round, no. The .NET 4 CLR can load .NET 2 assemblies (usually - there are a few exceptions for mixed-mode assemblies, IIRC), but not vice versa.

You'll either have to upgrade the .NET 2 project to .NET 4, or downgrade the .NET 4 project to .NET 3.5 (or earlier).

How to get child element by index in Jquery?

There are the following way to select first child

1) $('.second div:first-child')
2) $('.second *:first-child')
3) $('div:first-child', '.second')
4) $('*:first-child', '.second')
5) $('.second div:nth-child(1)')
6) $('.second').children().first()
7) $('.second').children().eq(0)

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

I was also facing same issue. I had Jdk1.7.0.79. Then I updated it with Jdk8.0.120. Then the problem solved. After successful completion of upgraded jdk. Go to project->clean. It will rebuild the project and all red alert will be eliminated.

How do you unit test private methods?

You could generate the test method for the private method from Visual studio 2008. When you create a unit test for a private method, a Test References folder is added to your test project and an accessor is added to that folder. The accessor is also referred to in the logic of the unit test method. This accessor allows your unit test to call private methods in the code that you are testing. For details have a look at

http://msdn.microsoft.com/en-us/library/bb385974.aspx

How to call a .NET Webservice from Android using KSOAP2?

You can Use below code to call the web service and get response .Make sure that your Web Service return the response in Data Table Format..This code help you if you using data from SQL Server database .If you you using MYSQL you need to change one thing just replace word NewDataSet from sentence obj2=(SoapObject) obj1.getProperty("NewDataSet"); by DocumentElement

private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://localhost/Web_Service.asmx?"; // you can use   IP address instead of localhost
private static final String METHOD_NAME = "Function_Name";
private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME;

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("parm_name", prm_value); // Parameter for Method
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

try {
    androidHttpTransport.call(SOAP_ACTION, envelope); //call the eb service Method
} catch (Exception e) {
    e.printStackTrace();
} //Next task is to get Response and format that response

SoapObject obj, obj1, obj2, obj3;
obj = (SoapObject) envelope.getResponse();
obj1 = (SoapObject) obj.getProperty("diffgram");
obj2 = (SoapObject) obj1.getProperty("NewDataSet");

for (int i = 0; i < obj2.getPropertyCount(); i++) //the method getPropertyCount() return the number of rows
{
    obj3 = (SoapObject) obj2.getProperty(i);
    obj3.getProperty(0).toString(); //value of column 1
    obj3.getProperty(1).toString(); //value of column 2
    //like that you will get value from each column
}

If you have any problem regarding this you can write me..

switch case statement error: case expressions must be constant expression

In a regular Android project, constants in the resource R class are declared like this:

public static final int main=0x7f030004;

However, as of ADT 14, in a library project, they will be declared like this:

public static int main=0x7f030004;

In other words, the constants are not final in a library project. Therefore your code would no longer compile.

The solution for this is simple: Convert the switch statement into an if-else statement.

public void onClick(View src)
{
    int id = src.getId();
    if (id == R.id.playbtn){
        checkwificonnection();
    } else if (id == R.id.stopbtn){
        Log.d(TAG, "onClick: stopping srvice");
        Playbutton.setImageResource(R.drawable.playbtn1);
        Playbutton.setVisibility(0); //visible
        Stopbutton.setVisibility(4); //invisible
        stopService(new Intent(RakistaRadio.this,myservice.class));
        clearstatusbar();
        timer.cancel();
        Title.setText(" ");
        Artist.setText(" ");
    } else if (id == R.id.btnmenu){
        openOptionsMenu();
    }
}

http://tools.android.com/tips/non-constant-fields

You can quickly convert a switch statement to an if-else statement using the following:

In Eclipse
Move your cursor to the switch keyword and press Ctrl + 1 then select

Convert 'switch' to 'if-else'.

In Android Studio
Move your cursor to the switch keyword and press Alt + Enter then select

Replace 'switch' with 'if'.

Depend on a branch or tag using a git URL in a package.json?

per @dantheta's comment:

As of npm 1.1.65, Github URL can be more concise user/project. npmjs.org/doc/files/package.json.html You can attach the branch like user/project#branch

So

"babel-eslint": "babel/babel-eslint",

Or for tag v1.12.0 on jscs:

"jscs": "jscs-dev/node-jscs#v1.12.0",

Note, if you use npm --save, you'll get the longer git

From https://docs.npmjs.com/cli/v6/configuring-npm/package-json#git-urls-as-dependencies

Git URLs as Dependencies

Git urls are of the form:

git+ssh://[email protected]:npm/cli.git#v1.0.27 git+ssh://[email protected]:npm/cli#semver:^5.0 git+https://[email protected]/npm/cli.git
git://github.com/npm/cli.git#v1.0.27

If #<commit-ish> is provided, it will be used to clone exactly that commit. If > the commit-ish has the format #semver:<semver>, <semver> can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither #<commit-ish> or #semver:<semver> is specified, then master is used.

GitHub URLs

As of version 1.1.65, you can refer to GitHub urls as just "foo": "user/foo-project". Just as with git URLs, a commit-ish suffix can be included. For example:

{
 "name": "foo",
 "version": "0.0.0",
 "dependencies": {
   "express": "expressjs/express",
   "mocha": "mochajs/mocha#4727d357ea",
   "module": "user/repo#feature\/branch"
 }
}```

Configure nginx with multiple locations with different root folders on subdomain

A little more elaborate example.

Setup: You have a website at example.com and you have a web app at example.com/webapp

...
server {
  listen 443 ssl;
  server_name example.com;

  root   /usr/share/nginx/html/website_dir;
  index  index.html index.htm;
  try_files $uri $uri/ /index.html;

  location /webapp/ {
    alias  /usr/share/nginx/html/webapp_dir/;
    index  index.html index.htm;
    try_files $uri $uri/ /webapp/index.html;
  }
}
...

I've named webapp_dir and website_dir on purpose. If you have matching names and folders you can use the root directive.

This setup works and is tested with Docker.

NB!!! Be careful with the slashes. Put them exactly as in the example.

Python Timezone conversion

import datetime
import pytz

def convert_datetime_timezone(dt, tz1, tz2):
    tz1 = pytz.timezone(tz1)
    tz2 = pytz.timezone(tz2)

    dt = datetime.datetime.strptime(dt,"%Y-%m-%d %H:%M:%S")
    dt = tz1.localize(dt)
    dt = dt.astimezone(tz2)
    dt = dt.strftime("%Y-%m-%d %H:%M:%S")

    return dt

-

  • dt: date time string
  • tz1: initial time zone
  • tz2: target time zone

-

> convert_datetime_timezone("2017-05-13 14:56:32", "Europe/Berlin", "PST8PDT")
'2017-05-13 05:56:32'

> convert_datetime_timezone("2017-05-13 14:56:32", "Europe/Berlin", "UTC")
'2017-05-13 12:56:32'

-

> pytz.all_timezones[0:10]
['Africa/Abidjan',
 'Africa/Accra',
 'Africa/Addis_Ababa',
 'Africa/Algiers',
 'Africa/Asmara',
 'Africa/Asmera',
 'Africa/Bamako',
 'Africa/Bangui',
 'Africa/Banjul',
 'Africa/Bissau']

Markdown to create pages and table of contents?

If you happen to use Eclipse you can use the Ctrl+O (outline) shortcut, this will show the equivalent of the table of contents and allow to search in section titles (autocomplete).

You can also open the Outline view (Window -> Show View -> Outline) but it has no autocomplete search.

Using JavaMail with TLS

As a small note, it only started to work for me when I changed smtp to smtps in the examples above per samples from javamail (see smtpsend.java, https://github.com/javaee/javamail/releases/download/JAVAMAIL-1_6_2/javamail-samples.zip, option -S).

My resulting code is as follow:

Properties props=new Properties();
props.put("mail.smtps.starttls.enable","true");
// Use the following if you need SSL
props.put("mail.smtps.socketFactory.port", port);
props.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtps.socketFactory.fallback", "false");
props.put("mail.smtps.host", serverList.get(randNum));
Session session = Session.getDefaultInstance(props);

smtpConnectionPool = new SmtpConnectionPool(
    SmtpConnectionFactories.newSmtpFactory(session));
    
final ClosableSmtpConnection transport = smtpConnectionPool.borrowObject();
...
transport.sendMessage(message, message.getAllRecipients());

creating a new list with subset of list using index in python

Try new_list = a[0:2] + [a[4]] + a[6:].

Or more generally, something like this:

from itertools import chain
new_list = list(chain(a[0:2], [a[4]], a[6:]))

This works with other sequences as well, and is likely to be faster.

Or you could do this:

def chain_elements_or_slices(*elements_or_slices):
    new_list = []
    for i in elements_or_slices:
        if isinstance(i, list):
            new_list.extend(i)
        else:
            new_list.append(i)
    return new_list

new_list = chain_elements_or_slices(a[0:2], a[4], a[6:])

But beware, this would lead to problems if some of the elements in your list were themselves lists. To solve this, either use one of the previous solutions, or replace a[4] with a[4:5] (or more generally a[n] with a[n:n+1]).

Why is a div with "display: table-cell;" not affected by margin?

You can use inner divs to set the margin.

<div style="display: table-cell;">
   <div style="margin:5px;background-color: red;">1</div>
</div>
<div style="display: table-cell; ">
  <div style="margin:5px;background-color: green;">1</div>
</div>

JS Fiddle

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • In OS X Lion, LANG is not set to UTF-8, how to fix it?

    I noticed the exact same issue when logging onto servers running Red Hat from an OSX Lion machine.

    Try adding or editing the ~/.profile file for it to correctly export your locale settings upon initiating a new session.

    export LC_ALL=en_US.UTF-8  
    export LANG=en_US.UTF-8
    

    These two lines added to the file should suffice to set the locale [replace en_US for your desired locale, and check beforehand that it is indeed installed on your system (locale -a)].

    After that, you can start a new session and check using locale:

    $ locale
    

    The following should be the output:

    LANG="en_US.UTF-8"  
    LC_COLLATE="en_US.UTF-8"  
    LC_CTYPE="en_US.UTF-8"  
    LC_MESSAGES="en_US.UTF-8"  
    LC_MONETARY="en_US.UTF-8"  
    LC_NUMERIC="en_US.UTF-8"  
    LC_TIME="en_US.UTF-8"  
    LC_ALL="en_US.UTF-8"  
    

    Setting Remote Webdriver to run tests in a remote computer using Java

    You have to install a Selenium Server (a Hub) and register your remote WebDriver to it. Then, your client will talk to the Hub which will find a matching WebDriver to execute your test.

    You can have a look at here for more information.

    JPA 2.0, Criteria API, Subqueries, In Expressions

    Late resurrection.

    Your query seems very similar to the one at page 259 of the book Pro JPA 2: Mastering the Java Persistence API, which in JPQL reads:

    SELECT e 
    FROM Employee e 
    WHERE e IN (SELECT emp
                  FROM Project p JOIN p.employees emp 
                 WHERE p.name = :project)
    

    Using EclipseLink + H2 database, I couldn't get neither the book's JPQL nor the respective criteria working. For this particular problem I have found that if you reference the id directly instead of letting the persistence provider figure it out everything works as expected:

    SELECT e 
    FROM Employee e 
    WHERE e.id IN (SELECT emp.id
                     FROM Project p JOIN p.employees emp 
                    WHERE p.name = :project)
    

    Finally, in order to address your question, here is an equivalent strongly typed criteria query that works:

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
    Root<Employee> emp = c.from(Employee.class);
    
    Subquery<Integer> sq = c.subquery(Integer.class);
    Root<Project> project = sq.from(Project.class);
    Join<Project, Employee> sqEmp = project.join(Project_.employees);
    
    sq.select(sqEmp.get(Employee_.id)).where(
            cb.equal(project.get(Project_.name), 
            cb.parameter(String.class, "project")));
    
    c.select(emp).where(
            cb.in(emp.get(Employee_.id)).value(sq));
    
    TypedQuery<Employee> q = em.createQuery(c);
    q.setParameter("project", projectName); // projectName is a String
    List<Employee> employees = q.getResultList();
    

    How to indent a few lines in Markdown markup?

    To answer MengLu and @lifebalance's questions in response to SColvin's answer (which I much prefer to the accepted answer for the control it provides), it seems as though you could just target a parent element of the lists when setting the display to none, adding a surrounding element if necessary. So if we suppose we're doing this for a table of contents, we can extend SColvin's answer:

    HTML

    <nav class="table-of-contents">
      this is a normal line of text
      * this is the first level of bullet points, made up of <space><space>*<space>
        * this is more indented, composed of <space><space><space><space>*<space>
    </nav>
    

    CSS

    .table-of-contents ul {
      list-style-type: none;
    }
    

    How to remove leading and trailing white spaces from a given html string?

    var trim = your_string.replace(/^\s+|\s+$/g, '');
    

    change image opacity using javascript

    First set the opacity explicitly in your HTML thus:

    <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px; opacity:1"></div>
    

    otherwise it is 0 or null

    this is then in my .js file

    document.getElementById("fadeButton90").addEventListener("click", function(){
    document.getElementById("box").style.opacity  =   document.getElementById("box").style.opacity*0.90; });
    

    How do I implement charts in Bootstrap?

    Definitely late to the party; anyway, for those interested, picking up on Lan's mention of HTML5 canvas, you can use gRaphaël Charting which has a MIT License (instead of HighCharts dual license). It's not Bootstrap-specific either, so it's more of a general suggestion.

    I have to admit that HighCharts demos seem very pretty, and I have to warn that gRaphaël is quite hard to understand before becoming proficient with it. Anyway you can easily add nice features to your gRaphaël charts (say, tooltips or zooming effects), so it may be worth the effort.

    Very Simple Image Slider/Slideshow with left and right button. No autoplay

    Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).

    jQuery Cycle is one of my favourite light weight libraries.

    What you want to achieve could be done in just

        jQuery("#slideshow").cycle({
        timeout:0, // no autoplay
        fx: 'fade', //fade effect, although there are heaps
        next: '#next',
        prev: '#prev'
        });
    

    JSFIDDLE TO SEE HOW EASY IT IS

    font awesome icon in select option

    I recommend for you to use Jquery plugin selectBoxIt selectBoxIt

    It is nice and simple, and you can change the arrow of drop down menu.

    How to remove word wrap from textarea?

    I found a way to make a textarea with all this working at the same time:

    • With horizontal scrollbar
    • Supporting multiline text
    • Text not wrapping

    It works well on:

    • Chrome 15.0.874.120
    • Firefox 7.0.1
    • Opera 11.52 (1100)
    • Safari 5.1 (7534.50)
    • IE 8.0.6001.18702

    Let me explain how i get to that: I was using Chrome inspector integrated tool and I saw values on CSS styles, so I try these values, instead of normal ones... trial & errors till I got it reduced to minimum and here it is for anyone that wants it.

    In the CSS section I used just this for Chrome, Firefox, Opera and Safari:

    textarea {
      white-space:nowrap;
      overflow:scroll;
    }
    

    In the CSS section I used just this for IE:

    textarea {
      overflow:scroll;
    }
    

    It was a bit tricky, but there is the CSS.

    An (x)HTML tag like this:

    <textarea id="myTextarea" rows="10" cols="15"></textarea>
    

    And at the end of the <head> section a JavaScript like this:

     window.onload=function(){
       document.getElementById("myTextarea").wrap='off';
     }
    

    The JavaScript is for making the W3C validator passing XHTML 1.1 Strict, since the wrap attribute is not official and thus cannot be an (x)HTML tag directly, but most browsers handle it, so after loading the page it sets that attribute.

    Hope this can be tested on more browsers and versions and help someone to improve it and makes it fully cross-browser for all versions.

    How to rename a table in SQL Server?

    If you try exec sp_rename and receieve a LockMatchID error then it might help to add a use [database] statement first:

    I tried

     exec sp_rename '[database_name].[dbo].[table_name]', 'new_table_name';
     -- Invalid EXECUTE statement using object "Object", method "LockMatchID".
    

    What I had to do to fix it was to rewrite it to:

    use database_name
    exec sp_rename '[dbo].[table_name]', 'new_table_name';
    

    Is there a TRY CATCH command in Bash

    Below is an example of a script which implements try/catch/finally in bash.

    Like other answers to this question, exceptions must be caught after exiting a subprocess.

    The example scripts start by creating an anonymous fifo, which is used to pass string messages from a command exception or throw to end of the closest try block. Here the messages are removed from the fifo and placed in an array variable. The status is returned through return and exit commands and placed in a different variable. To enter a catch block, this status must not be zero. Other requirements to enter a catch block are passed as parameters. If the end of a catch block is reached, then the status is set to zero. If the end of the finally block is reached and the status is still nonzero, then an implicit throw containing the messages and status is executed. The script requires the calling of the function trycatchfinally which contains an unhandled exception handler.

    The syntax for the trycatchfinally command is given below.

    trycatchfinally [-cde] [-h ERR_handler] [-k] [-o debug_file] [-u unhandled_handler] [-v variable] fifo function
    

    The -c option adds the call stack to the exception messages.
    The -d option enables debug output.
    The -e option enables command exceptions.
    The -h option allows the user to substitute their own command exception handler.
    The -k option adds the call stack to the debug output.
    The -o option replaces the default output file which is /dev/fd/2.
    The -u option allows the user to substitute their own unhandled exception handler.
    The -v option allows the user the option to pass back values though the use of Command Substitution.
    The fifo is the fifo filename.
    The function function is called by trycatchfinally as a subprocess.

    Note: The cdko options were removed to simplify the script.

    The syntax for the catch command is given below.

    catch [[-enoprt] list ...] ...
    

    The options are defined below. The value for the first list is the status. Subsquent values are the messages. If the there are more messages than lists, then the remaining messages are ignored.

    -e means [[ $value == "$string" ]] (the value has to match at least one string in the list)
    -n means [[ $value != "$string" ]] (the value can not match any of the strings in the list)
    -o means [[ $value != $pattern ]] (the value can not match any of the patterns in the list)
    -p means [[ $value == $pattern ]] (the value has to match at least one pattern in the list)
    -r means [[ $value =~ $regex ]] (the value has to match at least one extended regular expression in the list)
    -t means [[ ! $value =~ $regex ]] (the value can not match any of the extended regular expressions in the list)

    The try/catch/finally script is given below. To simplify the script for this answer, most of the error checking was removed. This reduced the size by 64%. A complete copy of this script can be found at my other answer.

    shopt -s expand_aliases
    alias try='{ common.Try'
    alias yrt='EchoExitStatus; common.yrT; }'
    alias catch='{ while common.Catch'
    alias hctac='common.hctaC; done; }'
    alias finally='{ common.Finally'
    alias yllanif='common.yllaniF; }'
    
    DefaultErrHandler() {
        echo "Orginal Status: $common_status"
        echo "Exception Type: ERR"
    }
    
    exception() {
        let "common_status = 10#$1"
        shift
        common_messages=()
        for message in "$@"; do
            common_messages+=("$message")
        done
    }
    
    throw() {
        local "message"
        if [[ $# -gt 0 ]]; then
            let "common_status = 10#$1"
            shift
            for message in "$@"; do
                echo "$message" >"$common_fifo"
            done
        elif [[ ${#common_messages[@]} -gt 0 ]]; then
            for message in "${common_messages[@]}"; do
                echo "$message" >"$common_fifo"
            done
        fi
        chmod "0400" "$common_fifo"
        exit "$common_status"
    }
    
    common.ErrHandler() {
        common_status=$?
        trap ERR
        if [[ -w "$common_fifo" ]]; then
            if [[ $common_options != *e* ]]; then
                common_status="0"
                return
            fi
            eval "${common_errHandler:-} \"${BASH_LINENO[0]}\" \"${BASH_SOURCE[1]}\" \"${FUNCNAME[1]}\" >$common_fifo <$common_fifo"
            chmod "0400" "$common_fifo"
        fi
        if [[ common_trySubshell -eq BASH_SUBSHELL ]]; then
            return   
        else
            exit "$common_status"
        fi
    }
    
    common.Try() {
        common_status="0"
        common_subshell="$common_trySubshell"
        common_trySubshell="$BASH_SUBSHELL"
        common_messages=()
    }
    
    common.yrT() {
        local "status=$?"
        if [[ common_status -ne 0 ]]; then    
            local "message=" "eof=TRY_CATCH_FINALLY_END_OF_MESSAGES_$RANDOM"
            chmod "0600" "$common_fifo"
            echo "$eof" >"$common_fifo"
            common_messages=()
            while read "message"; do
                [[ $message != *$eof ]] || break
                common_messages+=("$message")
            done <"$common_fifo"
        fi
        common_trySubshell="$common_subshell"
    }
    
    common.Catch() {
        [[ common_status -ne 0 ]] || return "1"
        local "parameter" "pattern" "value"
        local "toggle=true" "compare=p" "options=$-"
        local -i "i=-1" "status=0"
        set -f
        for parameter in "$@"; do
            if "$toggle"; then
                toggle="false"
                if [[ $parameter =~ ^-[notepr]$ ]]; then
                    compare="${parameter#-}"
                    continue 
                fi
            fi
            toggle="true"
            while "true"; do
                eval local "patterns=($parameter)"
                if [[ ${#patterns[@]} -gt 0 ]]; then
                    for pattern in "${patterns[@]}"; do
                        [[ i -lt ${#common_messages[@]} ]] || break
                        if [[ i -lt 0 ]]; then
                            value="$common_status"
                        else
                            value="${common_messages[i]}"
                        fi
                        case $compare in
                        [ne]) [[ ! $value == "$pattern" ]] || break 2;;
                        [op]) [[ ! $value == $pattern ]] || break 2;;
                        [tr]) [[ ! $value =~ $pattern ]] || break 2;;
                        esac
                    done
                fi
                if [[ $compare == [not] ]]; then
                    let "++i,1"
                    continue 2
                else
                    status="1"
                    break 2
                fi
            done
            if [[ $compare == [not] ]]; then
                status="1"
                break
            else
                let "++i,1"
            fi
        done
        [[ $options == *f* ]] || set +f
        return "$status"
    } 
    
    common.hctaC() {
        common_status="0"
    }
    
    common.Finally() {
        :
    }
    
    common.yllaniF() {
        [[ common_status -eq 0 ]] || throw
    }
    
    caught() {
        [[ common_status -eq 0 ]] || return 1
    }
    
    EchoExitStatus() {
        return "${1:-$?}"
    }
    
    EnableThrowOnError() {
        [[ $common_options == *e* ]] || common_options+="e"
    }
    
    DisableThrowOnError() {
        common_options="${common_options/e}"
    }
    
    GetStatus() {
        echo "$common_status"
    }
    
    SetStatus() {
        let "common_status = 10#$1"
    }
    
    GetMessage() {
        echo "${common_messages[$1]}"
    }
    
    MessageCount() {
        echo "${#common_messages[@]}"
    }
    
    CopyMessages() {
        if [[ ${#common_messages} -gt 0 ]]; then
            eval "$1=(\"\${common_messages[@]}\")"
        else
            eval "$1=()"
        fi
    }
    
    common.GetOptions() {
        local "opt"
        let "OPTIND = 1"
        let "OPTERR = 0"
        while getopts ":cdeh:ko:u:v:" opt "$@"; do
            case $opt in
            e)  [[ $common_options == *e* ]] || common_options+="e";;
            h)  common_errHandler="$OPTARG";;
            u)  common_unhandled="$OPTARG";;
            v)  common_command="$OPTARG";;
            esac
        done
        shift "$((OPTIND - 1))"
        common_fifo="$1"
        shift
        common_function="$1"
        chmod "0600" "$common_fifo"
    }
    
    DefaultUnhandled() {
        local -i "i"
        echo "-------------------------------------------------"
        echo "TryCatchFinally: Unhandeled exception occurred"
        echo "Status: $(GetStatus)"
        echo "Messages:"
        for ((i=0; i<$(MessageCount); i++)); do
            echo "$(GetMessage "$i")"
        done
        echo "-------------------------------------------------"
    }
    
    TryCatchFinally() {
        local "common_errHandler=DefaultErrHandler"
        local "common_unhandled=DefaultUnhandled"
        local "common_options="
        local "common_fifo="
        local "common_function="
        local "common_flags=$-"
        local "common_trySubshell=-1"
        local "common_subshell"
        local "common_status=0"
        local "common_command="
        local "common_messages=()"
        local "common_handler=$(trap -p ERR)"
        [[ -n $common_handler ]] || common_handler="trap ERR"
        common.GetOptions "$@"
        shift "$((OPTIND + 1))"
        [[ -z $common_command ]] || common_command+="=$"
        common_command+='("$common_function" "$@")'
        set -E
        set +e
        trap "common.ErrHandler" ERR
        try
            eval "$common_command"
        yrt
        catch; do
            "$common_unhandled" >&2
        hctac
        [[ $common_flags == *E* ]] || set +E
        [[ $common_flags != *e* ]] || set -e
        [[ $common_flags != *f* || $- == *f* ]] || set -f
        [[ $common_flags == *f* || $- != *f* ]] || set +f
        eval "$common_handler"
    }
    

    Below is an example, which assumes the above script is stored in the file named simple. The makefifo file contains the script described in this answer. The assumption is made that the file named 4444kkkkk does not exist, therefore causing an exception to occur. The error message output from the ls 4444kkkkk command is automatically suppressed until inside the appropriate catch block.

    #!/bin/bash
    #
    
    if [[ $0 != ${BASH_SOURCE[0]} ]]; then
        bash "${BASH_SOURCE[0]}" "$@"
        return
    fi
    
    source simple
    source makefifo
    
    MyFunction3() {
        echo "entered MyFunction3" >&4
        echo "This is from MyFunction3"
        ls 4444kkkkk
        echo "leaving MyFunction3" >&4
    }
    
    MyFunction2() {
        echo "entered MyFunction2" >&4
        value="$(MyFunction3)"
        echo "leaving MyFunction2" >&4
    }
    
    MyFunction1() {
        echo "entered MyFunction1" >&4
        local "flag=false"
        try 
        (
            echo "start of try" >&4
            MyFunction2
            echo "end of try" >&4
        )
        yrt
        catch "[1-3]" "*" "Exception\ Type:\ ERR"; do
            echo 'start of catch "[1-3]" "*" "Exception\ Type:\ ERR"'
            local -i "i"
            echo "-------------------------------------------------"
            echo "Status: $(GetStatus)"
            echo "Messages:"
            for ((i=0; i<$(MessageCount); i++)); do
                echo "$(GetMessage "$i")"
            done
            echo "-------------------------------------------------"
            break
            echo 'end of catch "[1-3]" "*" "Exception\ Type:\ ERR"'
        hctac >&4
        catch "1 3 5" "*" -n "Exception\ Type:\ ERR"; do
            echo 'start of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"'
            echo "-------------------------------------------------"
            echo "Status: $(GetStatus)"
            [[ $(MessageCount) -le 1 ]] || echo "$(GetMessage "1")"
            echo "-------------------------------------------------"
            break
            echo 'end of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"'
        hctac >&4
        catch; do
            echo 'start of catch' >&4
            echo "failure"
            flag="true"
            echo 'end of catch' >&4
        hctac
        finally
            echo "in finally"
        yllanif >&4
        "$flag" || echo "success"
        echo "leaving MyFunction1" >&4
    } 2>&6
    
    ErrHandler() {
        echo "EOF"
        DefaultErrHandler "$@"
        echo "Function: $3"
        while read; do
            [[ $REPLY != *EOF ]] || break
            echo "$REPLY"
        done
    }
    
    set -u
    echo "starting" >&2
    MakeFIFO "6"
    TryCatchFinally -e -h ErrHandler -o /dev/fd/4 -v result /dev/fd/6 MyFunction1 4>&2
    echo "result=$result"
    exec >&6-
    

    The above script was tested using GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin17). The output, from running this script, is shown below.

    starting
    entered MyFunction1
    start of try
    entered MyFunction2
    entered MyFunction3
    start of catch "[1-3]" "*" "Exception\ Type:\ ERR"
    -------------------------------------------------
    Status: 1
    Messages:
    Orginal Status: 1
    Exception Type: ERR
    Function: MyFunction3
    ls: 4444kkkkk: No such file or directory
    -------------------------------------------------
    start of catch
    end of catch
    in finally
    leaving MyFunction1
    result=failure
    

    Another example which uses a throw can be created by replacing function MyFunction3 with the script shown below.

    MyFunction3() {
        echo "entered MyFunction3" >&4
        echo "This is from MyFunction3"
        throw "3" "Orginal Status: 3" "Exception Type: throw"
        echo "leaving MyFunction3" >&4
    }
    

    The syntax for the throw command is given below. If no parameters are present, then status and messages stored in the variables are used instead.

    throw [status] [message ...]
    

    The output, from executing the modified script, is shown below.

    starting
    entered MyFunction1
    start of try
    entered MyFunction2
    entered MyFunction3
    start of catch "1 3 5" "*" -n "Exception\ Type:\ ERR"
    -------------------------------------------------
    Status: 3
    Exception Type: throw
    -------------------------------------------------
    start of catch
    end of catch
    in finally
    leaving MyFunction1
    result=failure
    

    How to get the Android device's primary e-mail address

    public String getUsername() {
        AccountManager manager = AccountManager.get(this);
        Account[] accounts = manager.getAccountsByType("com.google");
        List<String> possibleEmails = new LinkedList<String>();
    
        for (Account account : accounts) {
            // TODO: Check possibleEmail against an email regex or treat
            // account.name as an email address only for certain account.type values.
            possibleEmails.add(account.name);
        }
    
        if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
            String email = possibleEmails.get(0);
            String[] parts = email.split("@");
    
            if (parts.length > 1)
                return parts[0];
        }
        return null;
    }
    

    How to fix Python indentation

    Using Vim, it shouldn't be more involved than hitting Esc, and then typing...

    :%s/\t/    /g
    

    ...on the file you want to change. That will convert all tabs to four spaces. If you have inconsistent spacing as well, then that will be more difficult.

    Using Git, show all commits that are in one branch, but not the other(s)

    Just use git cherry to pick all commits in the branch newFeature42 for example:

    git cherry -v master newFeature42

    socket.error: [Errno 48] Address already in use

    By the way, to prevent this from happening in the first place, simply press Ctrl+C in terminal while SimpleHTTPServer is still running normally. This will "properly" stop the server and release the port so you don't have to find and kill the process again before restarting the server.

    (Mods: I did try to put this comment on the best answer where it belongs, but I don't have enough reputation.)

    Python using enumerate inside list comprehension

    Be explicit about the tuples.

    [(i, j) for (i, j) in enumerate(mylist)]
    

    How to use OKHTTP to make a post request?

    Here is my method to do post request first pass in method map and data like

    HashMap<String, String> param = new HashMap<String, String>();
    
    param.put("Name", name);
    param.put("Email", email);
    param.put("Password", password);
    param.put("Img_Name", "");
    
    final JSONObject result = doPostRequest(map,Url);
    
    public static JSONObject doPostRequest(HashMap<String, String> data, String url) {
    
        try {
            RequestBody requestBody;
            MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
    
            if (data != null) {
    
    
                for (String key : data.keySet()) {
                    String value = data.get(key);
                    Utility.printLog("Key Values", key + "-----------------" + value);
    
                    mBuilder.addFormDataPart(key, value);
    
                }
            } else {
                mBuilder.addFormDataPart("temp", "temp");
            }
            requestBody = mBuilder.build();
    
    
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
    
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            String responseBody = response.body().string();
            Utility.printLog("URL", url);
            Utility.printLog("Response", responseBody);
            return new JSONObject(responseBody);
    
        } catch (UnknownHostException | UnsupportedEncodingException e) {
    
            JSONObject jsonObject=new JSONObject();
    
            try {
                jsonObject.put("status","false");
                jsonObject.put("message",e.getLocalizedMessage());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            Log.e(TAG, "Error: " + e.getLocalizedMessage());
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject jsonObject=new JSONObject();
    
            try {
                jsonObject.put("status","false");
                jsonObject.put("message",e.getLocalizedMessage());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
        }
        return null;
    }
    

    Java: convert seconds to minutes, hours and days

    You can use the Java enum TimeUnit to perform your math and avoid any hard coded values. Then we can use String.format(String, Object...) and a pair of StringBuilder(s) as well as a DecimalFormat to build the requested output. Something like,

    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter a number of seconds:");
    String str = scanner.nextLine().replace("\\,", "").trim();
    long secondsIn = Long.parseLong(str);
    long dayCount = TimeUnit.SECONDS.toDays(secondsIn);
    long secondsCount = secondsIn - TimeUnit.DAYS.toSeconds(dayCount);
    long hourCount = TimeUnit.SECONDS.toHours(secondsCount);
    secondsCount -= TimeUnit.HOURS.toSeconds(hourCount);
    long minutesCount = TimeUnit.SECONDS.toMinutes(secondsCount);
    secondsCount -= TimeUnit.MINUTES.toSeconds(minutesCount);
    StringBuilder sb = new StringBuilder();
    sb.append(String.format("%d %s, ", dayCount, (dayCount == 1) ? "day"
            : "days"));
    StringBuilder sb2 = new StringBuilder();
    sb2.append(sb.toString());
    sb2.append(String.format("%02d:%02d:%02d %s", hourCount, minutesCount,
            secondsCount, (hourCount == 1) ? "hour" : "hours"));
    sb.append(String.format("%d %s, ", hourCount, (hourCount == 1) ? "hour"
            : "hours"));
    sb.append(String.format("%d %s and ", minutesCount,
            (minutesCount == 1) ? "minute" : "minutes"));
    sb.append(String.format("%d %s.", secondsCount,
            (secondsCount == 1) ? "second" : "seconds"));
    System.out.printf("You entered %s seconds, which is %s (%s)%n",
            new DecimalFormat("#,###").format(secondsIn), sb, sb2);
    

    Which, when I enter 500000 outputs the requested (manual line break added for post) -

    You entered 500,000 seconds, which is 5 days, 18 hours, 
    53 minutes and 20 seconds. (5 days, 18:53:20 hours)
    

    Confirm postback OnClientClick button ASP.NET

    The code is like this:

    In Aspx:

    <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" CausesValidation=true />
    

    in Cs:

    protected void Page_Load(object sender, System.EventArgs e)
    {
         if (!IsPostBack)
         {
             btnSave.Attributes["Onclick"] = "return confirm('Do you really want to save?')";          
         }
    }
    
    protected void btnSave_Click(object sender, EventArgs e){
        Page.Validate();
        if (Page.IsValid)
        {
           //Update the database
             lblMessage.Text = "Saved Successfully";
        }
    }
    

    Improving bulk insert performance in Entity framework

    There are two major performance issues with your code:

    • Using Add method
    • Using SaveChanges

    Using Add method

    The Add method becomes only slower and slower at each entity you add.

    See: http://entityframework.net/improve-ef-add-performance

    For example, adding 10,000 entities via:

    • Add (take ~105,000ms)
    • AddRange (take ~120ms)

    Note: Entities has not been saved yet in the database!

    The problem is that the Add method tries to DetectChanges at every entity added while AddRange does it once after all entities have been added to the context.

    Common solutions are:

    • Use AddRange over Add
    • SET AutoDetectChanges to false
    • SPLIT SaveChanges in multiple batches

    Using SaveChanges

    Entity Framework has not been created for Bulk Operations. For every entity you save, a database round-trip is performed.

    So, if you want to insert 20,000 records, you will perform 20,000 database round-trip which is INSANE!

    There are some third-party libraries supporting Bulk Insert available:

    • Z.EntityFramework.Extensions (Recommended)
    • EFUtilities
    • EntityFramework.BulkInsert

    See: Entity Framework Bulk Insert library

    Be careful, when choosing a bulk insert library. Only Entity Framework Extensions support all kind of associations and inheritance, and it's the only one still supported.


    Disclaimer: I'm the owner of Entity Framework Extensions

    This library allows you to perform all bulk operations you need for your scenarios:

    • Bulk SaveChanges
    • Bulk Insert
    • Bulk Delete
    • Bulk Update
    • Bulk Merge

    Example

    // Easy to use
    context.BulkSaveChanges();
    
    // Easy to customize
    context.BulkSaveChanges(bulk => bulk.BatchSize = 100);
    
    // Perform Bulk Operations
    context.BulkDelete(customers);
    context.BulkInsert(customers);
    context.BulkUpdate(customers);
    
    // Customize Primary Key
    context.BulkMerge(customers, operation => {
       operation.ColumnPrimaryKeyExpression = 
            customer => customer.Code;
    });
    

    EDIT: Answer Question in Comment

    Is there a recommend max size for each bulk insert for the library you created

    Not too high, not too low. There isn't a particular value that fit in all scenarios since it depends on multiple factors such as row size, index, trigger, etc.

    It's normally recommended to be around 4000.

    Also is there a way to tie it all in one transaction and not worry about it timing out

    You can use Entity Framework transaction. Our library uses the transaction if one is started. But be careful, a transaction that takes too much time come also with problems such as some row/index/table lock.

    What does numpy.random.seed(0) do?

    I have used this very often in neural networks. It is well known that when we start training a neural network we randomly initialise the weights. The model is trained on these weights on a particular dataset. After number of epochs you get trained set of weights.

    Now suppose you want to again train from scratch or you want to pass the model to others to reproduce your results, the weights will be again initialised to a random numbers which mostly will be different from earlier ones. The obtained trained weights after same number of epochs ( keeping same data and other parameters ) as earlier one will differ. The problem is your model is no more reproducible that is every time you train your model from scratch it provides you different sets of weights. This is because the model is being initialized by different random numbers every time.

    What if every time you start training from scratch the model is initialised to the same set of random initialise weights? In this case your model could become reproducible. This is achieved by numpy.random.seed(0). By mentioning seed() to a particular number, you are hanging on to same set of random numbers always.

    Typing Greek letters etc. in Python plots

    Python 3.x: small greek letters are coded from 945 to 969 so,alpha is chr(945), omega is chr(969) so just type

    print(chr(945))
    

    the list of small greek letters in a list:

    greek_letterz=[chr(code) for code in range(945,970)]
    
    print(greek_letterz)
    

    And now, alpha is greek_letterz[0], beta is greek_letterz[1], a.s.o

    How to obtain Telegram chat_id for a specific user?

    The message updates you receive via getUpdates or your webhook will contain the chat ID for the specific message. It will be contained under the message.chat.id key.

    This seems like the only way you are able to retrieve the chat ID. So if you want to write something where the bot initiates the conversation you will probably have to store the chat ID in relation to the user in some sort of key->value store like MemCache or Redis.

    I believe their documentation suggests something similar here, https://core.telegram.org/bots#deep-linking-example. You can use deep-linking to initiate a conversation without requiring the user to type a message first.

    Does "\d" in regex mean a digit?

    This is just a guess, but I think your editor actually matches every single digit — 1 2 3 — but only odd matches are highlighted, to distinguish it from the case when the whole 123 string is matched.

    Most regex consoles highlight contiguous matches with different colors, but due to the plugin settings, terminal limitations or for some other reason, only every other group might be highlighted in your case.

    Can gcc output C code after preprocessing?

    Suppose we have a file as Message.cpp or a .c file

    Steps 1: Preprocessing (Argument -E )

    g++ -E .\Message.cpp > P1

    P1 file generated has expanded macros and header file contents and comments are stripped off.

    Step 2: Translate Preprocessed file to assembly (Argument -S). This task is done by compiler

    g++ -S .\Message.cpp

    An assembler (ASM) is generated (Message.s). It has all the assembly code.

    Step 3: Translate assembly code to Object code. Note: Message.s was generated in Step2. g++ -c .\Message.s

    An Object file with the name Message.o is generated. It is the binary form.

    Step 4: Linking the object file. This task is done by linker

    g++ .\Message.o -o MessageApp

    An exe file MessageApp.exe is generated here.

    #include <iostream>
    using namespace std;
    
     //This a sample program
      int main()
    {
    cout << "Hello" << endl;
     cout << PQR(P,K) ;
    getchar();
    return 0;
    }
    

    Convert a file path to Uri in Android

    Please try the following code

    Uri.fromFile(new File("/sdcard/sample.jpg"))
    

    Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

    Because I always struggle to remember, a quick summary of what each of these do:

    >>> pd.Timestamp.now()  # naive local time
    Timestamp('2019-10-07 10:30:19.428748')
    
    >>> pd.Timestamp.utcnow()  # tz aware UTC
    Timestamp('2019-10-07 08:30:19.428748+0000', tz='UTC')
    
    >>> pd.Timestamp.now(tz='Europe/Brussels')  # tz aware local time
    Timestamp('2019-10-07 10:30:19.428748+0200', tz='Europe/Brussels')
    
    >>> pd.Timestamp.now(tz='Europe/Brussels').tz_localize(None)  # naive local time
    Timestamp('2019-10-07 10:30:19.428748')
    
    >>> pd.Timestamp.now(tz='Europe/Brussels').tz_convert(None)  # naive UTC
    Timestamp('2019-10-07 08:30:19.428748')
    
    >>> pd.Timestamp.utcnow().tz_localize(None)  # naive UTC
    Timestamp('2019-10-07 08:30:19.428748')
    
    >>> pd.Timestamp.utcnow().tz_convert(None)  # naive UTC
    Timestamp('2019-10-07 08:30:19.428748')
    

    Easy way to prevent Heroku idling?

    It says in Heroku documentation that having more than 1 web dyno will never idle out. Possibly a cheaper solution than $0.09/hour like Pierre suggests.

    enter image description here

    Documentation

    How to change text color and console color in code::blocks?

    You should define the function textcolor before. Because textcolor is not a standard function in C.

    void textcolor(unsigned short color) {
        HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
        SetConsoleTextAttribute(hcon,color);
    }
    

    What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

    Most of the answers provided here address the number of incoming requests to your backend webservice, not the number of outgoing requests you can make from your ASP.net application to your backend service.

    It's not your backend webservice that is throttling your request rate here, it is the number of open connections your calling application is willing to establish to the same endpoint (same URL).

    You can remove this limitation by adding the following configuration section to your machine.config file:

    <configuration>
      <system.net>
        <connectionManagement>
          <add address="*" maxconnection="65535"/>
        </connectionManagement>
      </system.net>
    </configuration>
    

    You could of course pick a more reasonable number if you'd like such as 50 or 100 concurrent connections. But the above will open it right up to max. You can also specify a specific address for the open limit rule above rather than the '*' which indicates all addresses.

    MSDN Documentation for System.Net.connectionManagement

    Another Great Resource for understanding ConnectManagement in .NET

    Hope this solves your problem!

    EDIT: Oops, I do see you have the connection management mentioned in your code above. I will leave my above info as it is relevant for future enquirers with the same problem. However, please note there are currently 4 different machine.config files on most up to date servers!

    There is .NET Framework v2 running under both 32-bit and 64-bit as well as .NET Framework v4 also running under both 32-bit and 64-bit. Depending on your chosen settings for your application pool you could be using any one of these 4 different machine.config files! Please check all 4 machine.config files typically located here:

    • C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG
    • C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG
    • C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config
    • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config

    How to show empty data message in Datatables

    It is worth noting that if you are returning server side data - you must supply the Data attribute even if there isn't any. It doesn't read the recordsTotal or recordsFiltered but relies on the count of the data object

    'react-scripts' is not recognized as an internal or external command

    Running these commands worked for me:

    npm cache clean --force
    npm rebuild
    npm install
    

    How do I prevent site scraping?

    There are a few things you can do to try and prevent screen scraping. Some are not very effective, while others (a CAPTCHA) are, but hinder usability. You have to keep in mind too that it may hinder legitimate site scrapers, such as search engine indexes.

    However, I assume that if you don't want it scraped that means you don't want search engines to index it either.

    Here are some things you can try:

    • Show the text in an image. This is quite reliable, and is less of a pain on the user than a CAPTCHA, but means they won't be able to cut and paste and it won't scale prettily or be accessible.
    • Use a CAPTCHA and require it to be completed before returning the page. This is a reliable method, but also the biggest pain to impose on a user.
    • Require the user to sign up for an account before viewing the pages, and confirm their email address. This will be pretty effective, but not totally - a screen-scraper might set up an account and might cleverly program their script to log in for them.
    • If the client's user-agent string is empty, block access. A site-scraping script will often be lazily programmed and won't set a user-agent string, whereas all web browsers will.
    • You can set up a black list of known screen scraper user-agent strings as you discover them. Again, this will only help the lazily-coded ones; a programmer who knows what he's doing can set a user-agent string to impersonate a web browser.
    • Change the URL path often. When you change it, make sure the old one keeps working, but only for as long as one user is likely to have their browser open. Make it hard to predict what the new URL path will be. This will make it difficult for scripts to grab it if their URL is hard-coded. It'd be best to do this with some kind of script.

    If I had to do this, I'd probably use a combination of the last three, because they minimise the inconvenience to legitimate users. However, you'd have to accept that you won't be able to block everyone this way and once someone figures out how to get around it, they'll be able to scrape it forever. You could then just try to block their IP addresses as you discover them I guess.

    How do you add an action to a button programmatically in xcode

    Try this:

    Swift 4

    myButton.addTarget(self,
                       action: #selector(myAction),
                       for: .touchUpInside)
    

    Objective-C

    [myButton addTarget:self 
                 action:@selector(myAction) 
       forControlEvents:UIControlEventTouchUpInside];
    

    You can find a rich source of information in Apple's Documentation. Have a look at the UIButton's documentation, it will reveal that UIButton is a descendant of UIControl, which implements the method to add targets.

    --

    You'll need to pay attention to whether add colon or not after myAction in action:@selector(myAction)

    Here's the reference.

    Using File.listFiles with FileNameExtensionFilter

    Duh.... listFiles requires java.io.FileFilter. FileNameExtensionFilter extends javax.swing.filechooser.FileFilter. I solved my problem by implementing an instance of java.io.FileFilter

    Edit: I did use something similar to @cFreiner's answer. I was trying to use a Java API method instead of writing my own implementation which is why I was trying to use FileNameExtensionFilter. I have many FileChoosers in my application and have used FileNameExtensionFilters for that and I mistakenly assumed that it was also extending java.io.FileFilter.

    putting datepicker() on dynamically created elements - JQuery/JQueryUI

    The new method for dynamic elements is MutationsObserver .. The following example uses underscore.js to use ( _.each ) function.

    MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;    
    
    var observerjQueryPlugins = new MutationObserver(function (repeaterWrapper) {
    
        _.each(repeaterWrapper, function (repeaterItem, index) {
    
            var jq_nodes = $(repeaterItem.addedNodes);
    
            jq_nodes.each(function () {
    
                // Date Picker
                $(this).parents('.current-repeateritem-container').find('.element-datepicker').datepicker({
                    dateFormat: "dd MM, yy",
                    showAnim: "slideDown",
                    changeMonth: true,
                    numberOfMonths: 1
                });
    
            });
    
        });
    
    });
    
    observerjQueryPlugins.observe(document, {
        childList: true,
        subtree: true,
        attributes: false,
        characterData: false
    });
    

    HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

    Just remove the inner quotes - they confuse Firefox. You can just use "video/ogg; codecs=theora,vorbis".

    Also, that markup works in my Minefiled 3.7a5pre, so if your ogv file doesn't play, it may be a bogus file. How did you create it? You might want to register a bug with Firefox.

    How to enter newline character in Oracle?

    begin   
       dbms_output.put_line( 'hello' ||chr(13) || chr(10) || 'world' );
    end;
    

    Cause of a process being a deadlock victim

    Although @Remus Rusanu's is already an excelent answer, in case one is looking forward a better insight on SQL Server's Deadlock causes and trace strategies, I would suggest you to read Brad McGehee's How to Track Down Deadlocks Using SQL Server 2005 Profiler

    Link a photo with the cell in excel

    Hold down the Alt key and drag the pictures to snap to the upper left corner of the cell.

    Format the picture and in the Properties tab select "Move but don't size with cells"

    Now you can sort the data table by any column and the pictures will stay with the respective data.

    This post at SuperUser has a bit more background and screenshots: https://superuser.com/questions/712622/put-an-equation-object-in-an-excel-cell/712627#712627

    How to set an HTTP proxy in Python 2.7?

    cd C:\Python34\Scripts
    
    set HTTP_PROXY= DOMAIN\User_Name:Passw0rd123@PROXY_SERVER_NAME_OR_IP:PORT#
    
    set HTTP_PROXY= DOMAIN\User_Name:Passw0rd123@PROXY_SERVER_NAME_OR_IP:PORT#
    
    pip.exe install PackageName
    

    Closing Application with Exit button

    this.close_Button = (Button)this.findViewById(R.id.close);
       this.close_Button.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View v) {
            finish();
         }
      });
    

    finish() - Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().

    Limit Get-ChildItem recursion depth

    I tried to limit Get-ChildItem recursion depth using Resolve-Path

    $PATH = "."
    $folder = get-item $PATH 
    $FolderFullName = $Folder.FullName
    $PATHs = Resolve-Path $FolderFullName\*\*\*\
    $Folders = $PATHs | get-item | where {$_.PsIsContainer}
    

    But this works fine :

    gci "$PATH\*\*\*\*"
    

    Escaping single quotes in JavaScript string for JavaScript evaluation

    There are two ways to escaping the single quote in JavaScript.

    1- Use double-quote or backticks to enclose the string.

    Example: "fsdsd'4565sd" or `fsdsd'4565sd`.

    2- Use backslash before any special character, In our case is the single quote

    Example:strInputString = strInputString.replace(/ ' /g, " \\' ");

    Note: use a double backslash.

    Both methods work for me.

    Using jQuery To Get Size of Viewport

    You can try viewport units (CSS3):

    div { 
      height: 95vh; 
      width: 95vw; 
    }
    

    Browser support

    sql primary key and index

    a PK will become a clustered index unless you specify non clustered

    Best way to format multiple 'or' conditions in an if statement (Java)

    With Java 8, you could use a primitive stream:

    if (IntStream.of(12, 16, 19).anyMatch(i -> i == x))
    

    but this may have a slight overhead (or not), depending on the number of comparisons.

    Applying styles to tables with Twitter Bootstrap

    Just another good looking table. I added "table-hover" class because it gives a nice hovering effect.

       <h3>NATO Phonetic Alphabet</h3>    
       <table class="table table-striped table-bordered table-condensed table-hover">
       <thead>
        <tr> 
            <th>Letter</th>
            <th>Phonetic Letter</th>
    
        </tr>
        </thead>
      <tr>
        <th>A</th>
        <th>Alpha</th>
    
      </tr>
      <tr>
        <td>B</td>
        <td>Bravo</td>
    
      </tr>
      <tr>
        <td>C</td>
        <td>Charlie</td>
    
      </tr>
    
    </table>
    

    HTML5 Email input pattern attribute

    In HTML5 you can use the new 'email' type: http://www.w3.org/TR/html-markup/input.email.html

    For example:

    <input type="email" id="email" />
    

    If the browser implements HTML5 it will make sure that the user has entered a valid email address in the field. Note that if the browser doesn't implement HTML5, it will be treated like a 'text' type, ie:

    <input type="text" id="email" />
    

    How to embed a YouTube channel into a webpage

    In order to embed your channel, all you need to do is copy then paste the following code in another web-page.

    <script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=YourChannelName&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>
    

    Make sure to replace the YourChannelName with your actual channel name.

    For example: if your channel name were CaliChick94066 your channel embed code would be:

    <script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=CaliChick94066&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>
    

    Please look at the following links:

    YouTube on your site

    Embed YouTube Channel

    You just have to name the URL to your channel name. Also you can play with the height and the border color and size. Hope it helps

    ASP.NET MVC How to pass JSON object from View to Controller as Parameter

    in response to Dan's comment above:

    I am using this method to implement the same thing, but for some reason I am getting an exception on the ReadObject method: "Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''." Any ideas why? – Dan Appleyard Apr 6 '10 at 17:57

    I had the same problem (MVC 3 build 3.0.11209.0), and the post below solved it for me. Basically the json serializer is trying to read a stream which is not at the beginning, so repositioning the stream to 0 'fixed' it...

    http://nali.org/asp-net-mvc-expecting-element-root-from-namespace-encountered-none-with-name-namespace/

    react change class name on state change

    Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

    Explanation

    Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

    In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

    Example

    _x000D_
    _x000D_
    class Container extends React.Component {_x000D_
      state = {_x000D_
        activeIndex: null_x000D_
      }_x000D_
    _x000D_
      handleClick = (index) => this.setState({ activeIndex: index })_x000D_
    _x000D_
      render() {_x000D_
        return <div>_x000D_
          <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
          <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
          <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
        </div>_x000D_
      }_x000D_
    }_x000D_
    _x000D_
    class MyClickable extends React.Component {_x000D_
      handleClick = () => this.props.onClick(this.props.index)_x000D_
      _x000D_
      render() {_x000D_
        return <button_x000D_
          type='button'_x000D_
          className={_x000D_
            this.props.isActive ? 'active' : 'album'_x000D_
          }_x000D_
          onClick={ this.handleClick }_x000D_
        >_x000D_
          <span>{ this.props.name }</span>_x000D_
        </button>_x000D_
      }_x000D_
    }_x000D_
    _x000D_
    ReactDOM.render(<Container />, document.getElementById('app'))
    _x000D_
    button {_x000D_
      display: block;_x000D_
      margin-bottom: 1em;_x000D_
    }_x000D_
    _x000D_
    .album>span:after {_x000D_
      content: ' (an album)';_x000D_
    }_x000D_
    _x000D_
    .active {_x000D_
      font-weight: bold;_x000D_
    }_x000D_
    _x000D_
    .active>span:after {_x000D_
      content: ' ACTIVE';_x000D_
    }
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
    <div id="app"></div>
    _x000D_
    _x000D_
    _x000D_

    Update: "Loops"

    In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

    // New render method for `Container`
    render() {
      const clickables = [
        { name: "a" },
        { name: "b" },
        { name: "c" },
      ]
    
      return <div>
          { clickables.map(function(clickable, i) {
              return <MyClickable key={ clickable.name }
                name={ clickable.name }
                index={ i }
                isActive={ this.state.activeIndex === i }
                onClick={ this.handleClick }
              />
            } )
          }
      </div>
    }
    

    docker : invalid reference format

    This also happens when you use development docker compose like the below, in production. You don't want to be building images in production as that breaks the ideology of containers. We should be deploying images:

      web:
        build: .
        command: python manage.py runserver 0.0.0.0:8000
        volumes:
          - .:/code
        ports:
          - "8000:8000"
    

    Change that to use the built image:

      web:
        command: /bin/bash run.sh
        image: registry.voxcloud.co.za:9000/dyndns_api_web:0.1
        ports:
          - "8000:8000"
    

    Is Unit Testing worth the effort?

    From my experience, unit tests and integration tests are a "MUST HAVE" in complex software environments.

    In order to convince the developers in your team to write unit tests you may want to consider integrating unit test regression analysis in your development environment (for example, in your daily build process).

    Once developers know that if a unit test fails they don't have to spend so much time on debugging it to find the problem, they would be more encouraged to write them.

    Here's a tool which provides such functionality:

    unit test regression analysis tool

    How to cast ArrayList<> from List<>

    The first approach is trying to cast the list but this would work only if the List<> were an ArrayList<>. That is not the case. So you need the second approach, that is building a new ArrayList<> with the elements of the List<>

    How to populate/instantiate a C# array with a single value?

    For large arrays or arrays that will be variable sized you should probably use:

    Enumerable.Repeat(true, 1000000).ToArray();
    

    For small array you can use the collection initialization syntax in C# 3:

    bool[] vals = new bool[]{ false, false, false, false, false, false, false };
    

    The benefit of the collection initialization syntax, is that you don't have to use the same value in each slot and you can use expressions or functions to initialize a slot. Also, I think you avoid the cost of initializing the array slot to the default value. So, for example:

    bool[] vals = new bool[]{ false, true, false, !(a ||b) && c, SomeBoolMethod() };
    

    Check if a value exists in ArrayList

    Please refer to my answer on this post.

    There is no need to iterate over the List just overwrite the equals method.

    Use equals instead of ==

    @Override
    public boolean equals (Object object) {
        boolean result = false;
        if (object == null || object.getClass() != getClass()) {
            result = false;
        } else {
            EmployeeModel employee = (EmployeeModel) object;
            if (this.name.equals(employee.getName()) && this.designation.equals(employee.getDesignation())   && this.age == employee.getAge()) {
                result = true;
            }
        }
        return result;
    }
    

    Call it like this:

    public static void main(String args[]) {
    
        EmployeeModel first = new EmployeeModel("Sameer", "Developer", 25);
        EmployeeModel second = new EmployeeModel("Jon", "Manager", 30);
        EmployeeModel third = new EmployeeModel("Priyanka", "Tester", 24);
    
        List<EmployeeModel> employeeList = new ArrayList<EmployeeModel>();
        employeeList.add(first);
        employeeList.add(second);
        employeeList.add(third);
    
        EmployeeModel checkUserOne = new EmployeeModel("Sameer", "Developer", 25);
        System.out.println("Check checkUserOne is in list or not");
        System.out.println("Is checkUserOne Preasent = ? " + employeeList.contains(checkUserOne));
    
        EmployeeModel checkUserTwo = new EmployeeModel("Tim", "Tester", 24);
        System.out.println("Check checkUserTwo is in list or not");
        System.out.println("Is checkUserTwo Preasent = ? " + employeeList.contains(checkUserTwo));
    
    }
    

    Difference between using "chmod a+x" and "chmod 755"

    Indeed there is.

    chmod a+x is relative to the current state and just sets the x flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.

    chmod 755, however, sets the mask as written: rwxr-xr-x, no matter how it was before. It is equivalent to chmod u=rwx,go=rx.

    How to use type: "POST" in jsonp ajax call

    Use json in dataType and send like this:

        $.ajax({
            url: "your url which return json",
            type: "POST",
            crossDomain: true,
            data: data,
            dataType: "json",
            success:function(result){
                alert(JSON.stringify(result));
            },
            error:function(xhr,status,error){
                alert(status);
            }
        });
    

    and put this lines in your server side file:

    if PHP:

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Max-Age: 1000');
    

    if java:

    response.addHeader( "Access-Control-Allow-Origin", "*" ); 
    response.addHeader( "Access-Control-Allow-Methods", "POST" ); 
    response.addHeader( "Access-Control-Max-Age", "1000" );
    

    import httplib ImportError: No module named httplib

    If you use PyCharm, please change you 'Project Interpreter' to '2.7.x'

    enter image description here

    Adding elements to object

    cart.push({"element":{ id: id, quantity: quantity }});
    

    Get all unique values in a JavaScript array (remove duplicates)

    I have a solution that uses es6 reduce and find array helper methods to remove duplicates.

    _x000D_
    _x000D_
    let numbers = [2, 2, 3, 3, 5, 6, 6];_x000D_
    _x000D_
    const removeDups = array => {_x000D_
      return array.reduce((acc, inc) => {_x000D_
        if (!acc.find(i => i === inc)) {_x000D_
          acc.push(inc);_x000D_
        }_x000D_
        return acc;_x000D_
      }, []);_x000D_
    }_x000D_
    _x000D_
    console.log(removeDups(numbers)); /// [2,3,5,6]
    _x000D_
    _x000D_
    _x000D_

    nvarchar(max) vs NText

    I want to add that you can use the .WRITE clause for partial or full updates and high performance appends to varchar(max)/nvarchar(max) data types.

    Here you can found full example of using .WRITE clause.

    expand/collapse table rows with JQuery

    I expanded one of the answers, however my functionality is a bit different. In my version, different rows form different groups. And "header" row triggers collapsing/expanding of that particular group. Also, each individual subgroup memorizes state that its in. It might sound a bit confusing, you can test drive my version using jsfiddle. Hope this code snippets will be helpful to someone out there!

    HTML

    <table border="0">
      <tr>
          <th>Header 1</th>
          <th>Header 2</th>
      </tr>
      <tr>
        <td class='group1'>Group 1</td>
        <td>data 2</td>
      </tr>
      <tr class='group1'>
        <td>data 3</td>
        <td>data 4</td>
      </tr>
      <tr>
        <td class='group2'>Group 2</td>
        <td>data 2</td>
      </tr>
      <tr class='group2'>
        <td>data 3</td>
        <td>data 4</td>
      </tr>
      <tr class='group2'>
        <td class='sub_group1'>Sub Group 1</td>
        <td>data 6</td>
      </tr>
      <tr class='group2 sub_group1'>
        <td>data 7</td>
        <td>data 8</td>
      </tr>
      <tr class='group2 sub_group1'>
        <td>data 9</td>
        <td>data 10</td>
      </tr>
      <tr class='group2 sub_group1'>
        <td class='sub_sub_group1'>Sub Sub Group 1</td>
        <td>data 11</td>
      </tr>
      <tr class='group2 sub_group1 sub_sub_group1'>
        <td>data 12</td>
        <td>data 13</td>
      </tr>
      <tr class='group2 sub_group1 sub_sub_group1'>
        <td>data 14</td>
        <td>data 15</td>
      </tr>
      <tr class='group2'>
        <td class='sub_group2'>Sub Group 2</td>
        <td>data 11</td>
      </tr>
      <tr class='group2 sub_group2'>
        <td>data 12</td>
        <td>data 13</td>
      </tr>
      <tr class='group2 sub_group2'>
        <td>data 14</td>
        <td>data 15</td>
      </tr>
    </table>
    

    CSS

    table, tr, td, th
    {
        border: 1px solid black;
        border-collapse:collapse;
    }
    
    img.button_open{
      content:url('http://code.stephenmorley.org/javascript/collapsible-lists/button-open.png');
      cursor:pointer;
    }
    
    img.button_closed{
      content: url('http://code.stephenmorley.org/javascript/collapsible-lists/button-closed.png');
      cursor:pointer;
    }
    

    JS

    function CreateGroup(group_name)
    {
        // Create Button(Image)
        $('td.' + group_name).prepend("<img class='" + group_name + " button_closed'> ");
        // Add Padding to Data
        $('tr.' + group_name).each(function () {
            var first_td = $(this).children('td').first();
            var padding_left = parseInt($(first_td).css('padding-left'));
            $(first_td).css('padding-left', String(padding_left + 25) + 'px');
        });
        RestoreGroup(group_name);
    
        // Tie toggle function to the button
        $('img.' + group_name).click(function(){
            ToggleGroup(group_name);
        });
    }
    
    function ToggleGroup(group_name)
    {
        ToggleButton($('img.' + group_name));
        RestoreGroup(group_name);
    }
    
    function RestoreGroup(group_name)
    {
        if ($('img.' + group_name).hasClass('button_open'))
        {
            // Open everything
            $('tr.' + group_name).show();
    
            // Close subgroups that been closed
            $('tr.' + group_name).find('img.button_closed').each(function () {
                sub_group_name = $(this).attr('class').split(/\s+/)[0];
                //console.log(sub_group_name);
                RestoreGroup(sub_group_name);
            });
        }
    
        if ($('img.' + group_name).hasClass('button_closed'))
        {
            // Close everything
            $('tr.' + group_name).hide();
        }
    }
    
    function ToggleButton(button)
    {
        $(button).toggleClass('button_open');
        $(button).toggleClass('button_closed');
    }
    
    CreateGroup('group1');
    CreateGroup('group2');
    CreateGroup('sub_group1');
    CreateGroup('sub_group2');
    CreateGroup('sub_sub_group1');
    

    DEMO

    Batch file to perform start, run, %TEMP% and delete all

    @echo off
    del /s /f /q c:\windows\temp\*.*
    rd /s /q c:\windows\temp
    md c:\windows\temp
    del /s /f /q C:\WINDOWS\Prefetch
    del /s /f /q %temp%\*.*
    rd /s /q %temp%
    md %temp%
    deltree /y c:\windows\tempor~1
    deltree /y c:\windows\temp
    deltree /y c:\windows\tmp
    deltree /y c:\windows\ff*.tmp
    deltree /y c:\windows\history
    deltree /y c:\windows\cookies
    deltree /y c:\windows\recent
    deltree /y c:\windows\spool\printers
    del c:\WIN386.SWP
    cls
    

    Add single element to array in numpy

    This might be a bit overkill, but I always use the the np.take function for any wrap-around indexing:

    >>> a = np.array([1, 2, 3])
    >>> np.take(a, range(0, len(a)+1), mode='wrap')
    array([1, 2, 3, 1])
    
    >>> np.take(a, range(-1, len(a)+1), mode='wrap')
    array([3, 1, 2, 3, 1])
    

    How to get all privileges back to the root user in MySQL?

    This worked for me on Ubuntu:

    Stop MySQL server:

    /etc/init.d/mysql stop
    

    Start MySQL from the commandline:

    /usr/sbin/mysqld
    

    In another terminal enter mysql and issue:

    grant all privileges on *.* to 'root'@'%' with grant option;
    

    You may also want to add

    grant all privileges on *.* to 'root'@'localhost' with grant option;
    

    and optionally use a password as well.

    flush privileges;
    

    and then exit your MySQL prompt and then kill the mysqld server running in the foreground. Restart with

    /etc/init.d/mysql start  
    

    How to merge a transparent png image with another image using PIL

    I ended up coding myself the suggestion of this comment made by the user @P.Melch and suggested by @Mithril on a project I'm working on.

    I coded out of bounds safety as well, here's the code for it. (I linked a specific commit because things can change in the future of this repository)

    Note: I expect numpy arrays from the images like so np.array(Image.open(...)) as the inputs A and B from copy_from and this linked function overlay arguments.

    The dependencies are the function right before it, the copy_from method, and numpy arrays as the PIL Image content for slicing.

    Though the file is very class oriented, if you want to use that function overlay_transparent, be sure to rename the self.frame to your background image numpy array.

    Or you can just copy the whole file (probably remove some imports and the Utils class) and interact with this Frame class like so:

    # Assuming you named the file frame.py in the same directory
    from frame import Frame
    
    background = Frame()
    overlay = Frame()
    
    background.load_from_path("your path here")
    overlay.load_from_path("your path here")
    
    background.overlay_transparent(overlay.frame, x=300, y=200)
    

    Then you have your background.frame as the overlayed and alpha composited array, you can get a PIL image from it with overlayed = Image.fromarray(background.frame) or something like:

    overlayed = Frame()
    overlayed.load_from_array(background.frame)
    

    Or just background.save("save path") as that takes directly from the alpha composited internal self.frame variable.

    You can read the file and find some other nice functions with this implementation I coded like the methods get_rgb_frame_array, resize_by_ratio, resize_to_resolution, rotate, gaussian_blur, transparency, vignetting :)

    You'd probably want to remove the resolve_pending method as that is specific for that project.

    Glad if I helped you, be sure to check out the repo of the project I'm talking about, this question and thread helped me a lot on the development :)

    How can I convert spaces to tabs in Vim or Linux?

    Changes all spaces to tab :%s/\s/\t/g

    Transactions in .net

    protected void Button1_Click(object sender, EventArgs e)
       {
    
    
           using (SqlConnection connection1 = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True"))
           {
               connection1.Open();
    
               // Start a local transaction.
               SqlTransaction sqlTran = connection1.BeginTransaction();
    
               // Enlist a command in the current transaction.
               SqlCommand command = connection1.CreateCommand();
               command.Transaction = sqlTran;
    
               try
               {
                   // Execute two separate commands.
                   command.CommandText =
                    "insert into [doctor](drname,drspecialization,drday) values ('a','b','c')";
                   command.ExecuteNonQuery();
                   command.CommandText =
                    "insert into [doctor](drname,drspecialization,drday) values ('x','y','z')";
                   command.ExecuteNonQuery();
    
                   // Commit the transaction.
                   sqlTran.Commit();
                   Label3.Text = "Both records were written to database.";
               }
               catch (Exception ex)
               {
                   // Handle the exception if the transaction fails to commit.
                   Label4.Text = ex.Message;
    
    
                   try
                   {
                       // Attempt to roll back the transaction.
                       sqlTran.Rollback();
                   }
                   catch (Exception exRollback)
                   {
                       // Throws an InvalidOperationException if the connection 
                       // is closed or the transaction has already been rolled 
                       // back on the server.
                       Label5.Text = exRollback.Message;
    
                   }
               }
           }
    
    
       }
    

    How to install PIP on Python 3.6?

    Since python 3.4 pip is included in the installation of python.

    Generate random password string with requirements in javascript

    A little more maintainable and secure approach.

    An update to expand on what I meant and how it works.

    1. Secure. MDN is pretty explicit about the use of Math.random for anything related to security:

      Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

      Looking at the can-i-use for getRandomValues in 2020 you probably don't need the msCrypto and Math.random fallback any more, unless you care about ancient browsers.

    2. Maintainable is mostly about the RegExp _pattern as an easy way to define what character classes you allow in the password. But also about the 3 things where each does its job: defines a pattern, gets a random byte as securely as possible, provides a public API to combine the two.

    _x000D_
    _x000D_
    var Password = {
     
      _pattern : /[a-zA-Z0-9_\-\+\.]/,
      
      
      _getRandomByte : function()
      {
        // http://caniuse.com/#feat=getrandomvalues
        if(window.crypto && window.crypto.getRandomValues) 
        {
          var result = new Uint8Array(1);
          window.crypto.getRandomValues(result);
          return result[0];
        }
        else if(window.msCrypto && window.msCrypto.getRandomValues) 
        {
          var result = new Uint8Array(1);
          window.msCrypto.getRandomValues(result);
          return result[0];
        }
        else
        {
          return Math.floor(Math.random() * 256);
        }
      },
      
      generate : function(length)
      {
        return Array.apply(null, {'length': length})
          .map(function()
          {
            var result;
            while(true) 
            {
              result = String.fromCharCode(this._getRandomByte());
              if(this._pattern.test(result))
              {
                return result;
              }
            }        
          }, this)
          .join('');  
      }    
        
    };
    _x000D_
    <input type='text' id='p'/><br/>
    <input type='button' value ='generate' onclick='document.getElementById("p").value = Password.generate(16)'>
    _x000D_
    _x000D_
    _x000D_

    How to loop backwards in python?

    def reverse(text):
        reversed = ''
        for i in range(len(text)-1, -1, -1):
            reversed += text[i]
        return reversed
    
    print("reverse({}): {}".format("abcd", reverse("abcd")))
    

    Enter key pressed event handler

    The KeyDown event only triggered at the standard TextBox or MaskedTextBox by "normal" input keys, not ENTER or TAB and so on.

    One can get special keys like ENTER by overriding the IsInputKey method:

    public class CustomTextBox : System.Windows.Forms.TextBox
    {
        protected override bool IsInputKey(Keys keyData)
        {
            if (keyData == Keys.Return)
                return true;
            return base.IsInputKey(keyData);
        }
    }
    

    Then one can use the KeyDown event in the following way:

    CustomTextBox ctb = new CustomTextBox();
    ctb.KeyDown += new KeyEventHandler(tb_KeyDown);
    
    private void tb_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
              //Enter key is down
    
              //Capture the text
              if (sender is TextBox)
              {
                  TextBox txb = (TextBox)sender;
                  MessageBox.Show(txb.Text);
              }
        }
    }
    

    ldap_bind: Invalid Credentials (49)

    I don't see an obvious problem with the above.

    It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

    Try an explicit URI:

    ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
    

    or prevent defaults with:

    LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
    

    If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

    • make sure your slapd.conf is being used and is correct (as root)

      slapd -T test -f slapd.conf -d 65535

      You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

    • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

      slapd -h ldap://localhost -d 481

      then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

    • if debug is enabled, then try also

      ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

    html select only one checkbox in a group

    If someone need a solution without an external javascript libraries you could use this example. A group of checkboxes allowing 0..1 values. You may click on the checkbox component or associated label text.

        <input id="mygroup1" name="mygroup" type="checkbox" value="1" onclick="toggleRadioCheckbox(this)" /> <label for="mygroup1">Yes</label>
        <input id="mygroup0" name="mygroup" type="checkbox" value="0" onclick="toggleRadioCheckbox(this)" /> <label for="mygroup0">No</label>
    
    - - - - - - - - 
    
        function toggleRadioCheckbox(sender) {
            // RadioCheckbox: 0..1 enabled in a group 
            if (!sender.checked) return;
            var fields = document.getElementsByName(sender.name);
            for(var idx=0; idx<fields.length; idx++) {
                var field = fields[idx];
                if (field.checked && field!=sender)
                    field.checked=false;
            }
        }
    

    There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

    A more simple approach where you can't mingle with the master.

    Consider i have master and JIRA-1234 branch and when i am trying to merge JIRA-1234 to master i am getting the above issue so please follow below steps:-

    1. From JIRA-1234 cut a branch JIRA-1234-rebase (Its a temp branch and can have any name. I have taken JIRA-1234-rebase to be meaningful.)

      git checkout JIRA-1234

      git checkout -b JIRA-1234-rebase

    2. The above command will create a new branch JIRA-1234-rebase and will checkout it.

    3. Now we will rebase our master.

      git rebase master (This is executed in the same branch JIRA-1234-rebase)

    4. You will see a window showing the commit history from first commit till the last commit on JIRA-1234-rebase. So if we have 98 commits then it will rebase them 1 by 1 and you will see something like 1/98.

    5. Here we just need to pick the commit we want so if you want this commit then don't do anything and just HIT Esc then :q! and HIT ENTER.
    6. There would be some changes in case of conflict and you need to resolve this conflict and then add the files by

      git add <FILE_NAME>.

    7. Now do git rebase continue it will take you to rebase 2/98 and similarly you have to go through all the 98 commits and resolve all of them and remeber we need to add the files in each commit.

    8. Finally you can now push these commits and then raise Pull Request by

      git push or git push origin JIRA-1234-rebase

    Efficient way to insert a number into a sorted array of numbers?

    For a small number of items, the difference is pretty trivial. However, if you're inserting a lot of items, or working with a very large array, calling .sort() after each insertion will cause a tremendous amount of overhead.

    I ended up writing a pretty slick binary search/insert function for this exact purpose, so I thought I'd share it. Since it uses a while loop instead of recursion, there is no overheard for extra function calls, so I think the performance will be even better than either of the originally posted methods. And it emulates the default Array.sort() comparator by default, but accepts a custom comparator function if desired.

    function insertSorted(arr, item, comparator) {
        if (comparator == null) {
            // emulate the default Array.sort() comparator
            comparator = function(a, b) {
                if (typeof a !== 'string') a = String(a);
                if (typeof b !== 'string') b = String(b);
                return (a > b ? 1 : (a < b ? -1 : 0));
            };
        }
    
        // get the index we need to insert the item at
        var min = 0;
        var max = arr.length;
        var index = Math.floor((min + max) / 2);
        while (max > min) {
            if (comparator(item, arr[index]) < 0) {
                max = index;
            } else {
                min = index + 1;
            }
            index = Math.floor((min + max) / 2);
        }
    
        // insert the item
        arr.splice(index, 0, item);
    };
    

    If you're open to using other libraries, lodash provides sortedIndex and sortedLastIndex functions, which could be used in place of the while loop. The two potential downsides are 1) performance isn't as good as my method (thought I'm not sure how much worse it is) and 2) it does not accept a custom comparator function, only a method for getting the value to compare (using the default comparator, I assume).

    EXEC sp_executesql with multiple parameters

    This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.

    DECLARE @Parmdef nvarchar (500)
    DECLARE @SQL nvarchar (max)
    DECLARE @xTxt1  nvarchar (100) = 'test1'
    DECLARE @xTxt2  nvarchar (500) = 'test2' 
    SET @parmdef = '@text1 nvarchar (100), @text2 nvarchar (500)'
    SET @SQL = 'PRINT @text1 + '' '' + @text2'
    EXEC sp_executeSQL @SQL, @Parmdef, @xTxt1, @xTxt2
    

    Editing dictionary values in a foreach loop

    Along with the other answers, I thought I'd note that if you get sortedDictionary.Keys or sortedDictionary.Values and then loop over them with foreach, you also go through in sorted order. This is because those methods return System.Collections.Generic.SortedDictionary<TKey,TValue>.KeyCollection or SortedDictionary<TKey,TValue>.ValueCollection objects, which maintain the sort of the original dictionary.

    iPad Multitasking support requires these orientations

    You need to add Portrait (top home button) on the supported interface orientation field of info.plist file in xcode

    enter image description here

    Where should I put <script> tags in HTML markup?

    You can place most of <script> references at the end of <body>,
    But If there are active components on your page which are using external scripts,
    then their dependency (js files) should come before that (ideally in head tag).

    Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

    Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

    element = document.getElementById(id);
    element is a reference to an Element object, or null if an element with the specified ID is not in the document.

    MDN

    Solutions:

    1. Put the scripts in the bottom of the page.
    2. Call the attach code in the load event.
    3. Use jQuery library and it's DOM ready event.

    What is the jQuery ready event and why is it needed?
    (why no just JavaScript's load event):

    While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
    ...

    ready docs

    How to change HTML Object element data attribute value in javascript

    In JavaScript, you can assign values to data attributes through Element.dataset.

    For example:

    avatar.dataset.id = 12345;
    

    Reference: https://developer.mozilla.org/en/docs/Web/API/HTMLElement/dataset

    How to display an image from a path in asp.net MVC 4 and Razor view?

    In your View try like this

      <img src= "@Url.Content(Model.ImagePath)" alt="Image" />
    

    DBCC CHECKIDENT Sets Identity to 0

    I did this as an experiment to reset the value to 0 as I want my first identity column to be 0 and it's working.

    dbcc CHECKIDENT(MOVIE,RESEED,0)
    dbcc CHECKIDENT(MOVIE,RESEED,-1)
    DBCC CHECKIDENT(MOVIE,NORESEED)
    

    jQuery - Getting the text value of a table cell in the same row as a clicked element

    it should work fine:

    var Something = $(this).children("td:nth-child(n)").text();
    

    bash: shortest way to get n-th column of output

    You can use cut to access the second field:

    cut -f2
    

    Edit: Sorry, didn't realise that SVN doesn't use tabs in its output, so that's a bit useless. You can tailor cut to the output but it's a bit fragile - something like cut -c 10- would work, but the exact value will depend on your setup.

    Another option is something like: sed 's/.\s\+//'

    AssertNull should be used or AssertNotNull

    The assertNotNull() method means "a passed parameter must not be null": if it is null then the test case fails.
    The assertNull() method means "a passed parameter must be null": if it is not null then the test case fails.

    String str1 = null;
    String str2 = "hello";              
    
    // Success.
    assertNotNull(str2);
    
    // Fail.
    assertNotNull(str1);
    
    // Success.
    assertNull(str1);
    
    // Fail.
    assertNull(str2);
    

    tsc throws `TS2307: Cannot find module` for a local file

    The vscode codebase does not use relative paths, but everything works fine for them

    Really depends on your module loader. If you are using systemjs with baseurl then it would work. VSCode uses its own custom module loader (based on an old version of requirejs).

    Recommendation

    Use relative paths as that is what commonjs supports. If you move files around you will get a typescript compile time error (a good thing) so you will be better off than a great majority of pure js projects out there (on npm).

    How to specify legend position in matplotlib in graph coordinates

    You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

    import matplotlib.pyplot as plt
    
    plt.subplot(211)
    plt.plot([1,2,3], label="test1")
    plt.plot([3,2,1], label="test2")
    # Place a legend above this subplot, expanding itself to
    # fully use the given bounding box.
    plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
               ncol=2, mode="expand", borderaxespad=0.)
    
    plt.subplot(223)
    plt.plot([1,2,3], label="test1")
    plt.plot([3,2,1], label="test2")
    # Place a legend to the right of this smaller subplot.
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    
    plt.show()
    

    How to open Visual Studio Code from the command line on OSX?

    This was the tutorial I was looking for in this thread. It shows the way to open files in Visual Studio Code by writing code .

    1.- Open the file

    Bash

                    open ~/.bash_profile 
    

    Terminal OS

                        open ~/.zshrc
    

    2.- Add in your file the :

             code () { VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $* ;}
    

    3.- Reinicialize terminal and try in the folder you want to open

             code .
    

    4.- Then you can use it as shown in this comment: https://stackoverflow.com/a/41821250/10033560

    Laravel Rule Validation for Numbers

    $this->validate($request,[
            'input_field_name'=>'digits_between:2,5',
           ]);
    

    Try this it will be work

    Jquery insert new row into table at a certain index

    Try this:

    var i = 3;
    
    $('#my_table > tbody > tr:eq(' + i + ')').after(html);
    

    or this:

    var i = 3;
    
    $('#my_table > tbody > tr').eq( i ).after(html);
    

    or this:

    var i = 4;
    
    $('#my_table > tbody > tr:nth-child(' + i + ')').after(html);
    

    All of these will place the row in the same position. nth-child uses a 1 based index.

    Basic text editor in command prompt?

    vim may be challenging for beginners. For a quick-and-dirty Windows console-mode text editor, I would suggest Kinesics Text Editor.

    OSError: [Errno 8] Exec format error

    If you think the space before and after "=" is mandatory, try it as separate item in the list.

    Out = subprocess.Popen(['/usr/local/bin/script', 'hostname', '=', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    

    Navigate to another page with a button in angular 2

    Use it like this, should work:

     <a routerLink="/Service/Sign_in"><button class="btn btn-success pull-right" > Add Customer</button></a>
    

    You can also use router.navigateByUrl('..') like this:

    <button type="button" class="btn btn-primary-outline pull-right" (click)="btnClick();"><i class="fa fa-plus"></i> Add</button>    
    
    import { Router } from '@angular/router';
    
    btnClick= function () {
            this.router.navigateByUrl('/user');
    };
    

    Update 1

    You have to inject Router in the constructor like this:

    constructor(private router: Router) { }
    

    only then you are able to use this.router. Remember also to import RouterModule in your module.

    Update 2

    Now, After Angular v4 you can directly add routerLink attribute on the button (As mentioned by @mark in comment section) like below (No "'/url?" since Angular 6, when a Route in RouterModule exists) -

     <button [routerLink]="'url'"> Button Label</button>
    

    How to convert unsigned long to string

    The standard approach is to use sprintf(buffer, "%lu", value); to write a string rep of value to buffer. However, overflow is a potential problem, as sprintf will happily (and unknowingly) write over the end of your buffer.

    This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.

    This site discusses this and related problems at some length.

    Some libraries offer snprintf as an alternative which lets you specify a maximum buffer size.

    Howto? Parameters and LIKE statement SQL

    Well, I'd go with:

     Dim cmd as New SqlCommand(
     "SELECT * FROM compliance_corner"_
      + " WHERE (body LIKE @query )"_ 
      + " OR (title LIKE @query)")
    
     cmd.Parameters.Add("@query", "%" +searchString +"%")
    

    How to add not null constraint to existing column in MySQL

    Try this, you will know the difference between change and modify,

    ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]
    
    ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
    
    • You can change name and datatype of the particular column using CHANGE.
    • You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

    Hope, I explained well in detail.

    How to export a Hive table into a CSV file?

    I have used simple linux shell piping + perl to convert hive generated output from tsv to csv.

    hive -e "SELECT col1, col2, … FROM table_name" | perl -lpe 's/"/\\"/g; s/^|$/"/g; s/\t/","/g' > output_file.csv
    

    (I got the updated perl regex from someone in stackoverflow some time ago)

    The result will be like regular csv:

    "col1","col2","col3"... and so on

    What does "implements" do on a class?

    Implements means that it takes on the designated behavior that the interface specifies. Consider the following interface:

    public interface ISpeak
    {
       public String talk();
    }
    
    public class Dog implements ISpeak
    {
       public String talk()
       {
            return "bark!";
       }
    }
    
    public class Cat implements ISpeak
    {
        public String talk()
        {
            return "meow!";
        }
    }
    

    Both the Cat and Dog class implement the ISpeak interface.

    What's great about interfaces is that we can now refer to instances of this class through the ISpeak interface. Consider the following example:

      Dog dog = new Dog();
      Cat cat = new Cat();
    
      List<ISpeak> animalsThatTalk = new ArrayList<ISpeak>();
    
      animalsThatTalk.add(dog);
      animalsThatTalk.add(cat);
    
      for (ISpeak ispeak : animalsThatTalk)
      {
          System.out.println(ispeak.talk());
      }
    

    The output for this loop would be:

    bark!
    meow!

    Interface provide a means to interact with classes in a generic way based upon the things they do without exposing what the implementing classes are.

    One of the most common interfaces used in Java, for example, is Comparable. If your object implements this interface, you can write an implementation that consumers can use to sort your objects.

    For example:

    public class Person implements Comparable<Person>
    {
      private String firstName;
      private String lastName;
    
      // Getters/Setters
    
      public int compareTo(Person p)
      {
        return this.lastName.compareTo(p.getLastName());  
      }
    }
    

    Now consider this code:

    //  Some code in other class
    
    List<Person> people = getPeopleList();
    
    Collections.sort(people);
    

    What this code did was provide a natural ordering to the Person class. Because we implemented the Comparable interface, we were able to leverage the Collections.sort() method to sort our List of Person objects by its natural ordering, in this case, by last name.

    Android Firebase, simply get one child object's data

    I store my data this way:

    accountsTable ->
      key1 -> account1
      key2 -> account2
    

    in order to get object data:

    accountsDb = mDatabase.child("accountsTable");
    
    accountsDb.child("some   key").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot snapshot) {
    
                        try{
    
                            Account account  = snapshot.getChildren().iterator().next()
                                      .getValue(Account.class);
    
    
                        } catch (Throwable e) {
                            MyLogger.error(this, "onCreate eror", e);
                        }
                    }
                    @Override public void onCancelled(DatabaseError error) { }
                });
    

    How can I remove an element from a list?

    There's the rlist package (http://cran.r-project.org/web/packages/rlist/index.html) to deal with various kinds of list operations.

    Example (http://cran.r-project.org/web/packages/rlist/vignettes/Filtering.html):

    library(rlist)
    devs <- 
      list(
        p1=list(name="Ken",age=24,
          interest=c("reading","music","movies"),
          lang=list(r=2,csharp=4,python=3)),
        p2=list(name="James",age=25,
          interest=c("sports","music"),
          lang=list(r=3,java=2,cpp=5)),
        p3=list(name="Penny",age=24,
          interest=c("movies","reading"),
          lang=list(r=1,cpp=4,python=2)))
    
    list.remove(devs, c("p1","p2"))
    

    Results in:

    # $p3
    # $p3$name
    # [1] "Penny"
    # 
    # $p3$age
    # [1] 24
    # 
    # $p3$interest
    # [1] "movies"  "reading"
    # 
    # $p3$lang
    # $p3$lang$r
    # [1] 1
    # 
    # $p3$lang$cpp
    # [1] 4
    # 
    # $p3$lang$python
    # [1] 2
    

    How to set the "Content-Type ... charset" in the request header using a HTML link

    This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

    To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


    Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

    alt text

    How to get user agent in PHP

    You could also use the php native funcion get_browser()

    IMPORTANT NOTE: You should have a browscap.ini file.

    Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

    Possible duplicate: Is there a maven 2 archetype for spring 3 MVC applications?

    That said, I would encourage you to think about making your own archetype. The reason is, no matter what you end up getting from someone else's, you can do better in not that much time, and a decent sized Java project is going to end up making a lot of jar projects.

    MySQLi count(*) always returns 1

    Always try to do an associative fetch, that way you can easy get what you want in multiple case result

    Here's an example

    $result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
    $row = $result->fetch_assoc();
    echo $row['cityCount']." rows in table myCity.";
    

    ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

    The following steps are to reset the password for a user in case you forgot, this would also solve your mentioned error.

    First, stop your MySQL:

    sudo /etc/init.d/mysql stop
    

    Now start up MySQL in safe mode and skip the privileges table:

    sudo mysqld_safe --skip-grant-tables &
    

    Login with root:

    mysql -uroot
    

    And assign the DB that needs to be used:

    use mysql;
    

    Now all you have to do is reset your root password of the MySQL user and restart the MySQL service:

    update user set password=PASSWORD("YOURPASSWORDHERE") where User='root';
    
    flush privileges;
    

    quit and restart MySQL:

    quit
    

    sudo /etc/init.d/mysql stop sudo /etc/init.d/mysql start Now your root password should be working with the one you just set, check it with:

    mysql -u root -p
    

    Remove ListView items in Android

    You can also use listView.setOnItemLongClickListener to delete selected item. Below is the code.

    // listView = name of your ListView

      listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int 
            position, long id) {
    
            // it will get the position of selected item from the ListView
    
    final int selected_item = position;
    
                new AlertDialog.Builder(MainActivity.this).
                        setIcon(android.R.drawable.ic_delete)
                        .setTitle("Are you sure...")
                        .setMessage("Do you want to delete the selected item..?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                list.remove(selected_item);
                                arrayAdapter.notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton("No" , null).show();
    
                return true;
            }
        });
    

    How can I get the named parameters from a URL using Flask?

    Use request.args.get(param), for example:

    http://10.1.1.1:5000/login?username=alex&password=pw1
    
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        username = request.args.get('username')
        print(username)
        password = request.args.get('password')
        print(password)
    

    Here is the referenced link to the code.

    Error with multiple definitions of function

    The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.

    You don't want to include cpp files. You want to include header files.

    The header file should just have the class definition. The corresponding cpp file, which you will compile separately, will have the function definition.

    fun.hpp:

    #include <iostream>
    
    class classA {
        friend void funct();
    public:
        classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
    private:
        int propa;
        int propb;
        void outfun(){
            std::cout<<"propa="<<propa<<endl<<"propb="<<propb<< std::endl;
        }
    };
    

    fun.cpp:

    #include "fun.hpp"
    
    using namespace std;
    
    void funct(){
        cout<<"enter funct"<<endl;
        classA tmp(1,2);
        tmp.outfun();
        cout<<"exit funct"<<endl;
    }
    

    mainfile.cpp:

    #include <iostream>
    #include "fun.hpp"
    using namespace std;
    
    int main(int nargin,char* varargin[]) {
        cout<<"call funct"<<endl;
        funct();
        cout<<"exit main"<<endl;
        return 0;
    }
    

    Note that it is generally recommended to avoid using namespace std in header files.

    Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

    Use

    export LD_LIBRARY_PATH="/path/to/library/"
    

    in your .bashrc otherwise, it'll only be available to bash and not any programs you start.

    Try -R/path/to/library/ flag when you're linking, it'll make the program look in that directory and you won't need to set any environment variables.

    EDIT: Looks like -R is Solaris only, and you're on Linux.

    An alternate way would be to add the path to /etc/ld.so.conf and run ldconfig. Note that this is a global change that will apply to all dynamically linked binaries.

    Cannot ping AWS EC2 instance

    1. Go to EC2 Dashboard and click "Running Instances" on "Security Groups", select the group of your instance which you need to add security.
    2. click on the "Inbound" tab
    3. Click "Edit" Button (It will open an popup window)
    4. click "Add Rule"
    5. Select the "Custom ICMP rule - IPv4" as Type
    6. Select "Echo Request" and "Echo Response" as the Protocol (Port Range by default show as "N/A)
    7. Enter the "0.0.0.0/0" as Source
    8. Click "Save"

    What is the "__v" field in Mongoose

    It is the version key.It gets updated whenever a new update is made. I personally don't like to disable it .

    Read this solution if you want to know more [1]: Mongoose versioning: when is it safe to disable it?

    How to add parameters to HttpURLConnection using POST using NameValuePair

    Try this:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("your url");
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
    nameValuePairs.add(new BasicNameValuePair("user_name", "Name"));
    nameValuePairs.add(new BasicNameValuePair("pass","Password" ));
    nameValuePairs.add(new BasicNameValuePair("user_email","email" ));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);
    
    String ret = EntityUtils.toString(response.getEntity());
    Log.v("Util response", ret);
    

    You can add as many nameValuePairs as you need. And don't forget to mention the count in the list.

    How to deserialize a JObject to .NET object

    According to this post, it's much better now:

    // pick out one album
    JObject jalbum = albums[0] as JObject;
    
    // Copy to a static Album instance
    Album album = jalbum.ToObject<Album>();
    

    Documentation: Convert JSON to a Type

    How to negate a method reference predicate

    You can accomplish this as long emptyStrings = s.filter(s->!s.isEmpty()).count();

    Powershell script does not run via Scheduled Tasks

    In my case it was related to a .ps1 referral inside the ps1 script which was not signed (you need to unblock it at the file properties) , also I added as first line:

    Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force

    Then it worked

    Java: print contents of text file to screen

    Every example here shows a solution using the FileReader. It is convenient if you do not need to care about a file encoding. If you use some other languages than english, encoding is quite important. Imagine you have file with this text

    Príliš žlutoucký kun
    úpel dábelské ódy
    

    and the file uses windows-1250 format. If you use FileReader you will get this result:

    P??li? ?lu?ou?k? k??
    ?p?l ??belsk? ?dy
    

    So in this case you would need to specify encoding as Cp1250 (Windows Eastern European) but the FileReader doesn't allow you to do so. In this case you should use InputStreamReader on a FileInputStream.

    Example:

    String encoding = "Cp1250";
    File file = new File("foo.txt");
    
    if (file.exists()) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    else {
        System.out.println("file doesn't exist");
    }
    

    In case you want to read the file character after character do not use BufferedReader.

    try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), encoding)) {
        int data = isr.read();
        while (data != -1) {
            System.out.print((char) data);
            data = isr.read();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    How to use the 'og' (Open Graph) meta tag for Facebook share

    Facebook uses what's called the Open Graph Protocol to decide what things to display when you share a link. The OGP looks at your page and tries to decide what content to show. We can lend a hand and actually tell Facebook what to take from our page.

    The way we do that is with og:meta tags.

    The tags look something like this -

      <meta property="og:title" content="Stuffed Cookies" />
      <meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" />
      <meta property="og:description" content="The Turducken of Cookies" />
      <meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">
    

    You'll need to place these or similar meta tags in the <head> of your HTML file. Don't forget to substitute the values for your own!

    For more information you can read all about how Facebook uses these meta tags in their documentation. Here is one of the tutorials from there - https://developers.facebook.com/docs/opengraph/tutorial/


    Facebook gives us a great little tool to help us when dealing with these meta tags - you can use the Debugger to see how Facebook sees your URL, and it'll even tell you if there are problems with it.

    One thing to note here is that every time you make a change to the meta tags, you'll need to feed the URL through the Debugger again so that Facebook will clear all the data that is cached on their servers about your URL.

    Vertically align text within a div

    To make Omar's (or Mahendra's) solution even more universal, the block of code relative to Firefox should be replaced by the following:

    /* Firefox */
    display: flex;
    justify-content: center;
    align-items: center;
    

    The problem with Omar's code, otherwise operative, arises when you want to center the box in the screen or in its immediate ancestor. This centering is done either by setting its position to

    position: relative; or position:static; (not with position:absolute nor fixed).

    And then margin: auto; or margin-right: auto; margin-left: auto;

    Under this box center aligning environment, Omar's suggestion does not work. It doesn't work either in Internet Explorer 8 (yet 7.7% market share). So for Internet Explorer 8 (and other browsers), a workaround as seen in other above solutions should be considered.

    Expression must have class type

    It's a pointer, so instead try:

    a->f();
    

    Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

    A a;
    a.f();
    A& ref = a;
    ref.f();
    

    If you have a pointer type, you have to dereference it first to obtain a reference:

    A* ptr = new A();
    (*ptr).f();
    ptr->f();
    

    The a->b notation is usually just a shorthand for (*a).b.

    A note on smart pointers

    The operator-> can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use -> to refer to the pointed object:

    auto ptr = make_unique<A>();
    ptr->f();
    

    How to install node.js as windows service?

    From this blog

    Next up, I wanted to host node as a service, just like IIS. This way it’d start up with my machine, run in the background, restart automatically if it crashes and so forth.

    This is where nssm, the non-sucking service manager, enters the picture. This tool lets you host a normal .exe as a Windows service.

    Here are the commands I used to setup an instance of the your node application as a service, open your cmd like administrator and type following commands:

    nssm.exe install service_name c:\your_nodejs_directory\node.exe c:\your_application_directory\server.js
    net start service_name
    

    Is ConfigurationManager.AppSettings available in .NET Core 2.0?

    You can use Configuration to resolve this.

    Ex (Startup.cs):

    You can pass by DI to the controllers after this implementation.

    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    
            Configuration = builder.Build();
    
        }
    
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
    
            var microserviceName = Configuration["microserviceName"];
    
           services.AddSingleton(Configuration);
    
           ...
        }
    

    How can I reconcile detached HEAD with master/origin?

    If you are completely sure HEAD is the good state:

    git branch -f master HEAD
    git checkout master
    

    You probably can't push to origin, since your master has diverged from origin. If you are sure no one else is using the repo, you can force-push:

    git push -f
    

    Most useful if you are on a feature branch no one else is using.

    Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

    SOAP – "Simple Object Access Protocol"

    SOAP is a slight of transferring messages, or little amounts of information over the Internet. SOAP messages are formatted in XML and are typically sent controlling HTTP.

    REST – "REpresentational State Transfer"

    REST is a rudimentary proceed of eventuality and receiving information between fan and server and it doesn't have unequivocally many standards defined. You can send and accept information as JSON, XML or even plain text. It's light weighted compared to SOAP.

    Remove Array Value By index in jquery

    1. Find the element in array and get its position
    2. Remove using the position

    _x000D_
    _x000D_
    var array = new Array();_x000D_
      _x000D_
    array.push('123');_x000D_
    array.push('456');_x000D_
    array.push('789');_x000D_
                     _x000D_
    var _searchedIndex = $.inArray('456',array);_x000D_
    alert(_searchedIndex );_x000D_
    if(_searchedIndex >= 0){_x000D_
      array.splice(_searchedIndex,1);_x000D_
      alert(array );_x000D_
    }
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    _x000D_
    _x000D_
    _x000D_

    • inArray() - helps you to find the position.
    • splice() - helps you to remove the element in that position.

    How can I print variable and string on same line in Python?

    You can either use a formatstring:

    print "There are %d births" % (births,)
    

    or in this simple case:

    print "There are ", births, "births"
    

    Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

    First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

    For example,

    > z <- factor(letters[c(3, 2, 3, 4)])
    
    # human-friendly display, but internal structure is invisible
    > z
    [1] c b c d
    Levels: b c d
    
    # internal structure of factor
    > unclass(z)
    [1] 2 1 2 3
    attr(,"levels")
    [1] "b" "c" "d"
    

    here, z has 4 elements.
    The index is 2, 1, 2, 3 in that order.
    The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

    Then, as.numeric converts simply the index part of factor into numeric.
    as.character handles the index and levels, and generates character vector expressed by its level.

    ?as.numeric says that Factors are handled by the default method.

    How to calculate the sum of all columns of a 2D numpy array (efficiently)

    Use the axis argument:

    >> numpy.sum(a, axis=0)
      array([18, 22, 26])
    

    SonarQube Exclude a directory

    This worked for me:

    sonar.exclusions=src/**/wwwroot/**/*.js,src/**/wwwroot/**/*.css
    

    It excludes any .js and .css files under any of the sub directories of a folder "wwwroot" appearing as one of the sub directories of the "src" folder (project root).

    How do I check if an element is really visible with JavaScript?

    You can use the clientHeight or clientWidth properties

    function isViewable(element){
      return (element.clientHeight > 0);
    }
    

    Variable length (Dynamic) Arrays in Java

    Simple code for dynamic array. In below code then array will become full of size we copy all element to new double size array(variable size array).sample code is below 
    
    public class DynamicArray {
     static   int []increaseSizeOfArray(int []arr){
              int []brr=new int[(arr.length*2)];
              for (int i = 0; i < arr.length; i++) {
             brr[i]=arr[i];     
              }
              return brr;
         }
    public static void main(String[] args) {
         int []arr=new int[5];
          for (int i = 0; i < 11; i++) {
              if (i<arr.length) {
                  arr[i]=i+100;
              }
              else {
                  arr=increaseSizeOfArray(arr);
                  arr[i]=i+100;
              }        
         }
    
    for (int i = 0; i < arr.length; i++) {
         System.out.println("arr="+arr[i]);
    }    
    }
    
    }
    

    Source : How to make dynamic array

    Align <div> elements side by side

    keep it simple

    <div align="center">
    <div style="display: inline-block"> <img src="img1.png"> </div>
    <div style="display: inline-block"> <img src="img2.png"> </div>
    </div>
    

    CardView background color always white

    XML code

    <android.support.v7.widget.CardView
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:id="@+id/card_view_top"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:cardCornerRadius="5dp"
            app:contentPadding="25dp"
            app:cardBackgroundColor="#e4bfef"
            app:cardElevation="4dp"
            app:cardMaxElevation="6dp" />
    

    From the code

    CardView card = findViewById(R.id.card_view_top);
    card.setCardBackgroundColor(Color.parseColor("#E6E6E6"));
    

    How to set proper codeigniter base url?

    I think CodeIgniter 3 recommends to set $config['base_url'] to a full url manually in order to avoid HTTP header injection.

    If you are not concerned about it, you can simply add the following lines in your

    application/config/config.php

    defined('BASE_URL') OR define('BASE_URL', (is_https() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']) . '/');
    $config['base_url'] = BASE_URL;
    

    In this way you also have BASE_URL constant available in all your project code (including the views) and you don't have to use functions:

    config_item('base_url') //returns BASE_URL
    $this->config->item('base_url'); //returns BASE_URL
    

    C++ catching all exceptions

    try{
        // ...
    } catch (...) {
        // ...
    }
    

    will catch all C++ exceptions, but it should be considered bad design. You can use c++11's new current_exception mechanism, but if you don't have the ability to use c++11 (legacy code systems requiring a rewrite), then you have no named exception pointer to use to get a message or name. You may want to add separate catch clauses for the various exceptions you can catch, and only catch everything at the bottom to record an unexpected exception. E.g.:

    try{
        // ...
    } catch (const std::exception& ex) {
        // ...
    } catch (const std::string& ex) {
        // ...
    } catch (...) {
        // ...
    }
    

    Should I use alias or alias_method?

    alias_method new_method, old_method

    old_method will be declared in a class or module which is being inherited now to our class where new_method will be used.

    these can be variable or method both.

    Suppose Class_1 has old_method, and Class_2 and Class_3 both of them inherit Class_1.

    If, initialization of Class_2 and Class_3 is done in Class_1 then both can have different name in Class_2 and Class_3 and its usage.

    Create a function with optional call variables

    Powershell provides a lot of built-in support for common parameter scenarios, including mandatory parameters, optional parameters, "switch" (aka flag) parameters, and "parameter sets."

    By default, all parameters are optional. The most basic approach is to simply check each one for $null, then implement whatever logic you want from there. This is basically what you have already shown in your sample code.

    If you want to learn about all of the special support that Powershell can give you, check out these links:

    about_Functions

    about_Functions_Advanced

    about_Functions_Advanced_Parameters

    alert() not working in Chrome

    put this line at the end of the body. May be the DOM is not ready yet at the moment this line is read by compiler.

    <script type="text/javascript" src="script.js"></script>"
    

    How to use variables in a command in sed?

    This might work for you:

    sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1
    

    Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

    Try to put this line of code in your main projects gradle script:

    configurations { all*.exclude group: 'com.android.support', module: 'support-v4' }
    

    I have two libraries linked to my project and they where using 'com.android.support:support-v4:22.0.0'.

    Hope it helps someone.

    How to change context root of a dynamic web project in Eclipse?

    If using eclipse to deploy your application . We can use this maven plugin

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <version>2.10</version>
        <configuration>
            <wtpversion>2.0</wtpversion>
            <wtpContextName>newContextroot</wtpContextName>
        </configuration>
    </plugin>
    

    now go to your project root folder and open cmd prompt at that location type this command :

    mvn eclipse:eclipse -Dwtpversion=2.0

    You may need to restart eclipse , or in server view delete server and create agian to see affect. I wonder this exercise make sense in real life but works.

    SQL Case Expression Syntax?

    The complete syntax depends on the database engine you're working with:

    For SQL Server:

    CASE case-expression
        WHEN when-expression-1 THEN value-1
      [ WHEN when-expression-n THEN value-n ... ]
      [ ELSE else-value ]
    END
    

    or:

    CASE
        WHEN boolean-when-expression-1 THEN value-1
      [ WHEN boolean-when-expression-n THEN value-n ... ]
      [ ELSE else-value ]
    END
    

    expressions, etc:

    case-expression    - something that produces a value
    when-expression-x  - something that is compared against the case-expression
    value-1            - the result of the CASE statement if:
                             the when-expression == case-expression
                          OR the boolean-when-expression == TRUE
    boolean-when-exp.. - something that produces a TRUE/FALSE answer
    

    Link: CASE (Transact-SQL)

    Also note that the ordering of the WHEN statements is important. You can easily write multiple WHEN clauses that overlap, and the first one that matches is used.

    Note: If no ELSE clause is specified, and no matching WHEN-condition is found, the value of the CASE expression will be NULL.

    How to set custom location for local installation of npm package?

    After searching for this myself wanting several projects with shared dependencies to be DRYer, I’ve found:

    • Installing locally is the Node way for anything you want to use via require()
    • Installing globally is for binaries you want in your path, but is not intended for anything via require()
    • Using a prefix means you need to add appropriate bin and man paths to $PATH
    • npm link (info) lets you use a local install as a source for globals

    ? stick to the Node way and install locally

    ref:

    JOIN queries vs multiple queries

    The real question is: Do these records have a one-to-one relationship or a one-to-many relationship?

    TLDR Answer:

    If one-to-one, use a JOIN statement.

    If one-to-many, use one (or many) SELECT statements with server-side code optimization.

    Why and How To Use SELECT for Optimization

    SELECT'ing (with multiple queries instead of joins) on large group of records based on a one-to-many relationship produces an optimal efficiency, as JOIN'ing has an exponential memory leak issue. Grab all of the data, then use a server-side scripting language to sort it out:

    SELECT * FROM Address WHERE Personid IN(1,2,3);
    

    Results:

    Address.id : 1            // First person and their address
    Address.Personid : 1
    Address.City : "Boston"
    
    Address.id : 2            // First person's second address
    Address.Personid : 1
    Address.City : "New York"
    
    Address.id : 3            // Second person's address
    Address.Personid : 2
    Address.City : "Barcelona"
    

    Here, I am getting all of the records, in one select statement. This is better than JOIN, which would be getting a small group of these records, one at a time, as a sub-component of another query. Then I parse it with server-side code that looks something like...

    <?php
        foreach($addresses as $address) {
             $persons[$address['Personid']]->Address[] = $address;
        }
    ?>
    

    When Not To Use JOIN for Optimization

    JOIN'ing a large group of records based on a one-to-one relationship with one single record produces an optimal efficiency compared to multiple SELECT statements, one after the other, which simply get the next record type.

    But JOIN is inefficient when getting records with a one-to-many relationship.

    Example: The database Blogs has 3 tables of interest, Blogpost, Tag, and Comment.

    SELECT * from BlogPost
    LEFT JOIN Tag ON Tag.BlogPostid = BlogPost.id
    LEFT JOIN Comment ON Comment.BlogPostid = BlogPost.id;
    

    If there is 1 blogpost, 2 tags, and 2 comments, you will get results like:

    Row1: tag1, comment1,
    Row2: tag1, comment2,
    Row3: tag2, comment1,
    Row4: tag2, comment2,
    

    Notice how each record is duplicated. Okay, so, 2 comments and 2 tags is 4 rows. What if we have 4 comments and 4 tags? You don't get 8 rows -- you get 16 rows:

    Row1: tag1, comment1,
    Row2: tag1, comment2,
    Row3: tag1, comment3,
    Row4: tag1, comment4,
    Row5: tag2, comment1,
    Row6: tag2, comment2,
    Row7: tag2, comment3,
    Row8: tag2, comment4,
    Row9: tag3, comment1,
    Row10: tag3, comment2,
    Row11: tag3, comment3,
    Row12: tag3, comment4,
    Row13: tag4, comment1,
    Row14: tag4, comment2,
    Row15: tag4, comment3,
    Row16: tag4, comment4,
    

    Add more tables, more records, etc., and the problem will quickly inflate to hundreds of rows that are all full of mostly redundant data.

    What do these duplicates cost you? Memory (in the SQL server and the code that tries to remove the duplicates) and networking resources (between SQL server and your code server).

    Source: https://dev.mysql.com/doc/refman/8.0/en/nested-join-optimization.html ; https://dev.mysql.com/doc/workbench/en/wb-relationship-tools.html

    Equivalent of shell 'cd' command to change the working directory?

    import os
    
    abs_path = 'C://a/b/c'
    rel_path = './folder'
    
    os.chdir(abs_path)
    os.chdir(rel_path)
    

    You can use both with os.chdir(abs_path) or os.chdir(rel_path), there's no need to call os.getcwd() to use a relative path.

    Reloading .env variables without restarting server (Laravel 5, shared hosting)

    I know this is old, but for local dev, this is what got things back to a production .env file:

    rm bootstrap/cache/config.php
    

    then

    php artisan config:cache
    php artisan config:clear
    php artisan cache:clear
    

    How to get current timestamp in milliseconds since 1970 just the way Java gets

    If you have access to the C++ 11 libraries, check out the std::chrono library. You can use it to get the milliseconds since the Unix Epoch like this:

    #include <chrono>
    
    // ...
    
    using namespace std::chrono;
    milliseconds ms = duration_cast< milliseconds >(
        system_clock::now().time_since_epoch()
    );
    

    method in class cannot be applied to given types

    call generateNumbers(numbers);, your generateNumbers(); expects int[] as an argument ans you were passing none, thus the error

    Firebase onMessageReceived not called when app in background

    There are 2 types of Firebase push-notifications:

    1- Notification message(Display message) -> -- 1.1 If you choose this variant, the OS will create it self a notification if app is in Background and will pass the data in the intent. Then it's up to the client to handle this data.

    -- 1.2 If the app is in Foreground then the notification it will be received via callback-function in the FirebaseMessagingService and it's up to the client to handle it.

    2- Data messages(up to 4k data) -> These messages are used to send only data to the client(silently) and it's up to the client to handle it for both cases background/foreground via callback-function in FirebaseMessagingService

    This is according official docs:https://firebase.google.com/docs/cloud-messaging/concept-options

    How can I view the allocation unit size of a NTFS partition in Vista?

    I know this is an old thread, but there's a newer way then having to use fsutil or diskpart.

    Run this powershell command.

    Get-Volume | Format-List AllocationUnitSize, FileSystemLabel

    Convert text to columns in Excel using VBA

    If someone is facing issue using texttocolumns function in UFT. Please try using below function.

    myxl.Workbooks.Open myexcel.xls
    myxl.Application.Visible = false `enter code here`
    set mysheet = myxl.ActiveWorkbook.Worksheets(1)
    Set objRange = myxl.Range("A1").EntireColumn
    Set objRange2 = mysheet.Range("A1")
    objRange.TextToColumns objRange2,1,1, , , , true
    

    Here we are using coma(,) as delimiter.

    glob exclude pattern

    You can use the below method:

    # Get all the files
    allFiles = glob.glob("*")
    # Files starting with eph
    ephFiles = glob.glob("eph*")
    # Files which doesnt start with eph
    noephFiles = []
    for file in allFiles:
        if file not in ephFiles:
            noephFiles.append(file)
    # noepchFiles has all the file which doesnt start with eph.
    
    Thank you.  
    

    MySQL CREATE FUNCTION Syntax

    You have to override your ; delimiter with something like $$ to avoid this kind of error.

    After your function definition, you can set the delimiter back to ;.

    This should work:

    DELIMITER $$
    CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal) 
    RETURNS decimal
    DETERMINISTIC
    BEGIN 
      DECLARE dist decimal;
      SET dist = SQRT(x1 - y1);
      RETURN dist;
    END$$
    DELIMITER ;
    

    How do you reverse a string in place in JavaScript?

    Using Array functions,

    String.prototype.reverse = function(){
        return [].reduceRight.call(this, function(last, secLast){return last + secLast});
    }
    

    Understanding the map function

    Simplifying a bit, you can imagine map() doing something like this:

    def mymap(func, lst):
        result = []
        for e in lst:
            result.append(func(e))
        return result
    

    As you can see, it takes a function and a list, and returns a new list with the result of applying the function to each of the elements in the input list. I said "simplifying a bit" because in reality map() can process more than one iterable:

    If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items.

    For the second part in the question: What role does this play in making a Cartesian product? well, map() could be used for generating the cartesian product of a list like this:

    lst = [1, 2, 3, 4, 5]
    
    from operator import add
    reduce(add, map(lambda i: map(lambda j: (i, j), lst), lst))
    

    ... But to tell the truth, using product() is a much simpler and natural way to solve the problem:

    from itertools import product
    list(product(lst, lst))
    

    Either way, the result is the cartesian product of lst as defined above:

    [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
     (2, 1), (2, 2), (2, 3), (2, 4), (2, 5),
     (3, 1), (3, 2), (3, 3), (3, 4), (3, 5),
     (4, 1), (4, 2), (4, 3), (4, 4), (4, 5),
     (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
    

    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()
    

    Return Index of an Element in an Array Excel VBA

    'To return the position of an element within any-dimension array  
    'Returns 0 if the element is not in the array, and -1 if there is an error  
    Public Function posInArray(ByVal itemSearched As Variant, ByVal aArray As Variant) As Long  
    Dim pos As Long, item As Variant  
    
    posInArray = -1  
    If IsArray(aArray) Then  
        If not IsEmpty(aArray) Then  
            pos = 1  
            For Each item In aArray  
                If itemSearched = item Then  
                    posInArray = pos  
                    Exit Function  
                End If  
                pos = pos + 1  
            Next item  
            posInArray = 0  
        End If  
    End If
    
    End Function
    

    How can I read Chrome Cache files?

    EDIT: The below answer no longer works see here


    Chrome stores the cache as a hex dump. OSX comes with xxd installed, which is a command line tool for converting hex dumps. I managed to recover a jpg from my Chrome's HTTP cache on OSX using these steps:

    1. Goto: chrome://cache
    2. Find the file you want to recover and click on it's link.
    3. Copy the 4th section to your clipboard. This is the content of the file.
    4. Follow the steps on this gist to pipe your clipboard into the python script which in turn pipes to xxd to rebuild the file from the hex dump: https://gist.github.com/andychase/6513075

    Your final command should look like:

    pbpaste | python chrome_xxd.py | xxd -r - image.jpg

    If you're unsure what section of Chrome's cache output is the content hex dump take a look at this page for a good guide: http://www.sparxeng.com/blog/wp-content/uploads/2013/03/chrome_cache_html_report.png

    Image source: http://www.sparxeng.com/blog/software/recovering-images-from-google-chrome-browser-cache

    More info on XXD: http://linuxcommand.org/man_pages/xxd1.html

    Thanks to Mathias Bynens above for sending me in the right direction.

    How to get the last value of an ArrayList

    As stated in the solution, if the List is empty then an IndexOutOfBoundsException is thrown. A better solution is to use the Optional type:

    public class ListUtils {
        public static <T> Optional<T> last(List<T> list) {
            return list.isEmpty() ? Optional.empty() : Optional.of(list.get(list.size() - 1));
        }
    }
    

    As you'd expect, the last element of the list is returned as an Optional:

    var list = List.of(10, 20, 30);
    assert ListUtils.last(list).orElse(-1) == 30;
    

    It also deals gracefully with empty lists as well:

    var emptyList = List.<Integer>of();
    assert ListUtils.last(emptyList).orElse(-1) == -1;
    

    Bootstrap 3 - How to load content in modal body via AJAX?

    In the case where you need to update the same modal with content from different Ajax / API calls here's a working solution.

    $('.btn-action').click(function(){
        var url = $(this).data("url"); 
        $.ajax({
            url: url,
            dataType: 'json',
            success: function(res) {
    
                // get the ajax response data
                var data = res.body;
    
                // update modal content here
                // you may want to format data or 
                // update other modal elements here too
                $('.modal-body').text(data);
    
                // show modal
                $('#myModal').modal('show');
    
            },
            error:function(request, status, error) {
                console.log("ajax call went wrong:" + request.responseText);
            }
        });
    });
    

    Bootstrap 3 Demo
    Bootstrap 4 Demo

    how to parse JSONArray in android

    Here is a better way for doing it. Hope this helps

    protected void onPostExecute(String result) {
                    Log.v(TAG + " result);
    
    
                    if (!result.equals("")) {
    
                        // Set up variables for API Call
                        ArrayList<String> list = new ArrayList<String>();
    
                        try {
                            JSONArray jsonArray = new JSONArray(result);
    
                            for (int i = 0; i < jsonArray.length(); i++) {
    
                                list.add(jsonArray.get(i).toString());
    
                            }//end for
                        } catch (JSONException e) {
                            Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
                            e.printStackTrace();
                        }
    
    
                        adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
                        listView.setAdapter(adapter);
                        listView.setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
                                // ListView Clicked item index
                                int itemPosition = position;
    
                                // ListView Clicked item value
                                String itemValue = (String) listView.getItemAtPosition(position);
    
                                // Show Alert
                                Toast.makeText( ListViewData.this, "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();
                            }
                        });
    
                        adapter.notifyDataSetChanged();
    ...
    

    Combine two pandas Data Frames (join on a common column)

    Joining fails if the DataFrames have some column names in common. The simplest way around it is to include an lsuffix or rsuffix keyword like so:

    restaurant_review_frame.join(restaurant_ids_dataframe, on='business_id', how='left', lsuffix="_review")
    

    This way, the columns have distinct names. The documentation addresses this very problem.

    Or, you could get around this by simply deleting the offending columns before you join. If, for example, the stars in restaurant_ids_dataframe are redundant to the stars in restaurant_review_frame, you could del restaurant_ids_dataframe['stars'].

    How to do a SOAP Web Service call from Java class?

    Or just use Apache CXF's wsdl2java to generate objects you can use.

    It is included in the binary package you can download from their website. You can simply run a command like this:

    $ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl
    

    It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):

    DefaultWebService defaultWebService = new DefaultWebService();
    String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
    System.out.println(res);
    

    There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html

    Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315

    Message: Trying to access array offset on value of type null

    This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

    To check whether the index exists or not you can use isset():

    isset($cOTLdata['char_data'])
    

    Which means the line should look something like this:

    $len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
    

    Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

    Oracle - How to generate script from sql developer

    I did not know about DMBS_METADATA, but your answers prompted me to create a utility to script all objects owned by an Oracle user.

    iptables block access to port 8000 except from IP address

    Another alternative is;

    sudo iptables -A INPUT -p tcp --dport 8000 -s ! 1.2.3.4 -j DROP
    

    I had similar issue that 3 bridged virtualmachine just need access eachother with different combination, so I have tested this command and it works well.

    Edit**

    According to Fernando comment and this link exclamation mark (!) will be placed before than -s parameter:

    sudo iptables -A INPUT -p tcp --dport 8000 ! -s 1.2.3.4 -j DROP
    

    How to check for palindrome using Python logic

    def isPalin(checkWord):
        Hsize = len(lst)/2
        seed = 1
        palind=True
        while seed<Hsize+1:
            #print seed,lst[seed-1], lst [-(seed)]
            if(lst[seed-1] != lst [-seed]):
                palind = False
                break
            seed = seed+1
        return palind
    
    lst = 'testset'
    print lst, isPalin(lst)    
    lst = 'testsest'
    print lst, isPalin(lst) 
    

    Output

    testset True
    testsest False
    

    Automatically enter SSH password with script

    Use public key authentication: https://help.ubuntu.com/community/SSH/OpenSSH/Keys

    In the source host run this only once:

    ssh-keygen -t rsa # ENTER to every field
    ssh-copy-id myname@somehost
    

    That's all, after that you'll be able to do ssh without password.

    how to display a div triggered by onclick event

    function showstuff(boxid){
       document.getElementById(boxid).style.visibility="visible";
    }
    
    <button onclick="showstuff('id_to_show');" />
    

    This will help you, I think.

    Unable to use Intellij with a generated sources folder

    Whoever wrote that plugin screwed up big time. That's not the way to do it!

    Any workaround would be a huge hack, make the plugin developer aware of his bug.

    Sorry, that's the only thing to do.


    OK here's a hack, directly after your plugin's execution, use the antrun plugin to move the directory somewhere else:

    <plugin>
        <artifactId>maven-antrun-plugin</artifactId>
        <version>1.6</version>
        <executions>
          <execution>
            <phase>process-sources</phase>
            <configuration>
              <target>
                <move todir="${project.build.directory}/generated-sources/toolname/com"
                      overwrite="true">
                    <fileset dir="${project.build.directory}/generated-sources/com"/>
                </move>
              </target>
            </configuration>
            <goals>
              <goal>run</goal>
            </goals>
          </execution>
        </executions>
    </plugin>
    

    In this example, toolname should be replaced by anything that uniquely identifies the plugin that created the code and com stands for the root of the created packages. If you have multiple package roots, you probably need multiple <move> tasks.

    But if the plugin adds the folder as source folder, then you're screwed.

    Occurrences of substring in a string

    I'm very surprised no one has mentioned this one liner. It's simple, concise and performs slightly better than str.split(target, -1).length-1

    public static int count(String str, String target) {
        return (str.length() - str.replace(target, "").length()) / target.length();
    }
    

    Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

    I had the problem too.

    Same with most of others above. The problem is caused by huge image.

    Just resize some images, and no need to change any code.

    Adjusting HttpWebRequest Connection Timeout in C#

    I believe that the problem is that the WebRequest measures the time only after the request is actually made. If you submit multiple requests to the same address then the ServicePointManager will throttle your requests and only actually submit as many concurrent connections as the value of the corresponding ServicePoint.ConnectionLimit which by default gets the value from ServicePointManager.DefaultConnectionLimit. Application CLR host sets this to 2, ASP host to 10. So if you have a multithreaded application that submits multiple requests to the same host only two are actually placed on the wire, the rest are queued up.

    I have not researched this to a conclusive evidence whether this is what really happens, but on a similar project I had things were horrible until I removed the ServicePoint limitation.

    Another factor to consider is the DNS lookup time. Again, is my belief not backed by hard evidence, but I think the WebRequest does not count the DNS lookup time against the request timeout. DNS lookup time can show up as very big time factor on some deployments.

    And yes, you must code your app around the WebRequest.BeginGetRequestStream (for POSTs with content) and WebRequest.BeginGetResponse (for GETs and POSTSs). Synchronous calls will not scale (I won't enter into details why, but that I do have hard evidence for). Anyway, the ServicePoint issue is orthogonal to this: the queueing behavior happens with async calls too.

    php execute a background process

    Here is a function to launch a background process in PHP. Finally created one that actually works on Windows too, after a lot of reading and testing different approaches and parameters.

    function LaunchBackgroundProcess($command){
      // Run command Asynchroniously (in a separate thread)
      if(PHP_OS=='WINNT' || PHP_OS=='WIN32' || PHP_OS=='Windows'){
        // Windows
        $command = 'start "" '. $command;
      } else {
        // Linux/UNIX
        $command = $command .' /dev/null &';
      }
      $handle = popen($command, 'r');
      if($handle!==false){
        pclose($handle);
        return true;
      } else {
        return false;
      }
    }
    

    Note 1: On windows, do not use /B parameter as suggested elsewhere. It forces process to run the same console window as start command itself, resulting in the process being processed synchronously. To run the process in a separate thread (asynchronously), do not use /B.

    Note 2: The empty double quotes after start "" are required if the command is a quoted path. start command interprets the first quoted parameter as window title.

    Display PDF file inside my android application

    Highly recommend you check out PDF.js which is able to render PDF documents in a standard a WebView component.

    Also see https://github.com/loosemoose/androidpdf for a sample implementation of this.

    How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

    tv_nsec is the sleep time in nanoseconds. 500000us = 500000000ns, so you want:

    nanosleep((const struct timespec[]){{0, 500000000L}}, NULL);