Programs & Examples On #Database concurrency

Printing an array in C++?

// Just do this, use a vector with this code and you're good lol -Daniel

#include <Windows.h>
#include <iostream>
#include <vector>

using namespace std;


int main()
{

    std::vector<const char*> arry = { "Item 0","Item 1","Item 2","Item 3" ,"Item 4","Yay we at the end of the array"};
    
    if (arry.size() != arry.size() || arry.empty()) {
        printf("what happened to the array lol\n ");
        system("PAUSE");
    }
    for (int i = 0; i < arry.size(); i++)
    {   
        if (arry.max_size() == true) {
            cout << "Max size of array reached!";
        }
        cout << "Array Value " << i << " = " << arry.at(i) << endl;
            
    }
}

Java Serializable Object to Byte Array

Can be done by SerializationUtils, by serialize & deserialize method by ApacheUtils to convert object to byte[] and vice-versa , as stated in @uris answer.

To convert an object to byte[] by serializing:

byte[] data = SerializationUtils.serialize(object);

To convert byte[] to object by deserializing::

Object object = (Object) SerializationUtils.deserialize(byte[] data)

Click on the link to Download org-apache-commons-lang.jar

Integrate .jar file by clicking:

FileName -> Open Medule Settings -> Select your module -> Dependencies -> Add Jar file and you are done.

Hope this helps.

How can I change text color via keyboard shortcut in MS word 2010

For Word 2010 and 2013, go to File > Options > Customize Ribbon > Keyboard Shortcuts > All Commands (in left list) > Color: (in right list) -- at this point, you type in the short cut (such as Alt+r) and select the color (such as red). (This actually goes back to 2003 but I don't have that installed to provide the pathway.)

How do I reference to another (open or closed) workbook, and pull values back, in VBA? - Excel 2007

You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-

(untested code)

Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")

' now you can manipulate the data in the workbook anyway you want, e.g. '

Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value

Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False

' etc '

Call wbk.Close(False)

Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.

In java how to get substring from a string till a character c?

Here is code which returns a substring from a String until any of a given list of characters:

/**
 * Return a substring of the given original string until the first appearance
 * of any of the given characters.
 * <p>
 * e.g. Original "ab&cd-ef&gh"
 * 1. Separators {'&', '-'}
 * Result: "ab"
 * 2. Separators {'~', '-'}
 * Result: "ab&cd"
 * 3. Separators {'~', '='}
 * Result: "ab&cd-ef&gh"
 *
 * @param original   the original string
 * @param characters the separators until the substring to be considered
 * @return the substring or the original string of no separator exists
 */
public static String substringFirstOf(String original, List<Character> characters) {
    return characters.stream()
            .map(original::indexOf)
            .filter(min -> min > 0)
            .reduce(Integer::min)
            .map(position -> original.substring(0, position))
            .orElse(original);
}

What is the precise meaning of "ours" and "theirs" in git?

From git checkout's usage:

-2, --ours            checkout our version for unmerged files
-3, --theirs          checkout their version for unmerged files
-m, --merge           perform a 3-way merge with the new branch

When resolving merge conflicts, you can do git checkout --theirs some_file, and git checkout --ours some_file to reset the file to the current version and the incoming versions respectively.

If you've done git checkout --ours some_file or git checkout --theirs some_file and would like to reset the file to the 3-way merge version of the file, you can do git checkout --merge some_file.

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

if else statement in AngularJS templates

A possibility for Angular: I had to include an if - statement in the html part, I had to check if all variables of an URL that I produce are defined. I did it the following way and it seems to be a flexible approach. I hope it will be helpful for somebody.

The html part in the template:

    <div  *ngFor="let p of poemsInGrid; let i = index" >
        <a [routerLink]="produceFassungsLink(p[0],p[3])" routerLinkActive="active">
    </div>

And the typescript part:

  produceFassungsLink(titel: string, iri: string) {
      if(titel !== undefined && iri !== undefined) {
         return titel.split('/')[0] + '---' + iri.split('raeber/')[1];
      } else {
         return 'Linkinformation has not arrived yet';
      }
  }

Thanks and best regards,

Jan

Determine the process pid listening on a certain port

I wanted to programmatically -- using only Bash -- kill the process listening on a given port.

Let's say the port is 8089, then here is how I did it:

badPid=$(netstat --listening --program --numeric --tcp | grep "::8089" | awk '{print $7}' | awk -F/ '{print $1}' | head -1)
kill -9 $badPid

I hope this helps someone else! I know it is going to help my team.

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Building on what is mentioned in the comments, the simplest solution would be:

@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {

    //whatever

}

class SomeDto {

   private List<WhateverBudgerPerDateDTO> budgetPerDate;


  //getters setters
}

The solution assumes that the HTTP request you are creating actually has

Content-Type:application/json instead of text/plain

Skip first line(field) in loop using CSV file?

There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:

with open(filename, 'r') as f:
    next(f)
    for line in f:

and:

with open(filename,'r') as f:
    lines = f.readlines()[1:]

Git - Ignore files during merge

I got over this issue by using git merge command with the --no-commit option and then explicitly removed the staged file and ignore the changes to the file. E.g.: say I want to ignore any changes to myfile.txt I proceed as follows:

git merge --no-ff --no-commit <merge-branch>
git reset HEAD myfile.txt
git checkout -- myfile.txt
git commit -m "merged <merge-branch>"

You can put statements 2 & 3 in a for loop, if you have a list of files to skip.

How do I multiply each element in a list by a number?

from functools import partial as p
from operator import mul
map(p(mul,5),my_list)

is one way you could do it ... your teacher probably knows a much less complicated way that was probably covered in class

Creating random colour in Java?

import android.graphics.Color;

import java.util.Random;

public class ColorDiagram {
    // Member variables (properties about the object)
    public String[] mColors = {
            "#39add1", // light blue
            "#3079ab", // dark blue
            "#c25975", // mauve
            "#e15258", // red
            "#f9845b", // orange
            "#838cc7", // lavender
            "#7d669e", // purple
            "#53bbb4", // aqua
            "#51b46d", // green
            "#e0ab18", // mustard
            "#637a91", // dark gray
            "#f092b0", // pink
            "#b7c0c7"  // light gray
    };

    // Method (abilities: things the object can do)
    public int getColor() {
        String color = "";

        // Randomly select a fact
        Random randomGenerator = new Random(); // Construct a new Random number generator
        int randomNumber = randomGenerator.nextInt(mColors.length);

        color = mColors[randomNumber];
        int colorAsInt = Color.parseColor(color);

        return colorAsInt;
    }
}

Html.DropDownList - Disabled/Readonly

I've create this answer after referring above all comments & answers. This will resolve the dropdown population error even it get disabled.

Step 01

_x000D_
_x000D_
Html.DropDownList("Types", Model.Types, new {@readonly="readonly"})
_x000D_
_x000D_
_x000D_

Step 02 This is css pointerevent remove code.

_x000D_
_x000D_
<style type="text/css">_x000D_
    #Types {_x000D_
        pointer-events:none;_x000D_
    }_x000D_
</style>
_x000D_
_x000D_
_x000D_ Then you can have expected results

Tested & Proven

Writing a Python list of lists to a csv file

In case of exporting lll list of lists of lists to .csv, this will work in Python3:

import csv
with open("output.csv", "w") as f:
    writer = csv.writer(f)
    for element in lll:
        writer.writerows(element)

What does 'public static void' mean in Java?

Considering the typical top-level class. Only public and no modifier access modifiers may be used at the top level so you'll either see public or you won't see any access modifier at all.

`static`` is used because you may not have a need to create an actual object at the top level (but sometimes you will want to so you may not always see/use static. There are other reasons why you wouldn't include static too but this is the typical one at the top level.)

void is used because usually you're not going to be returning a value from the top level (class). (sometimes you'll want to return a value other than NULL so void may not always be used either especially in the case when you have declared, initialized an object at the top level that you are assigning some value to).

Disclaimer: I'm a newbie myself so if this answer is wrong in any way please don't hang me. By day I'm a tech recruiter not a developer; coding is my hobby. Also, I'm always open to constructive criticism and love to learn so please feel free to point out any errors.

How can I convert a Unix timestamp to DateTime and vice versa?

DateTime unixEpoch = DateTime.ParseExact("1970-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
DateTime convertedTime = unixEpoch.AddMilliseconds(unixTimeInMillisconds);

Of course, one can make unixEpoch a global static, so it only needs to appear once in your project, and one can use AddSeconds if the UNIX time is in seconds.

To go the other way:

double unixTimeInMilliseconds = timeToConvert.Subtract(unixEpoch).TotalMilliseconds;

Truncate to Int64 and/or use TotalSeconds as needed.

How to trim leading and trailing white spaces of a string?

A quick string "GOTCHA" with JSON Unmarshall which will add wrapping quotes to strings.

(example: the string value of {"first_name":" I have whitespace "} will convert to "\" I have whitespace \"")

Before you can trim anything, you'll need to remove the extra quotes first:

playground example

// ScrubString is a string that might contain whitespace that needs scrubbing.
type ScrubString string

// UnmarshalJSON scrubs out whitespace from a valid json string, if any.
func (s *ScrubString) UnmarshalJSON(data []byte) error {
    ns := string(data)
    // Make sure we don't have a blank string of "\"\"".
    if len(ns) > 2 && ns[0] != '"' && ns[len(ns)] != '"' {
        *s = ""
        return nil
    }
    // Remove the added wrapping quotes.
    ns, err := strconv.Unquote(ns)
    if err != nil {
        return err
    }
    // We can now trim the whitespace.
    *s = ScrubString(strings.TrimSpace(ns))

    return nil
}

Creating object with dynamic keys

In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.

The syntax is:

var obj = {
  [myKey]: value,
}

If applied to the OP's scenario, it would turn into:

stuff = function (thing, callback) {
  var inputs  = $('div.quantity > input').map(function(){
    return {
      [this.attr('name')]: this.attr('value'),
    };
  }) 

  callback(null, inputs);
}

Note: A transpiler is still required for browser compatiblity.

Using Babel or Google's traceur, it is possible to use this syntax today.


In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.

To use a "dynamic" key, you have to use bracket notation:

var obj = {};
obj[myKey] = value;

In your case:

stuff = function (thing, callback) {
  var inputs  = $('div.quantity > input').map(function(){
    var key   = this.attr('name')
     ,  value = this.attr('value')
     ,  ret   = {};

     ret[key] = value;
     return ret;
  }) 

  callback(null, inputs);
}

Procedure or function !!! has too many arguments specified

Yet another cause of this error is when you are calling the stored procedure from code, and the parameter type in code does not match the type on the stored procedure.

How to set image to fit width of the page using jsPDF?

This is how I've achieved in Reactjs.

Main problem were ratio and scale If you do a quick window.devicePixelRatio, it's default value is 2 which was causing the half image issue.

const printDocument = () => {
  const input = document.getElementById('divToPrint');
  const divHeight = input.clientHeight
  const divWidth = input.clientWidth
  const ratio = divHeight / divWidth;

  html2canvas(input, { scale: '1' }).then((canvas) => {
    const imgData = canvas.toDataURL('image/jpeg');
    const pdfDOC = new JSPDF("l", "mm", "a0"); //  use a4 for smaller page

    const width = pdfDOC.internal.pageSize.getWidth();
    let height = pdfDOC.internal.pageSize.getHeight();
    height = ratio * width;

    pdfDOC.addImage(imgData, 'JPEG', 0, 0, width - 20, height - 10);
    pdfDOC.save('summary.pdf');   //Download the rendered PDF.
  })
}

Fragment onCreateView and onActivityCreated called twice

Ok, Here's what I found out.

What I didn't understand is that all fragments that are attached to an activity when a config change happens (phone rotates) are recreated and added back to the activity. (which makes sense)

What was happening in the TabListener constructor was the tab was detached if it was found and attached to the activity. See below:

mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
    if (mFragment != null && !mFragment.isDetached()) {
        Log.d(TAG, "constructor: detaching fragment " + mTag);
        FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
        ft.detach(mFragment);
        ft.commit();
    }

Later in the activity onCreate the previously selected tab was selected from the saved instance state. See below:

if (savedInstanceState != null) {
    bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
    Log.d(TAG, "FragmentTabs.onCreate tab: " + savedInstanceState.getInt("tab"));
    Log.d(TAG, "FragmentTabs.onCreate number: " + savedInstanceState.getInt("number"));
}

When the tab was selected it would be reattached in the onTabSelected callback.

public void onTabSelected(Tab tab, FragmentTransaction ft) {
    if (mFragment == null) {
        mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
        Log.d(TAG, "onTabSelected adding fragment " + mTag);
        ft.add(android.R.id.content, mFragment, mTag);
    } else {
        Log.d(TAG, "onTabSelected attaching fragment " + mTag);
        ft.attach(mFragment);
    }
}

The fragment being attached is the second call to the onCreateView and onActivityCreated methods. (The first being when the system is recreating the acitivity and all attached fragments) The first time the onSavedInstanceState Bundle would have saved data but not the second time.

The solution is to not detach the fragment in the TabListener constructor, just leave it attached. (You still need to find it in the FragmentManager by it's tag) Also, in the onTabSelected method I check to see if the fragment is detached before I attach it. Something like this:

public void onTabSelected(Tab tab, FragmentTransaction ft) {
            if (mFragment == null) {
                mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
                Log.d(TAG, "onTabSelected adding fragment " + mTag);
                ft.add(android.R.id.content, mFragment, mTag);
            } else {

                if(mFragment.isDetached()) {
                    Log.d(TAG, "onTabSelected attaching fragment " + mTag);
                    ft.attach(mFragment);
                } else {
                    Log.d(TAG, "onTabSelected fragment already attached " + mTag);
                }
            }
        }

Identifier not found error on function call

Add this line before main function:

void swapCase (char* name);

int main()
{
   ...
   swapCase(name);    // swapCase prototype should be known at this point
   ...
}

This is called forward declaration: compiler needs to know function prototype when function call is compiled.

Change the "From:" address in Unix "mail"

echo "body" | mail -S [email protected] "Hello"

-S lets you specify lots of string options, by far the easiest way to modify headers and such.

How do I add a bullet symbol in TextView?

Prolly a better solution out there somewhere, but this is what I did.

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
        <TableRow>    
            <TextView
                android:layout_column="1"
                android:text="•"></TextView>
            <TextView
                android:layout_column="2"
                android:layout_width="wrap_content"
                android:text="First line"></TextView>
        </TableRow>
        <TableRow>    
            <TextView
                android:layout_column="1"
                android:text="•"></TextView>
            <TextView
                android:layout_column="2"
                android:layout_width="wrap_content"
                android:text="Second line"></TextView>
        </TableRow>
  </TableLayout>

It works like you want, but a workaround really.

Outline radius?

I like this way.

.circle:before {
   content: "";
   width: 14px;
   height: 14px;
   border: 3px solid #fff;
   background-color: #ced4da;
   border-radius: 7px;
   display: inline-block;
   margin-bottom: -2px;
   margin-right: 7px;
   box-shadow: 0px 0px 0px 1px #ced4da;
}

It will create gray circle with wit border around it and again 1px around border!

How can one run multiple versions of PHP 5.x on a development LAMP server?

I have several projects running on my box. If you have already installed more than one version, this bash script should help you easily switch. At the moment I have php5, php5.6, and php7.0 which I often swtich back and forth depending on the project I am working on. Here is my code.

Feel free to copy. Make sure you understand how the code works. This is for the webhostin. my local box my mods are stored at /etc/apache2/mods-enabled/

    #!/bin/bash
# This file is for switching php versions.  
# To run this file you must use bash, not sh
# 
    # OS: Ubuntu 14.04 but should work on any linux
# Example: bash phpswitch.sh 7.0
# Written by Daniel Pflieger
# growlingflea at g mail dot com

NEWVERSION=$1  #this is the git directory target

#get the active php enabled mod by getting the array of files and store
#it to a variable
VAR=$(ls /etc/apache2/mods-enabled/php*)

#parse the returned variables and get the version of php that is active.
IFS=' ' read -r -a array <<< "$VAR"
array[0]=${array[0]#*php}
array[0]=${array[0]%.conf}


#confirm that the newversion veriable isn't empty.. if it is tell user 
#current version and exit
if [ "$NEWVERSION" = "" ]; then
echo current version is ${array[0]}.  To change version please use argument
exit 1
fi 

OLDVERSION=${array[0]}
#confirm to the user this is what they want to do
echo "Update php"  ${OLDVERSION} to ${NEWVERSION}


#give the user the opportunity to use CTRL-C to exit ot just hit return
read x

#call a2dismod function: this deactivate the current php version
sudo a2dismod php${OLDVERSION}

#call the a2enmod version.  This enables the new mode
sudo a2enmod php${NEWVERSION} 

echo "Restart service??"
read x

#restart apache
sudo service apache2 restart

Link and execute external JavaScript file hosted on GitHub

Above answers clearly answer the question but I want to provide another alternative - A different view/approach to solve the similar problem.

You can also use browser extension to remove X-Content-Type-Options response header for raw.githubusercontent.com files. There are couple of browser extensions to modify response headers.

  1. Requestly: Chrome + Firefox
  2. Modify Headers: Firefox

If you use Requestly, I can suggest two solutions

Solution 1: Use Modify Headers Rule and remove the response header

Steps

  1. Install Requestly from http://www.requestly.in
  2. Go to Rules Page
  3. Click on Add Icon to create a rule
  4. Select Modify Headers
  5. Give a Name and Descripton
  6. Select Remove -> Response -> X-Content-Type-Options
  7. In Source field, enter Url -> Contains -> raw.githubusercontent.com

Solution 2: Use Replace host Rule

  1. Install Requestly from http://www.requestly.in
  2. Go to Rules Page
  3. Click on Add Icon to create a rule
  4. Replace raw.githubusercontent.com with rawgit.com

Check this screenshot for more detailsenter image description here

How to test

We created a simple JS Fiddle to test out if we can use raw github files as scripts in our code. Here is the Fiddle with the following code

<center id="msg"></center>

<script src="https://raw.githubusercontent.com/sachinjain024/practicebook/master/web-extensions-master/storage/background.js"></script>
<script>
try {
  if (typeof BG.Methods !== 'undefoned') {
    document.getElementById('msg').innerHTML = 'Script evaluated successfully!';
  }
} catch (e) {
  document.getElementById('msg').innerHTML = 'Problem evaluating script';
}
</script>

If you see Script evaluated successfully!, It means you are able to use raw github file in your code Otherwise Problem evaluating script indicates that there is some problem while executing script from raw github source.

I also wrote an article on Requestly blog about this. Please refer it for more details.

Hope it helps!!

Disclaimer: I am author of Requestly So you can blame for anything you don't like.

How to filter in NaN (pandas)?

This doesn't work because NaN isn't equal to anything, including NaN. Use pd.isnull(df.var2) instead.

How to merge remote changes at GitHub?

When I got this error, I backed up my entire project folder. Then I did something like

$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master

...depending on your branch name (if it's not master).

Then I did git pull --rebase. After that, I replaced the pulled files with my backed-up project's files. Now I am ready to commit my changes again and push.

Build android release apk on Phonegap 3.x CLI

Following up to @steven-anderson you can also configure passwords inside the ant.properties, so the process can be fully automated

so if you put in platform\android\ant.properties the following

key.store=../../yourCertificate.jks
key.store.password=notSoSecretPassword
key.alias=userAlias
key.alias.password=notSoSecretPassword

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

Note: I found this question (varchar(255) v tinyblob v tinytext), which says that VARCHAR(n) requires n+1 bytes of storage for n<=255, n+2 bytes of storage for n>255. Is this the only reason? That seems kind of arbitrary, since you would only be saving two bytes compared to VARCHAR(256), and you could just as easily save another two bytes by declaring it VARCHAR(253).

No. you don't save two bytes by declaring 253. The implementation of the varchar is most likely a length counter and a variable length, nonterminated array. This means that if you store "hello" in a varchar(255) you will occupy 6 bytes: one byte for the length (the number 5) and 5 bytes for the five letters.

PHP $_POST not working?

Instead of using $_POST, use $_REQUEST:

HTML:

<form action="" method="post">
  <input type="text" name="firstname">
  <input type="submit" name="submit" value="Submit">
</form>

PHP:

if(isset($_REQUEST['submit'])){
  $test = $_REQUEST['firstname'];
  echo $test;
}

MySQL: How to add one day to datetime field in query

If you are able to use NOW() this would be simplest form:

SELECT * FROM `fab_scheduler` WHERE eventdate>=(NOW() - INTERVAL 1 DAY)) AND eventdate<NOW() ORDER BY eventdate DESC;

With MySQL 5.6+ query abowe should do. Depending on sql server, You may be required to use CURRDATE() instead of NOW() - which is alias for DATE(NOW()) and will return only date part of datetime data type;

Use of "instanceof" in Java

instanceof is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

Read more from the Oracle language definition here.

How to get CRON to call in the correct PATHs

Should you use webmin then these are the steps how to set the PATH value:

System
  -> Scheduled Cron Jobs
       -> Create a new environment variable
            -> For user: <Select the user name>
            -> Variable name: PATH
            -> Value: /usr/bin:/bin:<your personal path>
            -> Add environment variable: Before all Cron jobs for user

Which keycode for escape key with jQuery

A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.

http://jaywcjlove.github.io/hotkeys/

hotkeys('enter,esc', function(event,handler){
    switch(handler.key){
        case "enter":$('.save').click();break;
        case "esc":$('.cancel').click();break;
    }
});

hotkeys understands the following modifiers: ?,shiftoption?altctrlcontrolcommand, and ?.

The following special keys can be used for shortcuts:backspacetab,clear,enter,return,esc,escape,space,up,down,left,right,home,end,pageup,pagedown,del,delete andf1 throughf19.

How to Set JPanel's Width and Height?

Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);

SSH SCP Local file to Remote in Terminal Mac Os X

At first, you need to add : after the IP address to indicate the path is following:

scp magento.tar.gz [email protected]:/var/www

I don't think you need to sudo the scp. In this case it doesn't affect the remote machine, only the local command.

Then if your user@xx.x.x.xx doesn't have write access to /var/www then you need to do it in 2 times:

Copy to remote server in your home folder (: represents your remote home folder, use :subfolder/ if needed, or :/home/user/ for full path):

scp magento.tar.gz [email protected]:

Then SSH and move the file:

ssh [email protected]
sudo mv magento.tar.gz /var/www

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

Well actually your only need $.each to get all values, it will help you jsfiddle.net/NdQbw/5

<div class="divright">
            <select id="drp_Books_Ill_Illustrations" class="leaderMultiSelctdropdown Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
                <option value=" ">No illustrations</option>
                <option value="a" selected>Illustrations</option>
                <option value="b">Maps</option>
                <option value="c" selected>selectedPortraits</option>
            </select>
    </div>

<div class="divright">
        <select id="drp_Books_Ill_Illustrations1" class=" Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
            <option value=" ">No illustrations</option>
            <option value="a">Illustrations</option>
            <option value="b">Maps</option>
            <option value="c">selectedPortraits</option>
        </select>
</div>

<button class="getValue">Get Value</button>
<button  class="setValue"> Set  value </button>

<div class="divright">
        <select id="drp_Books_Ill_Illustrations2" class="leaderMultiSelctdropdown Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
            <option value=" ">No illustrations</option>
            <option value="a" selected>Illustrations</option>
            <option value="b">Maps</option>
            <option value="c" selected>selectedPortraits</option>
        </select>
</div>

<div class="divright">
        <select id="drp_Books_Ill_Illustrations3" class=" Books_Illustrations" name="drp_Books_Ill_Illustrations" multiple="">
            <option value=" ">No illustrations</option>
            <option value="a">Illustrations</option>
            <option value="b">Maps</option>
            <option value="c">selectedPortraits</option>
        </select>
</div>

<button class="getValue1">Get Value</button>
<button  class="setValue1"> Set  value </button>

The script:

 var selectedValues = new Array();
    selectedValues[0] = "a";
    selectedValues[1] = "c";

$(".getValue").click(function() {
    alert($(".leaderMultiSelctdropdown").val());
});
$(".setValue").click(function() {
   $(".Books_Illustrations").val(selectedValues);
});

$('#drp_Books_Ill_Illustrations2, #drp_Books_Ill_Illustrations3').select2();


$(".getValue1").click(function() {
    alert($(".leaderMultiSelctdropdown").val());
});

$(".setValue1").click(function() {
    //You need a id for set values
    $.each($(".Books_Illustrations"), function(){
            $(this).select2('val', selectedValues);
    });
});

Setting focus to a textbox control

create a textbox:

 <TextBox Name="tb">
 ..hello..
</TextBox>

focus() ---> it is used to set input focus to the textbox control

tb.focus()

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

How to dismiss keyboard for UITextView with return key?

function to hideQueboard.

- (void)HideQueyboard
{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder)   to:nil from:nil forEvent:nil];
}

Centering a Twitter Bootstrap button

If you don't mind a bit more markup, this would work:

<div class="centered">
    <button class="btn btn-large btn-primary" type="button">Submit</button>
</div>

With the corresponding CSS rule:

.centered
{
    text-align:center;
}

I have to look at the CSS rules for the btn class, but I don't think it specifies a width, so auto left & right margins wouldn't work. If you added one of the span or input- rules to the button, auto margins would work, though.

Edit:

Confirmed my initial thought; the btn classes do not have a width defined, so you can't use auto side margins. Also, as @AndrewM notes, you could simply use the text-center class instead of creating a new ruleset.

Python Library Path

You can also make additions to this path with the PYTHONPATH environment variable at runtime, in addition to:

import sys
sys.path.append('/home/user/python-libs')

What is a file with extension .a?

.a files are created with the ar utility, and they are libraries. To use it with gcc, collect all .a files in a lib/ folder and then link with -L lib/ and -l<name of specific library>.

Collection of all .a files into lib/ is optional. Doing so makes for better looking directories with nice separation of code and libraries, IMHO.

Split string into strings by length?

# spliting a string by the length of the string

def len_split(string,sub_string):
    n,sub,str1=list(string),len(sub_string),')/^0*/-'
    for i in range(sub,len(n)+((len(n)-1)//sub),sub+1):
        n.insert(i,str1)   
    n="".join(n)
    n=n.split(str1)
    return n

x="divyansh_looking_for_intership_actively_contact_Me_here"
sub="four"
print(len_split(x,sub))

# Result-> ['divy', 'ansh', 'tiwa', 'ri_l', 'ooki', 'ng_f', 'or_i', 'nter', 'ship', '_con', 'tact', '_Me_', 'here']

UITableView load more when scrolling to bottom like Facebook application

Details

  • Swift 5.1, Xcode 11.2.1

Solution

Worked with UIScrollView / UICollectionView / UITableView

import UIKit

class LoadMoreActivityIndicator {

    private let spacingFromLastCell: CGFloat
    private let spacingFromLastCellWhenLoadMoreActionStart: CGFloat
    private weak var activityIndicatorView: UIActivityIndicatorView?
    private weak var scrollView: UIScrollView?

    private var defaultY: CGFloat {
        guard let height = scrollView?.contentSize.height else { return 0.0 }
        return height + spacingFromLastCell
    }

    deinit { activityIndicatorView?.removeFromSuperview() }

    init (scrollView: UIScrollView, spacingFromLastCell: CGFloat, spacingFromLastCellWhenLoadMoreActionStart: CGFloat) {
        self.scrollView = scrollView
        self.spacingFromLastCell = spacingFromLastCell
        self.spacingFromLastCellWhenLoadMoreActionStart = spacingFromLastCellWhenLoadMoreActionStart
        let size:CGFloat = 40
        let frame = CGRect(x: (scrollView.frame.width-size)/2, y: scrollView.contentSize.height + spacingFromLastCell, width: size, height: size)
        let activityIndicatorView = UIActivityIndicatorView(frame: frame)
        if #available(iOS 13.0, *)
        {
            activityIndicatorView.color = .label
        }
        else
        {
            activityIndicatorView.color = .black
        }
        activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin]
        activityIndicatorView.hidesWhenStopped = true
        scrollView.addSubview(activityIndicatorView)
        self.activityIndicatorView = activityIndicatorView
    }

    private var isHidden: Bool {
        guard let scrollView = scrollView else { return true }
        return scrollView.contentSize.height < scrollView.frame.size.height
    }

    func start(closure: (() -> Void)?) {
        guard let scrollView = scrollView, let activityIndicatorView = activityIndicatorView else { return }
        let offsetY = scrollView.contentOffset.y
        activityIndicatorView.isHidden = isHidden
        if !isHidden && offsetY >= 0 {
            let contentDelta = scrollView.contentSize.height - scrollView.frame.size.height
            let offsetDelta = offsetY - contentDelta
            
            let newY = defaultY-offsetDelta
            if newY < scrollView.frame.height {
                activityIndicatorView.frame.origin.y = newY
            } else {
                if activityIndicatorView.frame.origin.y != defaultY {
                    activityIndicatorView.frame.origin.y = defaultY
                }
            }

            if !activityIndicatorView.isAnimating {
                if offsetY > contentDelta && offsetDelta >= spacingFromLastCellWhenLoadMoreActionStart && !activityIndicatorView.isAnimating {
                    activityIndicatorView.startAnimating()
                    closure?()
                }
            }

            if scrollView.isDecelerating {
                if activityIndicatorView.isAnimating && scrollView.contentInset.bottom == 0 {
                    UIView.animate(withDuration: 0.3) { [weak self] in
                        if let bottom = self?.spacingFromLastCellWhenLoadMoreActionStart {
                            scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: bottom, right: 0)
                        }
                    }
                }
            }
        }
    }

    func stop(completion: (() -> Void)? = nil) {
        guard let scrollView = scrollView , let activityIndicatorView = activityIndicatorView else { return }
        let contentDelta = scrollView.contentSize.height - scrollView.frame.size.height
        let offsetDelta = scrollView.contentOffset.y - contentDelta
        if offsetDelta >= 0 {
            UIView.animate(withDuration: 0.3, animations: {
                scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            }) { _ in completion?() }
        } else {
            scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            completion?()
        }
        activityIndicatorView.stopAnimating()
    }
}

Usage

init

activityIndicator = LoadMoreActivityIndicator(scrollView: tableView, spacingFromLastCell: 10, spacingFromLastCellWhenLoadMoreActionStart: 60)

handling

extension ViewController: UITableViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        activityIndicator.start {
            DispatchQueue.global(qos: .utility).async {
                sleep(3)
                DispatchQueue.main.async { [weak self] in
                    self?.activityIndicator.stop()
                }
            }
        }
    }
}

Full Sample

Do not forget to paste the solution code.

import UIKit

class ViewController: UIViewController {
    
    fileprivate var activityIndicator: LoadMoreActivityIndicator!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView(frame: view.frame)
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        
        tableView.dataSource = self
        tableView.delegate = self
        tableView.tableFooterView = UIView()
        activityIndicator = LoadMoreActivityIndicator(scrollView: tableView, spacingFromLastCell: 10, spacingFromLastCellWhenLoadMoreActionStart: 60)
    }
}

extension ViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 30
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "\(indexPath)"
        return cell
    }
}

extension ViewController: UITableViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        activityIndicator.start {
            DispatchQueue.global(qos: .utility).async {
                for i in 0..<3 {
                    print("!!!!!!!!! \(i)")
                    sleep(1)
                }
                DispatchQueue.main.async { [weak self] in
                    self?.activityIndicator.stop()
                }
            }
        }
    }
}

Result

enter image description here

newline in <td title="">

I use the jQuery clueTip plugin for this.

How to get current working directory in Java?

If you want the absolute path of the current source code, my suggestion is:

String internalPath = this.getClass().getName().replace(".", File.separator);
String externalPath = System.getProperty("user.dir")+File.separator+"src";
String workDir = externalPath+File.separator+internalPath.substring(0, internalPath.lastIndexOf(File.separator));

Why and how to fix? IIS Express "The specified port is in use"

If netstat doesn't show anything, try a reboot.

For me, nothing appeared in netstat for my port. I tried closing Google Chrome browser windows as @Clangon and @J.T. Taylor suggested, but to no avail.

In the end a system reboot worked, however, so I can only assume that something else was secretly holding the port open. Or perhaps it just took longer than I was prepared to wait for the ports to be released after Chrome shut down.

How to do joins in LINQ on multiple fields in single join

Using the join operator you can only perform equijoins. Other types of joins can be constructed using other operators. I'm not sure whether the exact join you are trying to do would be easier using these methods or by changing the where clause. Documentation on the join clause can be found here. MSDN has an article on join operations with multiple links to examples of other joins, as well.

img tag displays wrong orientation

save as png solved the problem for me.

How To Run PHP From Windows Command Line in WAMPServer

You can run php pages using php.exe create some php file with php code and in the cmd write "[PATH to php.ext]\php.exe [path_to_file]\file.php"

Why does NULL = NULL evaluate to false in SQL server

null is unknown in sql so we cant expect two unknowns to be same.

However you can get that behavior by setting ANSI_NULLS to Off(its On by Default) You will be able to use = operator for nulls

SET ANSI_NULLS off
if null=null
print 1
else 
print 2
set ansi_nulls on
if null=null
print 1
else 
print 2

Remove an item from array using UnderscoreJS

Please exercise care if you are filtering strings and looking for case insensitive filters. _.without() is case sensitive. You can also use _.reject() as shown below.

var arr = ["test","test1","test2"];

var filtered = _.filter(arr, function(arrItem) {
    return arrItem.toLowerCase() !== "TEST".toLowerCase();
});
console.log(filtered);
// ["test1", "test2"]

var filtered1 = _.without(arr,"TEST");
console.log(filtered1);
// ["test", "test1", "test2"]

var filtered2 = _.reject(arr, function(arrItem){ 
    return arrItem.toLowerCase() === "TEST".toLowerCase();
});
console.log(filtered2);
// ["test1", "test2"]

Javascript date regex DD/MM/YYYY

I use this function for dd/mm/yyyy format :

// (new Date()).fromString("3/9/2013") : 3 of september
// (new Date()).fromString("3/9/2013", false) : 9 of march
Date.prototype.fromString = function(str, ddmmyyyy) {
    var m = str.match(/(\d+)(-|\/)(\d+)(?:-|\/)(?:(\d+)\s+(\d+):(\d+)(?::(\d+))?(?:\.(\d+))?)?/);
    if(m[2] == "/"){
        if(ddmmyyyy === false)
            return new Date(+m[4], +m[1] - 1, +m[3], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
        return new Date(+m[4], +m[3] - 1, +m[1], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
    }
    return new Date(+m[1], +m[3] - 1, +m[4], m[5] ? +m[5] : 0, m[6] ? +m[6] : 0, m[7] ? +m[7] : 0, m[8] ? +m[8] * 100 : 0);
}

How to set underline text on textview?

Try this,

tv.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);

form action with javascript

Absolutely valid.

    <form action="javascript:alert('Hello there, I am being submitted');">
        <button type="submit">
            Let's do it
        </button>
    </form>
    <!-- Tested in Firefox, Chrome, Edge and Safari -->

So for a short answer: yes, this is an option, and a nice one. It says "when submitted, please don't go anywhere, just run this script" - quite to the point.

A minor improvement

To let the event handler know which form we're dealing with, it would seem an obvious way to pass on the sender object:

    <form action="javascript:myFunction(this)">  <!-- should work, but it won't -->

But instead, it will give you undefined. You can't access it because javascript: links live in a separate scope. Therefore I'd suggest the following format, it's only 13 characters more and works like a charm:

    <form action="javascript:;" onsubmit="myFunction(this)">  <!-- now you have it! -->

... now you can access the sender form properly. (You can write a simple "#" as action, it's quite common - but it has a side effect of scrolling to the top when submitting.)

Again, I like this approach because it's effortless and self-explaining. No "return false", no jQuery/domReady, no heavy weapons. It just does what it seems to do. Surely other methods work too, but for me, this is The Way Of The Samurai.

A note on validation

Forms only get submitted if their onsubmit event handler returns something truthy, so you can easily run some preemptive checks:

    <form action="/something.php" onsubmit="return isMyFormValid(this)">

Now isMyFormValid will run first, and if it returns false, server won't even be bothered. Needless to say, you will have to validate on server side too, and that's the more important one. But for quick and convenient early detection this is fine.

Why does this "Slow network detected..." log appear in Chrome?

I have network throttling disabled but started to get this error today on a 75mb/s business connection...

To fix it in my build of Chrome 60.0.3112.90 (Official Build) (64-bit) I opened the DevTools then navigated to the DevTools Settings then ticked 'Log XMLHttpRequests', unticked 'User messages only' and 'Hide network messages'

How to pad zeroes to a string?

Strings:

>>> n = '4'
>>> print(n.zfill(3))
004

And for numbers:

>>> n = 4
>>> print(f'{n:03}') # Preferred method, python >= 3.6
004
>>> print('%03d' % n)
004
>>> print(format(n, '03')) # python >= 2.6
004
>>> print('{0:03d}'.format(n))  # python >= 2.6 + python 3
004
>>> print('{foo:03d}'.format(foo=n))  # python >= 2.6 + python 3
004
>>> print('{:03d}'.format(n))  # python >= 2.7 + python3
004

String formatting documentation.

Sum one number to every element in a list (or array) in Python

try this. (I modified the example on the purpose of making it non trivial)

import operator
import numpy as np

n=10
a = list(range(n))
a1 = [1]*len(a)
an = np.array(a)

operator.add is almost more than two times faster

%timeit map(operator.add, a, a1)

than adding with numpy

%timeit an+1

How to read GET data from a URL using JavaScript?

location.search https://developer.mozilla.org/en/DOM/window.location

although most use some kind of parsing routine to read query string parameters.

here's one http://safalra.com/web-design/javascript/parsing-query-strings/

Android Studio does not show layout preview

  1. Clean Project
  2. Rebuild Project
  3. Invalidate Caches / Restart

Android: How can I validate EditText input?

TextWatcher is a bit verbose for my taste, so I made something a bit easier to swallow:

public abstract class TextValidator implements TextWatcher {
    private final TextView textView;

    public TextValidator(TextView textView) {
        this.textView = textView;
    }

    public abstract void validate(TextView textView, String text);

    @Override
    final public void afterTextChanged(Editable s) {
        String text = textView.getText().toString();
        validate(textView, text);
    }

    @Override
    final public void beforeTextChanged(CharSequence s, int start, int count, int after) { /* Don't care */ }

    @Override
    final public void onTextChanged(CharSequence s, int start, int before, int count) { /* Don't care */ }
}

Just use it like this:

editText.addTextChangedListener(new TextValidator(editText) {
    @Override public void validate(TextView textView, String text) {
       /* Validation code here */
    }
});

Byte[] to InputStream or OutputStream

we can convert byte[] array into input stream by using ByteArrayInputStream

String str = "Welcome to awesome Java World";
    byte[] content = str.getBytes();
    int size = content.length;
    InputStream is = null;
    byte[] b = new byte[size];
    is = new ByteArrayInputStream(content);

For full example please check here http://www.onlinecodegeek.com/2015/09/how-to-convert-byte-into-inputstream.html

React.js inline style best practices

For some components, it is easier to use inline styles. Also, I find it easier and more concise (as I'm using Javascript and not CSS) to animate component styles.

For stand-alone components, I use the 'Spread Operator' or the '...'. For me, it's clear, beautiful, and works in a tight space. Here is a little loading animation I made to show it's benefits:

<div style={{...this.styles.container, ...this.state.opacity}}>
    <div style={{...this.state.colors[0], ...this.styles.block}}/>
    <div style={{...this.state.colors[1], ...this.styles.block}}/>
    <div style={{...this.state.colors[2], ...this.styles.block}}/>
    <div style={{...this.state.colors[7], ...this.styles.block}}/>
    <div style={{...this.styles.block}}/>
    <div style={{...this.state.colors[3], ...this.styles.block}}/>
    <div style={{...this.state.colors[6], ...this.styles.block}}/>
    <div style={{...this.state.colors[5], ...this.styles.block}}/>
    <div style={{...this.state.colors[4], ...this.styles.block}}/>
  </div>

    this.styles = {
  container: {
    'display': 'flex',
    'flexDirection': 'row',
    'justifyContent': 'center',
    'alignItems': 'center',
    'flexWrap': 'wrap',
    'width': 21,
    'height': 21,
    'borderRadius': '50%'
  },
  block: {
    'width': 7,
    'height': 7,
    'borderRadius': '50%',
  }
}
this.state = {
  colors: [
    { backgroundColor: 'red'},
    { backgroundColor: 'blue'},
    { backgroundColor: 'yellow'},
    { backgroundColor: 'green'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
    { backgroundColor: 'white'},
  ],
  opacity: {
    'opacity': 0
  }
}

EDIT NOVEMBER 2019

Working in the industry (A Fortune 500 company), I am NOT allowed to make any inline styling. In our team, we've decided that inline style are unreadable and not maintainable. And, after having seen first hand how inline styles make supporting an application completely intolerable, I'd have to agree. I completely discourage inline styles.

How do I format currencies in a Vue component?

You can format currency writing your own code but it is just solution for the moment - when your app will grow you can need other currencies.

There is another issue with this:

  1. For EN-us - dolar sign is always before currency - $2.00,
  2. For selected PL you return sign after amount like 2,00 zl.

I think the best option is use complex solution for internationalization e.g. library vue-i18n( http://kazupon.github.io/vue-i18n/).

I use this plugin and I don't have to worry about such a things. Please look at documentation - it is really simple:

http://kazupon.github.io/vue-i18n/guide/number.html

so you just use:

<div id="app">
  <p>{{ $n(100, 'currency') }}</p>
</div>

and set EN-us to get $100.00:

<div id="app">
  <p>$100.00</p>
</div>

or set PL to get 100,00 zl:

<div id="app">
  <p>100,00 zl</p>
</div>

This plugin also provide different features like translations and date formatting.

WPF: ItemsControl with scrollbar (ScrollViewer)

To get a scrollbar for an ItemsControl, you can host it in a ScrollViewer like this:

<ScrollViewer VerticalScrollBarVisibility="Auto">
  <ItemsControl>
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
  </ItemsControl>
</ScrollViewer>

Selenium WebDriver and DropDown Boxes

Example for select an option from the drop down list:

Click on drop down list by using id or csspath or xpath or name. I have used id here.

driver.findElement(By.id("dropdownlistone")).click(); // To click on drop down list
driver.findElement(By.linkText("india")).click(); // To select a data from the drop down list.

how to hide keyboard after typing in EditText in android?

you can create a singleton class for call easily like this:

public class KeyboardUtils {

    private static KeyboardUtils instance;
    private InputMethodManager inputMethodManager;

    private KeyboardUtils() {
    }

    public static KeyboardUtils getInstance() {
        if (instance == null)
            instance = new KeyboardUtils();
        return instance;
    }

    private InputMethodManager getInputMethodManager() {
        if (inputMethodManager == null)
            inputMethodManager = (InputMethodManager) Application.getInstance().getSystemService(Activity.INPUT_METHOD_SERVICE);
        return inputMethodManager;
    }

    @SuppressWarnings("ConstantConditions")
    public void hide(final Activity activity) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                try {
                    getInputMethodManager().hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

so, after can call in the activity how the next form:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
        KeyboardUtils.getInstance().hide(this);
    }

}

How to launch an Activity from another Application in Android

If you don't know the main activity, then the package name can be used to launch the application.

Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.package.address");
if (launchIntent != null) { 
    startActivity(launchIntent);//null pointer check in case package name was not found
}

How to pass an array within a query string?

This works for me:

In link, to attribute has value:

to="/filter/arr?fruits=apple&fruits=banana"

Route can handle this:

path="/filter/:arr"

For Multiple arrays:

to="filter/arr?fruits=apple&fruits=banana&vegetables=potato&vegetables=onion"

Route stays same.

SCREENSHOT

enter image description here

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

Free XML Formatting tool

If you are a programmer, many XML parsing programming libraries will let you parse XML, then output it - and generating pretty printed, indented output is an output option.

What is the maximum length of a valid email address?

320

And the segments look like this

{64}@{255}

64 + 1 + 255 = 320

You should also read this if you are validating emails

http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx

jQueryUI modal dialog does not show close button (x)

In the upper right corner of the dialog, mouse over where the button should be, and see rather or not you get some effect (the button hover). Try clicking it and seeing if it closes. If it does close, then you're just missing your image sprites that came with your package download.

What is the most efficient way to store a list in the Django models?

"Premature optimization is the root of all evil."

With that firmly in mind, let's do this! Once your apps hit a certain point, denormalizing data is very common. Done correctly, it can save numerous expensive database lookups at the cost of a little more housekeeping.

To return a list of friend names we'll need to create a custom Django Field class that will return a list when accessed.

David Cramer posted a guide to creating a SeperatedValueField on his blog. Here is the code:

from django.db import models

class SeparatedValuesField(models.TextField):
    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):
        self.token = kwargs.pop('token', ',')
        super(SeparatedValuesField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value: return
        if isinstance(value, list):
            return value
        return value.split(self.token)

    def get_db_prep_value(self, value):
        if not value: return
        assert(isinstance(value, list) or isinstance(value, tuple))
        return self.token.join([unicode(s) for s in value])

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

The logic of this code deals with serializing and deserializing values from the database to Python and vice versa. Now you can easily import and use our custom field in the model class:

from django.db import models
from custom.fields import SeparatedValuesField 

class Person(models.Model):
    name = models.CharField(max_length=64)
    friends = SeparatedValuesField()

Displaying a vector of strings in C++

You have to insert the elements using the insert method present in vectors STL, check the below program to add the elements to it, and you can use in the same way in your program.

#include <iostream>
#include <vector>
#include <string.h>

int main ()
{
  std::vector<std::string> myvector ;
  std::vector<std::string>::iterator it;

   it = myvector.begin();
  std::string myarray [] = { "Hi","hello","wassup" };
  myvector.insert (myvector.begin(), myarray, myarray+3);

  std::cout << "myvector contains:";
  for (it=myvector.begin(); it<myvector.end(); it++)
    std::cout << ' ' << *it;
    std::cout << '\n';

  return 0;
}

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

SQL update trigger only when column is modified

fyi The code I ended up with:

IF UPDATE (QtyToRepair)
    begin
        INSERT INTO tmpQtyToRepairChanges (OrderNo, PartNumber, ModifiedDate, ModifiedUser, ModifiedHost, QtyToRepairOld, QtyToRepairNew)
        SELECT S.OrderNo, S.PartNumber, GETDATE(), SUSER_NAME(), HOST_NAME(), D.QtyToRepair, I.QtyToRepair FROM SCHEDULE S
        INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
        INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber 
        WHERE I.QtyToRepair <> D.QtyToRepair
end

Cutting the videos based on start and end time using ffmpeg

Even though I'm 6 years late, but I think all the answers above didn't properly address the question @kalai is asking. The bash script below will process a text file in the following format:

URL | start_time | end_time | filename

for example

https://www.youtube.com/watch?v=iUDURCrvrMI|00:02:02|00:03:41|1

and loop through the file, downloads the file that youtube-dl supports, calculating duration between start_time and end_time and passing it to ffmpeg, since -t is actually the duration, not the real end_time

Hit me up if you have any question.

    for i in $(<video.txt);
    do
        URL=`echo $i | cut -d "|" -f 1`;
        START=`echo $i | cut -d "|" -f 2`;
        END=`echo $i | cut -d "|" -f 3`;
        FILE=`echo $i | cut -d "|" -f 4`;

        SEC1=`echo $START | sed 's/^/((/; s/:/)*60+/g' | bc`
        SEC2=`echo $END | sed 's/^/((/; s/:/)*60+/g' | bc`

        DIFFSEC=`expr ${SEC2} - ${SEC1}`

        ffmpeg $(youtube-dl -g $URL | sed "s/.*/-ss $START -i &/") -t $DIFFSEC -c copy $FILE".mkv";
        ffmpeg -i $FILE".mkv" -f mp3 -ab 192000 -vn $FILE".mp3";
        rm $FILE".mkv";
    done;

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

Indentation shortcuts in Visual Studio

You can just use Tab and Shift+Tab

Javascript checkbox onChange

HTML:

<input type="checkbox" onchange="handleChange(event)">

JS:

function handleChange(e) {
     const {checked} = e.target;
}

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);

Show a message box from a class in c#?

Try this:

System.Windows.Forms.MessageBox.Show("Here's a message!");

How to add ASP.NET 4.0 as Application Pool on IIS 7, Windows 7

Chances are you need to install .NET 4 (Which will also create a new AppPool for you)

First make sure you have IIS installed then perform the following steps:

  1. Open your command prompt (Windows + R) and type cmd and press ENTER
    You may need to start this as an administrator if you have UAC enabled.
    To do so, locate the exe (usually you can start typing with Start Menu open), right click and select "Run as Administrator"
  2. Type cd C:\Windows\Microsoft.NET\Framework\v4.0.30319\ and press ENTER.
  3. Type aspnet_regiis.exe -ir and press ENTER again.
    • If this is a fresh version of IIS (no other sites running on it) or you're not worried about the hosted sites breaking with a framework change you can use -i instead of -ir. This will change their AppPools for you and steps 5-on shouldn't be necessary.
    • at this point you will see it begin working on installing .NET's framework in to IIS for you
  4. Close the DOS prompt, re-open your start menu and right click Computer and select Manage
  5. Expand the left-hand side (Services and Applications) and select Internet Information Services
    • You'll now have a new applet within the content window exclusively for IIS.
  6. Expand out your computer and locate the Application Pools node, and select it. (You should now see ASP.NET v4.0 listed)
  7. Expand out your Sites node and locate the site you want to modify (select it)
  8. To the right you'll notice Basic Settings... just below the Edit Site text. Click this, and a new window should appear
  9. Select the .NET 4 AppPool using the Select... button and click ok.
  10. Restart the site, and you should be good-to-go.

(You can repeat steps 7-on for every site you want to apply .NET 4 on as well).


Additional References:

  1. .NET 4 Framework
    The framework for those that don't already have it.
  2. How do I run a command with elevated privileges?
    Directions on how to run the command prompt with Administrator rights.
  3. aspnet_regiis.exe options
    For those that might want to know what -ir or -i does (or the difference between them) or what other options are available. (I typically use -ir to prevent any older sites currently running from breaking on a framework change but that's up to you.)

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

How do I access my SSH public key?

On a Mac, you can do this to copy it to your clipboard (like cmd + c shortcut)
cat ~/Desktop/ded.html | pbcopy
pbcopy < ~/.ssh/id_rsa.pub

and to paste pbpaste > ~Documents/id_rsa.txt

or, use cmd + v shorcut to paste it somewhere else.

~/.ssh is the same path as /Users/macbook-username/.ssh
You can use Print work directory: pwd command on terminal to get the path to your current directory.

Where is shared_ptr?

There are at least three places where you may find shared_ptr:

  1. If your C++ implementation supports C++11 (or at least the C++11 shared_ptr), then std::shared_ptr will be defined in <memory>.

  2. If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr will likely be in <memory> (Microsoft Visual C++) or <tr1/memory> (g++'s libstdc++). Boost also provides a TR1 implementation that you can use.

  3. Otherwise, you can obtain the Boost libraries and use boost::shared_ptr, which can be found in <boost/shared_ptr.hpp>.

Why doesn't [01-12] range work as expected?

Use this:

0?[1-9]|1[012]
  • 07: valid
  • 7: valid
  • 0: not match
  • 00 : not match
  • 13 : not match
  • 21 : not match

To test a pattern as 07/2018 use this:

/^(0?[1-9]|1[012])\/([2-9][0-9]{3})$/

(Date range between 01/2000 to 12/9999 )

‘ant’ is not recognized as an internal or external command

even with the environment variables set, I found that ant -version does not work in scripts. Try call ant -version

How to add a char/int to an char array in C?

I think you've forgotten initialize your string "str": You need initialize the string before using strcat. And also you need that tmp were a string, not a single char. Try change this:

char str[1024]; // Only declares size
char tmp = '.';

for

char str[1024] = "Hello World";  //Now you have "Hello World" in str
char tmp[2] = ".";

How to get elements with multiple classes

Okay this code does exactly what you need:

HTML:

<div class="class1">nothing happens hear.</div>

<div class="class1 class2">This element will receive yout code.</div>

<div class="class1">nothing happens hear.</div>

JS:

function getElementMultipleClasses() {
    var x = document.getElementsByClassName("class1 class2");
    x[0].innerHTML = "This is the element you want";
}
getElementMultipleClasses();

Hope it helps! ;)

Selenium WebDriver How to Resolve Stale Element Reference Exception?

After deep investigation of the problem I found that error occurs selecting DIV elements that were added for Bootstrap only. Chrome browser removes such DIVS and the error occurs. It is enough to step down and select real element for fixing an error. For example, my modal dialog has structure:

<div class="modal-content" uib-modal-transclude="">
    <div class="modal-header">
        ...
    </div>
    <div class="modal-body">
        <form class="form-horizontal ...">
            ...
        </form>
    <div>
<div>

Selecting div class="modal-body" generates an error, selecting form ... works as it would.

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))

The "3" at the end means for column C.

How do I parse command line arguments in Java?

Someone pointed me to args4j lately which is annotation based. I really like it!

Index Error: list index out of range (Python)

Generally it means that you are providing an index for which a list element does not exist.

E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.

How to create image slideshow in html?

Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.

Here is the one I most liked.

http://www.zurb.com/playground/orbit-jquery-image-slider

How to install Android SDK on Ubuntu?

To install it on a Debian based system simply do

# Install latest JDK
sudo apt install default-jdk

# install unzip if not installed yet
sudo apt install unzip

# get latest sdk tools - link will change. go to https://developer.android.com/studio/#downloads to get the latest one
cd ~
wget https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip

# unpack archive
unzip sdk-tools-linux-4333796.zip

rm sdk-tools-linux-4333796.zip

mkdir android-sdk
mv tools android-sdk/tools

Then add the Android SDK to your PATH, open ~/.bashrc in editor and add the following lines into the file

# Export the Android SDK path 
export ANDROID_HOME=$HOME/android-sdk
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools

# Fixes sdkmanager error with java versions higher than java 8
export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'

Run

source ~/.bashrc

Show all available sdk packages

sdkmanager --list

Identify latest android platform (here it's 28) and run

sdkmanager "platform-tools" "platforms;android-28"

Now you have adb, fastboot and the latest sdk tools installed

angular js unknown provider

In my Ruby on Rails app, I had done the following:

rake assets:precompile

This was done in the 'development' environment, which had minified Angular.js and included it in the /public/assets/application.js file.

Removing the /public/assets/* files solved the problem for me.

Replacing NULL with 0 in a SQL server query

When you say the first three columns, do you mean your SUM columns? If so, add ELSE 0 to your CASE statements. The SUM of a NULL value is NULL.

sum(case when c.runstatus = 'Succeeded' then 1 else 0 end) as Succeeded, 
sum(case when c.runstatus = 'Failed' then 1 else 0 end) as Failed, 
sum(case when c.runstatus = 'Cancelled' then 1 else 0 end) as Cancelled, 

How to ignore a particular directory or file for tslint?

In addition to Michael's answer, consider a second way: adding linterOptions.exclude to tslint.json

For example, you may have tslint.json with following lines:

{
  "linterOptions": {
    "exclude": [
      "someDirectory/*.d.ts"
    ]
  }
}

Git merge error "commit is not possible because you have unmerged files"

This error occurs when you resolve the conflicts but the file still needs to be added in the stage area. git add . would solve it. Then, try to commit and merge.

How to set a variable inside a loop for /F

To expand on the answer I came here to get a better understanding so I wrote this that can explain it and helped me too.

It has the setlocal DisableDelayedExpansion in there so you can locally set this as you wish between the setlocal EnableDelayedExpansion and it.

@echo off
title %~nx0
for /f "tokens=*" %%A in ("Some Thing") do (
  setlocal EnableDelayedExpansion
  set z=%%A
  echo !z!        Echoing the assigned variable in setlocal scope.
  echo %%A        Echoing the variable in local scope.
  setlocal DisableDelayedExpansion
  echo !z!        &rem !z!           Neither of these now work, which makes sense.
  echo %z%        &rem ECHO is off.  Neither of these now work, which makes sense.
  echo %%A        Echoing the variable in its local scope, will always work.
  )

Removing object properties with Lodash

You can use _.omit() for emitting the key from a JSON array if you have fewer objects:

_.forEach(data, (d) => {
    _.omit(d, ['keyToEmit1', 'keyToEmit2'])
});

If you have more objects, you can use the reverse of it which is _.pick():

_.forEach(data, (d) => {
    _.pick(d, ['keyToPick1', 'keyToPick2'])
});

What is SELF JOIN and when would you use it?

You'd use a self-join on a table that "refers" to itself - e.g. a table of employees where managerid is a foreign-key to employeeid on that same table.

Example:

SELECT E.name, ME.name AS manager
FROM dbo.Employees E
LEFT JOIN dbo.Employees ME
ON ME.employeeid = E.managerid

Remove commas from the string using JavaScript

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

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

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

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

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

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

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

ParseFloat converts the this type definition from string to number

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

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

    // Do the actual math and setState calls here
}

Change placeholder text

Using jquery you can do this by following code:

<input type="text" id="tbxEmail" name="Email" placeholder="Some Text"/>

$('#tbxEmail').attr('placeholder','Some New Text');

JavaScript string newline character?

I've just tested a few browsers using this silly bit of JavaScript:

_x000D_
_x000D_
function log_newline(msg, test_value) {_x000D_
  if (!test_value) { _x000D_
    test_value = document.getElementById('test').value;_x000D_
  }_x000D_
  console.log(msg + ': ' + (test_value.match(/\r/) ? 'CR' : '')_x000D_
              + ' ' + (test_value.match(/\n/) ? 'LF' : ''));_x000D_
}_x000D_
_x000D_
log_newline('HTML source');_x000D_
log_newline('JS string', "foo\nbar");_x000D_
log_newline('JS template literal', `bar_x000D_
baz`);
_x000D_
<textarea id="test" name="test">_x000D_
_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

IE8 and Opera 9 on Windows use \r\n. All the other browsers I tested (Safari 4 and Firefox 3.5 on Windows, and Firefox 3.0 on Linux) use \n. They can all handle \n just fine when setting the value, though IE and Opera will convert that back to \r\n again internally. There's a SitePoint article with some more details called Line endings in Javascript.

Note also that this is independent of the actual line endings in the HTML file itself (both \n and \r\n give the same results).

When submitting a form, all browsers canonicalize newlines to %0D%0A in URL encoding. To see that, load e.g. data:text/html,<form><textarea name="foo">foo%0abar</textarea><input type="submit"></form> and press the submit button. (Some browsers block the load of the submitted page, but you can see the URL-encoded form values in the console.)

I don't think you really need to do much of any determining, though. If you just want to split the text on newlines, you could do something like this:

lines = foo.value.split(/\r\n|\r|\n/g);

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

It depends on the encoding of your string (ASCII, UTF-8, ...).

For example:

byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);
byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);

A small sample why encoding matters:

string pi = "\u03a0";
byte[] ascii = System.Text.Encoding.ASCII.GetBytes (pi);
byte[] utf8 = System.Text.Encoding.UTF8.GetBytes (pi);

Console.WriteLine (ascii.Length); //Will print 1
Console.WriteLine (utf8.Length); //Will print 2
Console.WriteLine (System.Text.Encoding.ASCII.GetString (ascii)); //Will print '?'

ASCII simply isn't equipped to deal with special characters.

Internally, the .NET framework uses UTF-16 to represent strings, so if you simply want to get the exact bytes that .NET uses, use System.Text.Encoding.Unicode.GetBytes (...).

See Character Encoding in the .NET Framework (MSDN) for more information.

How should I print types like off_t and size_t?

As I recall, the only portable way to do it, is to cast the result to "unsigned long int" and use %lu.

printf("sizeof(int) = %lu", (unsigned long) sizeof(int));

Change the borderColor of the TextBox

With PictureBox1
    .Visible = False
    .Width = TextBox1.Width + 4
    .Height = TextBox1.Height + 4
    .Left = TextBox1.Left - 2
    .Top = TextBox1.Top - 2
    .SendToBack()
    .Visible = True
End With

Get GMT Time in Java

I wonder why no one does this:

Calendar time = Calendar.getInstance();
time.add(Calendar.MILLISECOND, -time.getTimeZone().getOffset(time.getTimeInMillis()));
Date date = time.getTime();

Update: Since Java 8,9,10 and more, there should be better alternatives supported by Java. Thanks for your comment @humanity

How to perform update operations on columns of type JSONB in Postgres 9.4

I wrote small function for myself that works recursively in Postgres 9.4. I had same problem (good they did solve some of this headache in Postgres 9.5). Anyway here is the function (I hope it works well for you):

CREATE OR REPLACE FUNCTION jsonb_update(val1 JSONB,val2 JSONB)
RETURNS JSONB AS $$
DECLARE
    result JSONB;
    v RECORD;
BEGIN
    IF jsonb_typeof(val2) = 'null'
    THEN 
        RETURN val1;
    END IF;

    result = val1;

    FOR v IN SELECT key, value FROM jsonb_each(val2) LOOP

        IF jsonb_typeof(val2->v.key) = 'object'
            THEN
                result = result || jsonb_build_object(v.key, jsonb_update(val1->v.key, val2->v.key));
            ELSE
                result = result || jsonb_build_object(v.key, v.value);
        END IF;
    END LOOP;

    RETURN result;
END;
$$ LANGUAGE plpgsql;

Here is sample use:

select jsonb_update('{"a":{"b":{"c":{"d":5,"dd":6},"cc":1}},"aaa":5}'::jsonb, '{"a":{"b":{"c":{"d":15}}},"aa":9}'::jsonb);
                            jsonb_update                             
---------------------------------------------------------------------
 {"a": {"b": {"c": {"d": 15, "dd": 6}, "cc": 1}}, "aa": 9, "aaa": 5}
(1 row)

As you can see it analyze deep down and update/add values where needed.

Getting the 'external' IP address in Java

System.out.println(pageCrawling.getHtmlFromURL("http://ipecho.net/plain"));

How using try catch for exception handling is best practice

I know this is an old question, but nobody here mentioned the MSDN article, and it was the document that actually cleared it up for me, MSDN has a very good document on this, you should catch exceptions when the following conditions are true:

  • You have a good understanding of why the exception might be thrown, and you can implement a specific recovery, such as prompting the user to enter a new file name when you catch a FileNotFoundException object.

  • You can create and throw a new, more specific exception.

int GetInt(int[] array, int index)
{
    try
    {
        return array[index];
    }
    catch(System.IndexOutOfRangeException e)
    {
        throw new System.ArgumentOutOfRangeException(
            "Parameter index is out of range.");
    }
}
  • You want to partially handle an exception before passing it on for additional handling. In the following example, a catch block is used to add an entry to an error log before re-throwing the exception.
    try
{
    // Try to access a resource.
}
catch (System.UnauthorizedAccessException e)
{
    // Call a custom error logging procedure.
    LogError(e);
    // Re-throw the error.
    throw;     
}

I'd suggest reading the entire "Exceptions and Exception Handling" section and also Best Practices for Exceptions.

Save file Javascript with file name

Replace your "Save" button with an anchor link and set the new download attribute dynamically. Works in Chrome and Firefox:

var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");

Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/

Here a compatibility table for downloadattribute: http://caniuse.com/download

How to select a single field for all documents in a MongoDB collection?

The query for MongoDB here fees is collection and description is a field.

db.getCollection('fees').find({},{description:1,_id:0})

OnItemCLickListener not working in listview

if you have textviews, buttons or stg clickable or selectable in your row view only

android:descendantFocusability="blocksDescendants"

is not enough. You have to set

android:textIsSelectable="false"

to your textviews and

android:focusable="false"

to your buttons and other focusable items.

HTML checkbox onclick called in Javascript

Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute selectAll() when you click on a label, right? Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label

<label for="check_all_1" onclick="selectAll(document.wizard_form, this);">
  <input type="checkbox" id="check_all_1" name="check_all_1" title="Select All">
  Select All
</label>

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

Ultimately you always have a finite max of heap to use no matter what platform you are running on. In Windows 32 bit this is around 2GB (not specifically heap but total amount of memory per process). It just happens that Java chooses to make the default smaller (presumably so that the programmer can't create programs that have runaway memory allocation without running into this problem and having to examine exactly what they are doing).

So this given there are several approaches you could take to either determine what amount of memory you need or to reduce the amount of memory you are using. One common mistake with garbage collected languages such as Java or C# is to keep around references to objects that you no longer are using, or allocating many objects when you could reuse them instead. As long as objects have a reference to them they will continue to use heap space as the garbage collector will not delete them.

In this case you can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place. One option which I have used in the past is "JMP" http://www.khelekore.org/jmp/.

If you determine that you are allocating these objects for a reason and you need to keep around references (depending on what you are doing this might be the case), you will just need to increase the max heap size when you start the program. However, once you do the memory profiling and understand how your objects are getting allocated you should have a better idea about how much memory you need.

In general if you can't guarantee that your program will run in some finite amount of memory (perhaps depending on input size) you will always run into this problem. Only after exhausting all of this will you need to look into caching objects out to disk etc. At this point you should have a very good reason to say "I need Xgb of memory" for something and you can't work around it by improving your algorithms or memory allocation patterns. Generally this will only usually be the case for algorithms operating on large datasets (like a database or some scientific analysis program) and then techniques like caching and memory mapped IO become useful.

How do I create an empty array/matrix in NumPy?

For creating an empty NumPy array without defining its shape:

  1. arr = np.array([])
    

    (this is preferred, because you know you will be using this as a NumPy array)

  2.  arr = []   # and use it as NumPy array later by converting it
     arr = np.asarray(arr)
    

NumPy converts this to np.ndarray type afterward, without extra [] 'dimension'.

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

Take a look at OAuth 2.0 playground.You will get an overview of the protocol.It is basically an environment(like any app) that shows you the steps involved in the protocol.

https://developers.google.com/oauthplayground/

jQuery select element in parent window

Use the context-parameter

$("#testdiv",parent.document)

But if you really use a popup, you need to access opener instead of parent

$("#testdiv",opener.document)

Error: Java: invalid target release: 11 - IntelliJ IDEA

Just had same error. Problem was that I had empty package-info.java file. As soon as I added package name inside it worked...

Ruby: Calling class method from instance

You're doing it the right way. Class methods (similar to 'static' methods in C++ or Java) aren't part of the instance, so they have to be referenced directly.

On that note, in your example you'd be better served making 'default_make' a regular method:

#!/usr/bin/ruby

class Truck
    def default_make
        # Class method.
        "mac"
    end

    def initialize
        # Instance method.
        puts default_make  # gets the default via the class's method.
    end
end

myTruck = Truck.new()

Class methods are more useful for utility-type functions that use the class. For example:

#!/usr/bin/ruby

class Truck
    attr_accessor :make

    def default_make
        # Class method.
        "mac"
    end

    def self.buildTrucks(make, count)
        truckArray = []

        (1..count).each do
            truckArray << Truck.new(make)
        end

        return truckArray
    end

    def initialize(make = nil)
        if( make == nil )
            @make = default_make()
        else
            @make = make
        end
    end
end

myTrucks = Truck.buildTrucks("Yotota", 4)

myTrucks.each do |truck|
    puts truck.make
end

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

Some code examples for simple GET request. Maybe this helps understanding the difference. Using then:

$http.get('/someURL').then(function(response) {
    var data = response.data,
        status = response.status,
        header = response.header,
        config = response.config;
    // success handler
}, function(response) {
    var data = response.data,
        status = response.status,
        header = response.header,
        config = response.config;
    // error handler
});

Using success/error:

$http.get('/someURL').success(function(data, status, header, config) {
    // success handler
}).error(function(data, status, header, config) {
    // error handler
});

How can I create a two dimensional array in JavaScript?

Row and Column sizes of an array known only at the run time then following method could be used for creating a dynamic 2d array.

_x000D_
_x000D_
    var num = '123456';
    var row = 3; // Known at run time
    var col = 2; // Known at run time
    var i = 0;
    
    var array2D = [[]];
    for(var r = 0; r < row; ++r)
    {
        array2D[r] = [];
        for(var c = 0; c < col; ++c)
        {
            array2D[r][c] = num[i++];
        }
    }
    console.log(array2D); 
    // [[ '1', '2' ], 
    //  [ '3', '4' ], 
    //  [ '5', '6' ]]
    
    console.log(array2D[2][1]); // 6
_x000D_
_x000D_
_x000D_

How to round the corners of a button

An alternative answer which sets a border too (making it more like a button) is here ... How to set rectangle border for custom type UIButton

Should I write script in the body or the head of the html?

W3Schools have a nice article on this subject.

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, are placed in functions.

Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.

Scripts in <body>

If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.

Adb Devices can't find my phone

Try doing this:

  • Unplug the device
  • Execute adb kill-server && adb start-server(that restarts adb)
  • Re-plug the device

Also you can try to edit an adb config file .android/adb_usb.ini and add a line 04e8 after the header. Restart adb required for changes to take effect.

How to present popover properly in iOS 8

In iOS9 UIPopoverController is depreciated. So can use the below code for Objective-C version above iOS9.x,

- (IBAction)onclickPopover:(id)sender {
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
UIViewController *viewController = [sb instantiateViewControllerWithIdentifier:@"popover"];

viewController.modalPresentationStyle = UIModalPresentationPopover;
viewController.popoverPresentationController.sourceView = self.popOverBtn;
viewController.popoverPresentationController.sourceRect = self.popOverBtn.bounds;
viewController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
[self presentViewController:viewController animated:YES completion:nil]; }

Wi-Fi Direct and iOS Support

According to this thread:

The peer-to-peer Wi-Fi implemented by iOS (and recent versions of OS X) is not compatible with Wi-Fi Direct. Note Just as an aside, you can access peer-to-peer Wi-Fi without using Multipeer Connectivity. The underlying technology is Bonjour + TCP/IP, and you can access that directly from your app. The WiTap sample code shows how.

Git credential helper - update password

Working solution for Windows:

Control Panel > User Accounts > Credential Manager > Generic Credentials

enter image description here

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

VSCode regex find & replace submatch math?

Just to add another example:

I was replacing src attr in img html tags, but i needed to replace only the src and keep any text between the img declaration and src attribute.

I used the find+replace tool (ctrl+h) as in the image: Find and replace

How do I export html table data as .csv file?

Thanks to gene tsai, here is some modifications to his code to run on my target page:

csv = []
rows = $('#data tr');
for(i =0;i < rows.length;i++) {
    cells = $(rows[i]).find('td,th');
    csv_row = [];
    for (j=0;j<cells.length;j++) {
        txt = cells[j].innerText;
        csv_row.push(txt.replace(",", "-"));
    }
    csv.push(csv_row.join(","));
}
output = csv.join("\n")

improvements:

  • Use generic JavaScript for loop
  • make sure each cell does not have a comma

Get Wordpress Category from Single Post

How about get_the_category?

You can then do

$category = get_the_category();
$firstCategory = $category[0]->cat_name;

How to post pictures to instagram using API

If you read the link you shared, the accepted answer is:

You cannot post pictures to Instagram via the API.

Instagram have now said this:

Now you can post your content using Instagram APIs (New) effects from 26th Jan 2021 !

https://developers.facebook.com/blog/post/2021/01/26/introducing-instagram-content-publishing-api/

Hopefully you have some luck here.

Call a Javascript function every 5 seconds continuously

For repeating an action in the future, there is the built in setInterval function that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:

setInterval(function() {
    // do stuff
}, duration);

What is JNDI? What is its basic use? When is it used?

What is JNDI ?

JNDI stands for Java Naming and Directory Interface. It comes standard with J2EE.

What is its basic use?

With this API, you can access many types of data, like objects, devices, files of naming and directory services, eg. it is used by EJB to find remote objects. JNDI is designed to provide a common interface to access existing services like DNS, NDS, LDAP, CORBA and RMI.

When it is used?

You can use the JNDI to perform naming operations, including read operations and operations for updating the namespace. The following operations are described here.

Export database schema into SQL file

enter image description here

In the picture you can see. In the set script options, choose the last option: Types of data to script you click at the right side and you choose what you want. This is the option you should choose to export a schema and data

What is Bootstrap?

Disclaimer: I have used bootstrap in the past, but I never really appreciated what it actually is before, this description comes from me coming to my own definition, today. And I know that bootstrap v4 is out, but I found the bootstrap v3 documentation to be much clearer, so I used that. The library is not going to fundamentally change what it provides.

Briefly

Bootstrap is a collection of CSS and javascript files that provides some nice-looking default styling for standard html elements, and a few common web content objects that are not standard html elements.

To make an analogy, it's kind of like applying a theme in powerpoint, but for your website: it makes things look pretty nice without too much initial effort.

What does it consist of?

The official v3 documentation breaks it up into three sections:

These roughly correspond to the three main things that Bootstrap provides:

  • Plain CSS files that style standard html elements. So, Bootstrap makes your standard elements pretty-looking. e.g. html: <input class="btn btn-default" type="button" value="Input">Click me</button>
  • CSS files that use styling on standard html elements to make them into something that is not a standard html element but is a standard Bootstrap element (e.g. https://getbootstrap.com/docs/3.3/components/#progress). In this way Bootstrap extends the list of "standard" web elements in a visually consistent way. e.g. html: <span class="glyphicon glyphicon-align-left"></span>
  • The CSS classes are designed with jQuery in mind. Internally, Bootstrap uses jQuery selectors to modify the styles on the fly and interact with the DOM, and thus provides the user the same capability. I believe this requires more explanation, so...

Using Javascript/jQuery

Bootstrap extends jQuery quite a bit. If we look at the source code, we can see that it uses jQuery to do things like: set up listeners for keydown event to interact with dropdowns. It does all of this jQuery setup when you import it in your <script> tag, so you need to make sure jQuery is loaded before Bootstrap is.

Additionally, it ties the javascript to the DOM more tightly than plain jQuery, providing a javascript class interface. e.g. toggle a button programmatically. Remember that CSS just defines how a thing looks, so the major job of these operations will tend to be to modify which CSS classes apply to the element at that moment in time. This kind of change, based on user input, can't be done with plain CSS.

There are other standard interactions with a user that we denizens of the internet are used to that are not covered by CSS. Like, clicking a link that scrolls you down a page instead of changing pages. One of the things that Bootstrap gives you is an easy way to implement this behaviour on your own website.

Standards

I have mentioned the word "standard" a lot here, and for good reason. I think the best thing that Bootstrap provides is a set of good-looking standards. You're free to modify the default theme as much as you want, but it's a better baseline than raw html, css and js. And this is why it's called "framework".

Different web browsers have different default styles and can act differently, and need different CSS prefixes and things like that. A major benefit of Bootstrap is that it is much more reliable than writing all that cross-browser stuff yourself (you will still have problems, I'm sure, but it's easier).

I think that Bootstrap was preferred more when gulp and babel weren't as popular. Looking at Bootstrap it seems to come from a time before everyone compiled their javascript. It's still relevant, but you can get some of the benefits from other sources now.

More recent versions of CSS have allowed you to define transitions between these static lists as they change. The original version of Bootstrap actually predates wide-spread adoption of this capability in browsers, so they still have their own animation classes. There are a few bits of Bootstrap that are like this: that other stuff has come up around it and makes it look a bit redundant.

How to pass parameters using ui-sref in ui-router to controller

You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)

Image style height and width not taken in outlook mails

The px needs to be left off, for some odd reason.

does linux shell support list data structure?

For make a list, simply do that

colors=(red orange white "light gray")

Technically is an array, but - of course - it has all list features.
Even python list are implemented with array

Docker compose, running containers in net:host

Those documents are outdated. I'm guessing the 1.6 in the URL is for Docker 1.6, not Compose 1.6. Check out the correct syntax here: https://docs.docker.com/compose/compose-file/#network_mode. You are looking for network_mode when using the v2 YAML format.

Change the name of a key in dictionary

In python 2.7 and higher, you can use dictionary comprehension: This is an example I encountered while reading a CSV using a DictReader. The user had suffixed all the column names with ':'

ori_dict = {'key1:' : 1, 'key2:' : 2, 'key3:' : 3}

to get rid of the trailing ':' in the keys:

corrected_dict = { k.replace(':', ''): v for k, v in ori_dict.items() }

DTO pattern: Best way to copy properties between two objects

I had an application that I needed to convert from a JPA entity to DTO, and I thought about it and finally came up using org.springframework.beans.BeanUtils.copyProperties for copying simple properties and also extending and using org.springframework.binding.convert.service.DefaultConversionService for converting complex properties.

In detail my service was something like this:

@Service("seedingConverterService")
public class SeedingConverterService extends DefaultConversionService implements ISeedingConverterService  {
    @PostConstruct
    public void init(){
        Converter<Feature,FeatureDTO> featureConverter = new Converter<Feature, FeatureDTO>() {

            @Override
            public FeatureDTO convert(Feature f) {
                FeatureDTO dto = new FeatureDTO();
                //BeanUtils.copyProperties(f, dto,"configurationModel");
                BeanUtils.copyProperties(f, dto);
                dto.setConfigurationModelId(f.getConfigurationModel()==null?null:f.getConfigurationModel().getId());
                return dto;
            }
        };

        Converter<ConfigurationModel,ConfigurationModelDTO> configurationModelConverter = new Converter<ConfigurationModel,ConfigurationModelDTO>() {
            @Override
            public ConfigurationModelDTO convert(ConfigurationModel c) {
                ConfigurationModelDTO dto = new ConfigurationModelDTO();
                //BeanUtils.copyProperties(c, dto, "features");
                BeanUtils.copyProperties(c, dto);
                dto.setAlgorithmId(c.getAlgorithm()==null?null:c.getAlgorithm().getId());
                List<FeatureDTO> l = c.getFeatures().stream().map(f->featureConverter.convert(f)).collect(Collectors.toList());
                dto.setFeatures(l);
                return dto;
            }
        };
        addConverter(featureConverter);
        addConverter(configurationModelConverter);
    }
}

C++ program converts fahrenheit to celsius

(5/9) will by default be computed as an integer division and will be zero. Try (5.0/9)

Keyboard shortcuts with jQuery

Since this question was originally asked, John Resig (the primary author of jQuery) has forked and improved the js-hotkeys project. His version is available at:

http://github.com/jeresig/jquery.hotkeys

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

I solved the problem by creating a symbolic link to the library. I.e.

The actual library resides in

/usr/local/mysql/lib

And then I created a symbolic link in

/usr/lib

Using the command:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

so that I have the following mapping:

ls -l libmysqlclient.18.dylib 
lrwxr-xr-x  1 root  wheel  44 16 Jul 14:01 libmysqlclient.18.dylib -> /usr/local/mysql/lib/libmysqlclient.18.dylib

That was it. After that everything worked fine.

EDIT:

Notice, that since MacOS El Capitan the System Integrity Protection (SIP, also known as "rootless") will prevent you from creating links in /usr/lib/. You could disable SIP by following these instructions, but you can create a link in /usr/local/lib/ instead:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

Hive insert query like SQL

Enter the following command to insert data into the testlog table with some condition:

INSERT INTO TABLE testlog SELECT * FROM table1 WHERE some condition;

Caching a jquery ajax response in javascript/browser

All the modern browsers provides you storage apis. You can use them (localStorage or sessionStorage) to save your data.

All you have to do is after receiving the response store it to browser storage. Then next time you find the same call, search if the response is saved already. If yes, return the response from there; if not make a fresh call.

Smartjax plugin also does similar things; but as your requirement is just saving the call response, you can write your code inside your jQuery ajax success function to save the response. And before making call just check if the response is already saved.

Change Default branch in gitlab

In the latest GitLab Community Edition version 9.2.2.:

  1. You have to click on 'Settings' tab located at right most on tabs panel after opening the project.
  2. Under 'Settings' you will get section 'Default Branch' dropdown which will give you all branches for the repository. Select the desired branch.
  3. Scroll down to hit green colored 'Save changes' button located just after 'Project Avatar'.

Please refer image below:

enter image description here

React component not re-rendering on state change

I'd like to add to this the enormously simple, but oh so easily made mistake of writing:

this.state.something = 'changed';

... and then not understanding why it's not rendering and Googling and coming on this page, only to realize that you should have written:

this.setState({something: 'changed'});

React only triggers a re-render if you use setState to update the state.

Cannot ignore .idea/workspace.xml - keeps popping up

To remove .idea/ completely from the git without affecting your IDE config you could just do:

git rm -r --cached '.idea/'
echo .idea >> .gitignore
git commit -am "removed .idea/ directory"

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

For my case, the problem was due to losing of the internet connection in my WiFi.

Unix - copy contents of one directory to another

Try this:

cp Folder1/* Folder2/

What exactly does += do in python?

Note x += y is not the same as x = x + y in some situations where an additional operator is included because of the operator precedence combined with the fact that the right hand side is always evaluated first, e.g.

>>> x = 2
>>> x += 2 and 1
>>> x
3

>>> x = 2
>>> x = x + 2 and 1
>>> x
1

Note the first case expand to:

>>> x = 2
>>> x = x + (2 and 1)
>>> x
3

You are more likely to encounter this in the 'real world' with other operators, e.g.

x *= 2 + 1 == x = x * (2 + 1) != x = x * 2 + 1

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

How to disable the resize grabber of <textarea>?

example of textarea for disable the resize option

<textarea CLASS="foo"></textarea>

<style>
textarea.foo
{
resize:none;
}

</style>

Deleting DataFrame row in Pandas based on column value

If I'm understanding correctly, it should be as simple as:

df = df[df.line_race != 0]

What does an exclamation mark before a cell reference mean?

If you use that forumla in the name manager you are creating a dynamic range which uses "this sheet" in place of a specific sheet.

As Jerry says, Sheet1!A1 refers to cell A1 on Sheet1. If you create a named range and omit the Sheet1 part you will reference cell A1 on the currently active sheet. (omitting the sheet reference and using it in a cell formula will error).

edit: my bad, I was using $A$1 which will lock it to the A1 cell as above, thanks pnuts :p

Reading an Excel file in python using pandas

You just need to feed the path to your file to pd.read_excel

import pandas as pd

file_path = "./my_excel.xlsx"
data_frame = pd.read_excel(file_path)

Checkout the documentation to explore parameters like skiprows to ignore rows when loading the excel

How to find the socket connection state in C?

TCP keepalive socket option (SO_KEEPALIVE) would help in this scenario and close server socket in case of connection loss.

Where is the web server root directory in WAMP?

this is the path to the web root directory c:\wamp\www

you can create different projects by adding different folders to this directory and call them like:

localhost/project1 from browser

this will run the index.html or index.php, lying inside project1

Permissions error when connecting to EC2 via SSH on Mac OSx

After about a half hour of searching and trying to debug this I was able to figure it out. My situation involved me using the same pem file for two different ec2 instance and it working for one and not the other.

My first instance it worked on was the standard aws linux ami amzn-ami-hvm-2014.03.2.x86_64-ebs. I simply used

ssh -i mypemfile.pem ec2-user@myec2ipaddress 

and it worked.

I then launched a fedora instance Fedora-x86_64-19-20140407-sda and tried the same command but kept getting:

Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

After changing my username from ec2-user to fedora it worked!

ssh -i mypemfile.pem fedora@myec2address

On duplicate key ignore?

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tag is the unique key, use:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;

on duplicate key produces:

Query OK, 0 rows affected (0.07 sec)

How to ignore certain files in Git

You can use below methods for ignoring/not-ignoring changes in tracked files.

  1. For ignoring: git update-index --assume-unchanged <file>
  2. For reverting ignored files: git update-index --no-assume-unchanged <file>

How to put text over images in html?

You can try this...

<div class="image">

      <img src="" alt="" />

      <h2>Text you want to display over the image</h2>

</div>

CSS

.image { 
   position: relative; 
   width: 100%; /* for IE 6 */
}

h2 { 
   position: absolute; 
   top: 200px; 
   left: 0; 
   width: 100%; 
}

Wait until a process ends

I had a case where Process.HasExited didn't change after closing the window belonging to the process. So Process.WaitForExit() also didn't work. I had to monitor Process.Responding that went to false after closing the window like that:

while (!_process.HasExited && _process.Responding) {
  Thread.Sleep(100);
}
...

Perhaps this helps someone.

Java Mouse Event Right Click

Yes, take a look at this thread which talks about the differences between platforms.

How to detect right-click event for Mac OS

BUTTON3 is the same across all platforms, being equal to the right mouse button. BUTTON2 is simply ignored if the middle button does not exist.

Command for restarting all running docker containers?

To start only stopped containers:

docker start $(docker ps -a -q -f status=exited)

(On windows it works in Powershell).

Iterator Loop vs index loop

Iterators are first choice over operator[]. C++11 provides std::begin(), std::end() functions.

As your code uses just std::vector, I can't say there is much difference in both codes, however, operator [] may not operate as you intend to. For example if you use map, operator[] will insert an element if not found.

Also, by using iterator your code becomes more portable between containers. You can switch containers from std::vector to std::list or other container freely without changing much if you use iterator such rule doesn't apply to operator[].

How do I flush the cin buffer?

Possibly:

std::cin.ignore(INT_MAX);

This would read in and ignore everything until EOF. (you can also supply a second argument which is the character to read until (ex: '\n' to ignore a single line).

Also: You probably want to do a: std::cin.clear(); before this too to reset the stream state.

How to call a PHP function on the click of a button

Try this:

if($_POST['select'] and $_SERVER['REQUEST_METHOD'] == "POST"){
    select();
}
if($_POST['insert'] and $_SERVER['REQUEST_METHOD'] == "POST"){
    insert();
}

Why can't I call a public method in another class?

You're trying to call an instance method on the class. To call an instance method on a class you must create an instance on which to call the method. If you want to call the method on non-instances add the static keyword. For example

class Example {
  public static string NonInstanceMethod() {
    return "static";
  }
  public string InstanceMethod() { 
    return "non-static";
  }
}

static void SomeMethod() {
  Console.WriteLine(Example.NonInstanceMethod());
  Console.WriteLine(Example.InstanceMethod());  // Does not compile
  Example v1 = new Example();
  Console.WriteLine(v1.InstanceMethod());
}

OrderBy descending in Lambda expression?

This only works in situations where you have a numeric field, but you can put a minus sign in front of the field name like so:

reportingNameGroups = reportingNameGroups.OrderBy(x=> - x.GroupNodeId);

However this works a little bit different than OrderByDescending when you have are running it on an int? or double? or decimal? fields.

What will happen is on OrderByDescending the nulls will be at the end, vs with this method the nulls will be at the beginning. Which is useful if you want to shuffle nulls around without splitting data into pieces and splicing it later.

Get type of all variables

> mtcars %>% 
+     summarise_all(typeof) %>% 
+     gather
    key  value
1   mpg double
2   cyl double
3  disp double
4    hp double
5  drat double
6    wt double
7  qsec double
8    vs double
9    am double
10 gear double
11 carb double

I try class and typeof functions, but all fails.

*ngIf and *ngFor on same element causing error

Table below only lists items that have a "beginner" value set. Requires both the *ngFor and the *ngIf to prevent unwanted rows in html.

Originally had *ngIf and *ngFor on the same <tr> tag, but doesn't work. Added a <div> for the *ngFor loop and placed *ngIf in the <tr> tag, works as expected.

<table class="table lessons-list card card-strong ">
  <tbody>
  <div *ngFor="let lesson of lessons" >
   <tr *ngIf="lesson.isBeginner">
    <!-- next line doesn't work -->
    <!-- <tr *ngFor="let lesson of lessons" *ngIf="lesson.isBeginner"> -->
    <td class="lesson-title">{{lesson.description}}</td>
    <td class="duration">
      <i class="fa fa-clock-o"></i>
      <span>{{lesson.duration}}</span>
    </td>
   </tr>
  </div>
  </tbody>

</table>

C++ Boost: undefined reference to boost::system::generic_category()

I had the same problem and also use Linux Mint (as nuduoz) . I my case problem was solved after i added boost_system to GCC C++ Linker->Libraries.

illegal use of break statement; javascript

break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return to break the execution flow of the current function and return to the caller.

function loop() {
    if (isPlaying) {
        jet1.draw();
        drawAllEnemies();
        requestAnimFrame(loop);
        if (game == 1) {
           return
        }
    }
}

Note: This does not cover the logic behind the if condition or when to return from the method, for that we need to have more context regarding the drawAllEnemies and requestAnimFrame method as well as how game value is updated

AngularJS ng-class if-else expression

This is the best and reliable way to do this. Here is a simple example and after that you can develop your custom logic:

//In .ts
public showUploadButton:boolean = false;

if(some logic)
{
    //your logic
    showUploadButton = true;
}

//In template
<button [class]="showUploadButton ? 'btn btn-default': 'btn btn-info'">Upload</button>

Importing lodash into angular2 + typescript application

I had created typings for lodash-es also, so now you can actually do the following

install

npm install lodash-es -S
npm install @types/lodash-es -D

usage

import kebabCase from "lodash-es/kebabCase";
const wings = kebabCase("chickenWings");

if you use rollup, i suggest using this instead of the lodash as it will be treeshaken properly.

Javascript string replace with regex to strip off illegal characters

What you need are character classes. In that, you've only to worry about the ], \ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ).

Syntax: [characters] where characters is a list with characters.

Example:

var cleanString = dirtyString.replace(/[|&;$%@"<>()+,]/g, "");

Best Practices for Custom Helpers in Laravel 5

in dir bootstrap\autoload.php

require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/../app/Helpers/function.php'; //add

add this file

app\Helpers\function.php

Learning Ruby on Rails

I'm currently learning RoR, here's what I've done so far: 1. Read, and followed, SitePoint's "Simply Rails 2.2" 2. Read, and followed, Oreilly's "Rails, Up and Running" 2nd edition.

Those two books are very instructive, and take the same approach in different styles; the second book is a little more aggressive, which is good if you have some RoR knowledge.

As posted above, be extremely careful when reading resources, there are A LOT of outdated videos and articles.

How to get CPU temperature?

I extracted the CPU part from Open Hardware Monitor into a separated library, exposing sensors and members normally hidden into OHM. It also includes many updates (like the support for Ryzen and Xeon) because on OHM they don't accept pull requests since 2015.

https://www.nuget.org/packages/HardwareProviders.CPU.Standard/

Let know your opinion :)

java.io.IOException: Server returned HTTP response code: 500

This Status Code 500 is an Internal Server Error. This code indicates that a part of the server (for example, a CGI program) has crashed or encountered a configuration error.

i think the problem does'nt lie on your side, but rather on the side of the Http server. the resources you used to access may have been moved or get corrupted, or its configuration just may have altered or spoiled

matplotlib: plot multiple columns of pandas data frame on the bar chart

You can plot several columns at once by supplying a list of column names to the plot's y argument.

df.plot(x="X", y=["A", "B", "C"], kind="bar")

enter image description here

This will produce a graph where bars are sitting next to each other.

In order to have them overlapping, you would need to call plot several times, and supplying the axes to plot to as an argument ax to the plot.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

y = np.random.rand(10,4)
y[:,0]= np.arange(10)
df = pd.DataFrame(y, columns=["X", "A", "B", "C"])

ax = df.plot(x="X", y="A", kind="bar")
df.plot(x="X", y="B", kind="bar", ax=ax, color="C2")
df.plot(x="X", y="C", kind="bar", ax=ax, color="C3")

plt.show()

enter image description here

Java balanced expressions check {[()]}

Please try this I checked it. It works correctly

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class CloseBrackets {
    private static Map<Character, Character> leftChar = new HashMap<>();
    private static Map<Character, Character> rightChar = new HashMap<>();

    static {
        leftChar.put('(', '(');
        rightChar.put(')', '(');
        leftChar.put('[', '[');
        rightChar.put(']', '[');
        leftChar.put('{', '{');
        rightChar.put('}', '{');
    }

    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String st = bf.readLine();
        System.out.println(isBalanced(st));
    }

    public static boolean isBalanced(String str) {

        boolean result = false;
        if (str.length() < 2)
            return false;
        Stack<Character> stack = new Stack<>();
        /* For Example I gave input 
         * str = "{()[]}" 
         */

        for (int i = 0; i < str.length(); i++) {

            char ch = str.charAt(i);
            if (!rightChar.containsKey(ch) && !leftChar.containsKey(ch)) {
                continue;
            }
            // Left bracket only add to stack. Other wise it will goes to else case 
            // For both above input how value added in stack 
            // "{(" after close bracket go to else case
            if (leftChar.containsKey(ch)) {
                stack.push(ch);
            } else {
                if (!stack.isEmpty()) {
                    // For both input how it performs
                    // 3rd character is close bracket so it will pop . pop value is "(" and map value for ")" key will "(" . So both are same . 
                    // it will return true. 
                    // now stack will contain only "{" , and travers to next up to end.
                    if (stack.pop() == rightChar.get(ch).charValue() || stack.isEmpty()) {
                        result = true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            }

        }
        if (!stack.isEmpty())
            return result = false;
        return result;
    }
}