Programs & Examples On #Downgrade

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

I know this doesn't help you, but I have to say that this is one of the reasons I jumped from XAMPP to WampServer. WampServer lets you install multiple versions of PHP, Apache and/or MySQL, and switch between them all via a menu option.

Downgrade npm to an older version

npm install -g npm@4

This will install the latest version on the major release 4, no no need to specify version number. Replace 4 with whatever major release you want.

How to downgrade Xcode to previous version?

I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

EC2 Instance Cloning

The easier way is through the web management console:

  1. go to the instance
  2. select the instance and click on instance action
  3. create image

Once you have an image you can launch another cloned instance, data and all. :)

How can I disable ARC for a single file in a project?

Note: if you want to disable ARC for many files, you have to:

  1. open "Build phases" -> "Compile sources"
  2. select files with "left_mouse" + "cmd" (for separated files) or + "shift" (for grouped files - select first and last)
  3. press "enter"
  4. paste -fno-objc-arc
  5. press "enter" again
  6. profit!

Remove all the elements that occur in one list from another

Expanding on Donut's answer and the other answers here, you can get even better results by using a generator comprehension instead of a list comprehension, and by using a set data structure (since the in operator is O(n) on a list but O(1) on a set).

So here's a function that would work for you:

def filter_list(full_list, excludes):
    s = set(excludes)
    return (x for x in full_list if x not in s)

The result will be an iterable that will lazily fetch the filtered list. If you need a real list object (e.g. if you need to do a len() on the result), then you can easily build a list like so:

filtered_list = list(filter_list(full_list, excludes))

How to create a drop shadow only on one side of an element?

This code pen (not by me) demonstrates a super simple way of doing this and the other sides by themselves quite nicely:

box-shadow: 0 5px 5px -5px #333;

https://codepen.io/zeckdude/pen/oxywmm

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

System.Data.OracleClient requires Oracle client software version 8.1.7

The author of this post (now deleted post) suggests checking your C:\Windows\System32 folder to make sure that the oci.dll exists there. Copying in the file from the Oracle home directory solved this problem for me.

Batch file for PuTTY/PSFTP file transfer automation

You need to store the psftp script (lines from open to bye) into a separate file and pass that to psftp using -b switch:

cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b


EDIT: For username+password: As you cannot use psftp commands in a batch file, for the same reason, you cannot specify the username and the password as psftp commands. These are inputs to the open command. While you can specify the username with the open command (open <user>@<IP>), you cannot specify the password this way. This can be done on a psftp command line only. Then it's probably cleaner to do all on the command-line:

cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>

And remove the open, <user> and <PW> lines from your script.txt.

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw


What you are doing atm is that you run psftp without any parameter or commands. Once you exit it (like by typing bye), your batch file continues trying to run open command (and others), what Windows shell obviously does not understand.


If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:

(
    echo cd ...
    echo lcd ...
    echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.


As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
{
    int a;
    int b;
    int c;
};

auto compare( Foo const& x, Foo const& y )
    -> int
{
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );
}

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.


With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

endforeach in loops?

How about that?

<?php
    while($items = array_pop($lists)){
        echo "<ul>";
        foreach($items as $item){
            echo "<li>$item</li>";
        }
        echo "</ul>";
    }
?>

Where is svn.exe in my machine?

If you'd like to use SVN.EXE, there are several companies that compile official binaries that are available for free download. For example, Collabnet:

http://www.open.collab.net/downloads/subversion/

What is token-based authentication?

A token is a piece of data which only Server X could possibly have created, and which contains enough data to identify a particular user.

You might present your login information and ask Server X for a token; and then you might present your token and ask Server X to perform some user-specific action.

Tokens are created using various combinations of various techniques from the field of cryptography as well as with input from the wider field of security research. If you decide to go and create your own token system, you had best be really smart.

Convert DOS line endings to Linux line endings in Vim

From Wikia:

%s/\r\+$//g

That will find all carriage return signs (one and more reps) up to the end of line and delete, so just \n will stay at EOL.

How do I resolve `The following packages have unmet dependencies`

I tried lots of method but below work like charm....

After this command run these :-

curl -sL https://deb.nodesource.com/setup_14.x 565 | sudo -E bash -
sudo apt-get install -y nodejs

Now check…

node -v
npm -v

Invoke-customs are only supported starting with android 0 --min-api 26

After hours of struggling, I solved it by including the following within app/build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

https://github.com/mapbox/mapbox-gl-native/issues/11378

How to wait in a batch script?

What about:

@echo off
set wait=%1
echo waiting %wait% s
echo wscript.sleep %wait%000 > wait.vbs
wscript.exe wait.vbs
del wait.vbs

Run react-native application on iOS device directly from command line?

First install the required library globally on your computer:

npm install -g ios-deploy

Go to your settings on your iPhone to find the name of the device.

Then provide that below like:

react-native run-ios --device "______\'s iPhone"

Sometimes this will fail and output a message like this:

Found Xcode project ________.xcodeproj
Could not find device with the name: "_______'s iPhone".
Choose one of the following:
______’s iPhone Udid: _________

That udid is used like this:

react-native run-ios --udid 0412e2c230a14e23451699

Optionally you may use:

react-native run-ios --udid 0412e2c230a14e23451699 -- configuration Release

Angular.js: How does $eval work and why is it different from vanilla eval?

I think one of the original questions here was not answered. I believe that vanilla eval() is not used because then angular apps would not work as Chrome apps, which explicitly prevent eval() from being used for security reasons.

How to show DatePickerDialog on Button click?

    final Calendar newCalendar = Calendar.getInstance();
    final DatePickerDialog  StartTime = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                    Calendar newDate = Calendar.getInstance();
                    newDate.set(year, monthOfYear, dayOfMonth);
                    activitydate.setText(dateFormatter.format(newDate.getTime()));
                }
    
            }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
    
      btn_checkin.setOnClickListener(new View.OnClickListener() {
@Override   public void onClick(View v) {
         StartTime.show():    
     });

design a stack such that getMinimum( ) should be O(1)

Let's assume the stack which we will be working on is this :

6 , minvalue=2
2 , minvalue=2
5 , minvalue=3
3 , minvalue=3
9 , minvalue=7
7 , minvalue=7
8 , minvalue=8

In the above representation the stack is only built by left value's the right value's [minvalue] is written only for illustration purpose which will be stored in one variable.

The actual Problem is when the value which is the minimun value get's removed at that point how can we know what is the next minimum element without iterating over the stack.

Like for example in our stack when 6 get's popped we know that ,this is not the minimum element because the minimum element is 2 ,so we can safely remove this without updating our min value.

But when we pop 2 ,we can see that the minimum value is 2 right now and if this get's popped out then we need to update the minimum value to 3.

Point1:

Now if you observe carefully we need to generate minvalue=3 from this particular state [2 , minvalue=2]. or if you go depperin the stack we need to generate minvalue=7 from this particular state [3 , minvalue=3] or if you go more depper in the stack then we need to generate minvalue=8 from this particular state[7 , minvalue=7]

Did you notice something in common in all of the above 3 cases the value which we need to generate depends upon two variable which are both equal. Correct. Why is this happening because when we push some element smaller then the current minvalue, then we basically push that element in the stack and updated the same number in minvalue also.

Point2:

So we are basically storing duplicate of the same number once in stack and once in minvalue variable. We need to focus on avoiding this duplication and store something useful data in the stack or the minvalue to generate the previous minimum as shown in CASES above.

Let's focus on what should we store in stack when the value to store in push is less than the minmumvalue. Let's name this variable y , so now our stack will look something like this:

6 , minvalue=2
y1 , minvalue=2
5 , minvalue=3
y2 , minvalue=3
9 , minvalue=7
y3 , minvalue=7
8 , minvalue=8

I have renamed them as y1,y2,y3 to avoid confusion that all of them will have same value.

Point3:

Now Let's try to find some constraint's over y1,y2and y3. Do you remember when exactly we need to update the minvalue while doing pop() ,only when we have popped the element which is equal to the minvalue. If we pop something greater than the minvalue then we don't have to update minvalue. So to trigger the update of minvalue, y1,y2&y3 should be smaller than there corresponding minvalue .[We are avoding equality to avoid duplicate[Point2]] so the constrain is [ y < minValue ].

Now let's come back to populate y ,we need to generate some value and put y at the time of push ,remember. Let's take the value which is coming for push to be x which is less that the prevMinvalue,and the value which we will actually push in stack to be y. So one thing is obvious that the newMinValue=x , and y < newMinvalue.

Now we need to calulate y(remember y can be anynumber which is less than newMinValue(x) so we need to find some number which can fulfill our constraint) with the help of prevMinvalue and x(newMinvalue).

Let's do the math:
    x < prevMinvalue [Given]
    x - prevMinvalue < 0 
    x - prevMinValue + x < 0 + x [Add x on both side]
    2*x - prevMinValue < x      
this is the y which we were looking for less than x(newMinValue).
y = 2*x - prevMinValue. 'or' y = 2*newMinValue - prevMinValue 'or' y = 2*curMinValue - prevMinValue [taking curMinValue=newMinValue].

So at the time of pushing x if it is less than prevMinvalue then we push y[2*x-prevMinValue] and update newMinValue = x .

And at the time of pop if the stack contains something less than the minValue then that's our trigger to update the minVAlue. We have to calculate prevMinValue from the curMinValue and y. y = 2*curMinValue - prevMinValue [Proved] prevMinVAlue = 2*curMinvalue - y .

2*curMinValue - y is the number which we need to update now to the prevMinValue.

Code for the same logic is shared below with O(1) time and O(1) space complexity.

// C++ program to implement a stack that supports 
// getMinimum() in O(1) time and O(1) extra space. 
#include <bits/stdc++.h> 
using namespace std; 

// A user defined stack that supports getMin() in 
// addition to push() and pop() 
struct MyStack 
{ 
    stack<int> s; 
    int minEle; 

    // Prints minimum element of MyStack 
    void getMin() 
    { 
        if (s.empty()) 
            cout << "Stack is empty\n"; 

        // variable minEle stores the minimum element 
        // in the stack. 
        else
            cout <<"Minimum Element in the stack is: "
                 << minEle << "\n"; 
    } 

    // Prints top element of MyStack 
    void peek() 
    { 
        if (s.empty()) 
        { 
            cout << "Stack is empty "; 
            return; 
        } 

        int t = s.top(); // Top element. 

        cout << "Top Most Element is: "; 

        // If t < minEle means minEle stores 
        // value of t. 
        (t < minEle)? cout << minEle: cout << t; 
    } 

    // Remove the top element from MyStack 
    void pop() 
    { 
        if (s.empty()) 
        { 
            cout << "Stack is empty\n"; 
            return; 
        } 

        cout << "Top Most Element Removed: "; 
        int t = s.top(); 
        s.pop(); 

        // Minimum will change as the minimum element 
        // of the stack is being removed. 
        if (t < minEle) 
        { 
            cout << minEle << "\n"; 
            minEle = 2*minEle - t; 
        } 

        else
            cout << t << "\n"; 
    } 

    // Removes top element from MyStack 
    void push(int x) 
    { 
        // Insert new number into the stack 
        if (s.empty()) 
        { 
            minEle = x; 
            s.push(x); 
            cout <<  "Number Inserted: " << x << "\n"; 
            return; 
        } 

        // If new number is less than minEle 
        if (x < minEle) 
        { 
            s.push(2*x - minEle); 
            minEle = x; 
        } 

        else
           s.push(x); 

        cout <<  "Number Inserted: " << x << "\n"; 
    } 
}; 

// Driver Code 
int main() 
{ 
    MyStack s; 
    s.push(3); 
    s.push(5); 
    s.getMin(); 
    s.push(2); 
    s.push(1); 
    s.getMin(); 
    s.pop(); 
    s.getMin(); 
    s.pop(); 
    s.peek(); 

    return 0; 
} 

How do I consume the JSON POST data in an Express application

Sometimes you don't need third party libraries to parse JSON from text. Sometimes all you need it the following JS command, try it first:

        const res_data = JSON.parse(body);

What is an index in SQL?

An index is used to speed up the performance of queries. It does this by reducing the number of database data pages that have to be visited/scanned.

In SQL Server, a clustered index determines the physical order of data in a table. There can be only one clustered index per table (the clustered index IS the table). All other indexes on a table are termed non-clustered.

How to tag docker image with docker-compose

If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image:

build: ./dir
image: webapp:tag

This results in an image named webapp and tagged tag, built from ./dir.

https://docs.docker.com/compose/compose-file/#build

HTML5 image icon to input placeholder

  1. You can set it as background-image and use text-indent or a padding to shift the text to the right.
  2. You can break it up into two elements.

Honestly, I would avoid usage of HTML5/CSS3 without a good fallback. There are just too many people using old browsers that don't support all the new fancy stuff. It will take a while before we can drop the fallback, unfortunately :(

The first method I mentioned is the safest and easiest. Both ways requires Javascript to hide the icon.

CSS:

input#search {
    background-image: url(bg.jpg);
    background-repeat: no-repeat;
    text-indent: 20px;
}

HTML:

<input type="text" id="search" name="search" onchange="hideIcon(this);" value="search" />

Javascript:

function hideIcon(self) {
    self.style.backgroundImage = 'none';
}

September 25h, 2013

I can't believe I said "Both ways requires JavaScript to hide the icon.", because this is not entirely true.

The most common timing to hide placeholder text is on change, as suggested in this answer. For icons however it's okay to hide them on focus which can be done in CSS with the active pseudo-class.

#search:active { background-image: none; }

Heck, using CSS3 you can make it fade away!

http://jsfiddle.net/2tTxE/


November 5th, 2013

Of course, there's the CSS3 ::before pseudo-elements too. Beware of browser support though!

            Chrome  Firefox     IE      Opera   Safari
:before     (yes)   1.0         8.0     4       4.0
::before    (yes)   1.5         9.0     7       4.0

https://developer.mozilla.org/en-US/docs/Web/CSS/::before

Select first 10 distinct rows in mysql

SELECT  DISTINCT *
FROM    people
WHERE   names = 'Smith'
ORDER BY
        names
LIMIT 10

How do I update Anaconda?

This is what the official Anaconda documentation recommends:

conda update conda
conda update anaconda=2020.07

If the second line throws an error (typo in the documentation?) this worked here:

conda install anaconda=2020.07

(You can find all version specifier here.)

The command will update to a specific release of the Anaconda meta-package.

This is, IMHO, what 95% of Anaconda users want. Simply upgrading to the latest version of the Anaconda meta-package (put together and tested by the Anaconda Distributors) and not caring about the update status of individual packages (which would be issued by conda update --all).

Pass array to MySQL stored routine

Use a join with a temporary table. You don't need to pass temporary tables to functions, they are global.

create temporary table ids( id int ) ;
insert into ids values (1),(2),(3) ;

delimiter //
drop procedure if exists tsel //
create procedure tsel() -- uses temporary table named ids. no params
READS SQL DATA
BEGIN
  -- use the temporary table `ids` in the SELECT statement or
  -- whatever query you have
  select * from Users INNER JOIN ids on userId=ids.id ;
END //
DELIMITER ;

CALL tsel() ; -- call the procedure

How to pip install a package with min and max version range?

you can also use:

pip install package==0.5.*

which is more consistent and easy to read.

How do I install SciPy on 64 bit Windows?

I haven't tried it, but you may want to download this version of Portable Python. It comes with Scipy-0.7.0b1 running on Python 2.5.4.

Javascript Uncaught Reference error Function is not defined

In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers.

Easiest fix is to change:

function something(...)

To:

window.something = function(...)

How to use icons and symbols from "Font Awesome" on Native Android Application

As all answers are great but I didn't want to use a library and each solution with just one line java code made my Activities and Fragments very messy. So I over wrote the TextView class as follows:

public class FontAwesomeTextView extends TextView {
private static final String TAG = "TextViewFontAwesome";
public FontAwesomeTextView(Context context) {
    super(context);
    init();
}

public FontAwesomeTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FontAwesomeTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init();
}

private void setCustomFont(Context ctx, AttributeSet attrs) {
    TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
    String customFont = a.getString(R.styleable.TextViewPlus_customFont);
    setCustomFont(ctx, customFont);
    a.recycle();
}

private void init() {
    if (!isInEditMode()) {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fontawesome-webfont.ttf");
        setTypeface(tf);
    }
}

public boolean setCustomFont(Context ctx, String asset) {
    Typeface typeface = null;
    try {
        typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
    } catch (Exception e) {
        Log.e(TAG, "Unable to load typeface: "+e.getMessage());
        return false;
    }

    setTypeface(typeface);
    return true;
}
}

what you should do is copy the font ttf file into assets folder .And use this cheat sheet for finding each icons string.

hope this helps.

TLS 1.2 in .NET Framework 4.0

I meet the same issue on a Windows installed .NET Framework 4.0.
And I Solved this issue by installing .NET Framework 4.6.2.
Or you may download the newest package to have a try.

What is the best way to detect a mobile device?

Checkout http://detectmobilebrowsers.com/ which provides you script for detecting mobile device in variety of languages including

JavaScript, jQuery, PHP, JSP, Perl, Python, ASP, C#, ColdFusion and many more

Print a file's last modified date in Bash

Isn't the 'date' command much simpler? No need for awk, stat, etc.

date -r <filename>

Also, consider looking at the man page for date formatting; for example with common date and time format:

date -r <filename> "+%m-%d-%Y %H:%M:%S"

Understanding the Linux oom-killer's logs

This webpage have an explanation and a solution.

The solution is:

To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:

vm.overcommit_memory = 2

vm.overcommit_ratio = 80

How to print out the method name and line number and conditionally disable NSLog?

Here are some useful macros around NSLog I use a lot:

#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#   define DLog(...)
#endif

// ALog always displays output regardless of the DEBUG setting
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

The DLog macro is used to only output when the DEBUG variable is set (-DDEBUG in the projects's C flags for the debug confirguration).

ALog will always output text (like the regular NSLog).

The output (e.g. ALog(@"Hello world") ) will look like this:

-[LibraryController awakeFromNib] [Line 364] Hello world

How to automatically crop and center an image

Try this:

#yourElementId
{
    background: url(yourImageLocation.jpg) no-repeat center center;
    width: 100px;
    height: 100px;
}

Keep in mind that width and height will only work if your DOM element has layout (a block displayed element, like a div or an img). If it is not (a span, for example), add display: block; to the CSS rules. If you do not have access to the CSS files, drop the styles inline in the element.

How to add text at the end of each line in Vim?

:%s/$/,/g

$ matches end of line

Sort a Custom Class List<T>

You can use linq:

var q = from tag in Week orderby Convert.ToDateTime(tag.date) select tag;
List<cTag> Sorted = q.ToList()

Hour from DateTime? in 24 hours format

Try this, if your input is string 
For example 

string input= "13:01";
string[] arry = input.Split(':');                  
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)

 {

DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)), 
int.Parse(timeinput.Substring(2, 2)), 0); 
return startTime.ToString("hh:mm tt");

}
out put: 01:01

MySQL Cannot Add Foreign Key Constraint

I had similar error with two foreign keys for different tables but with same key names! I have renamed keys and the error had gone)

Python: No acceptable C compiler found in $PATH when installing python

Issue :

configure: error: no acceptable C compiler found in $PATH

Fixed the issue by executing the following command:

yum install gcc

to install gcc.

border-radius not working

Im just highlighting part of @Ethan May answer which is

overflow: hidden;

It would most probably do the work for your case.

Convert UTC dates to local time in PHP

I store date in the DB in UTC format but then I show them to the final user in their local timezone

// retrieve
$d = (new \DateTime($val . ' UTC'))->format('U');
return date("Y-m-d H:i:s", $d);

Importing Maven project into Eclipse

Since Eclipse Neon which contains Eclipse Maven Integration (m2e) 1.7, the preferred way is one of the following ways:

  • File > Projects from File System... - This works for Eclipse projects (containing the file .project) as well as for non-Eclipse projects that only contain the file pom.xml.
  • If importing from a Git repository, in the Git Repositories view right-click the repository node, one folder or multiple selected folders in the Working Tree and choose Import Projects.... This opens the same dialog, but you don't have to select the directory.

insert vertical divider line between two nested divs, not full height

Try this. I set the blue box to float right, gave left and right a fixed height, and added a white border on the right of the left div. Also added rounded corners to more match your example (These won't work in ie 8 or less). I also took out the position: relative. You don't need it. Block level elements are set to position relative by default.

See it here: http://jsfiddle.net/ZSgLJ/

#left {
  float: left;
  width: 44%;
  margin: 0;
  padding: 0;
  border-right: 1px solid white;
  height:400px;
}

#right {
  position: relative;
  float: right;
  width: 49%;
  margin: 0;
  padding: 0;
  height:400px;
}

#blue_box {
  background-color:blue;
  border-radius: 10px;
  -moz-border-radius:10px;
  -webkit-border-radius: 10px;
  width: 45%;
  min-width: 400px;
  max-width: 600px;
  padding: 2%;
  float: right;
}

How to resolve "must be an instance of string, string given" prior to PHP 7?

I think typecasting on php on inside block, String on PHP is not object as I know:

<?php
function phpwtf($s) {
    $s = (string) $s;
    echo "$s\n";
}
phpwtf("Type hinting is da bomb");

Fastest way to iterate over all the chars in a String

Looks like niether is faster or slower

    public static void main(String arguments[]) {


        //Build a long string
        StringBuilder sb = new StringBuilder();
        for(int j = 0; j < 10000; j++) {
            sb.append("a really, really long string");
        }
        String str = sb.toString();
        for (int testscount = 0; testscount < 10; testscount ++) {


            //Test 1
            long start = System.currentTimeMillis();
            for(int c = 0; c < 10000000; c++) {
                for (int i = 0, n = str.length(); i < n; i++) {
                    char chr = str.charAt(i);
                    doSomethingWithChar(chr);//To trick JIT optimistaion
                }
            }

            System.out.println("1: " + (System.currentTimeMillis() - start));

            //Test 2
            start = System.currentTimeMillis();
            char[] chars = str.toCharArray();
            for(int c = 0; c < 10000000; c++) {
                for (int i = 0, n = chars.length; i < n; i++) {
                    char chr = chars[i];
                    doSomethingWithChar(chr);//To trick JIT optimistaion
                }
            }
            System.out.println("2: " + (System.currentTimeMillis() - start));
            System.out.println();
        }


    }


    public static void doSomethingWithChar(char chr) {
        int newInt = chr << 2;
    }

For long strings I'll chose the first one. Why copy around long strings? Documentations says:

public char[] toCharArray() Converts this string to a new character array.

Returns: a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.

//Edit 1

I've changed the test to trick JIT optimisation.

//Edit 2

Repeat test 10 times to let JVM warm up.

//Edit 3

Conclusions:

First of all str.toCharArray(); copies entire string in memory. It can be memory consuming for long strings. Method String.charAt( ) looks up char in char array inside String class checking index before. It looks like for short enough Strings first method (i.e. chatAt method) is a bit slower due to this index check. But if the String is long enough, copying whole char array gets slower, and the first method is faster. The longer the string is, the slower toCharArray performs. Try to change limit in for(int j = 0; j < 10000; j++) loop to see it. If we let JVM warm up code runs faster, but proportions are the same.

After all it's just micro-optimisation.

How to install Android SDK Build Tools on the command line?

Try

1. List all packages

android list sdk --all

2. Install packages using following command

android update sdk -u -a -t package1, package2, package3 //comma seperated packages obtained using list command 

Convert wchar_t to char

You are looking for wctomb(): it's in the ANSI standard, so you can count on it. It works even when the wchar_t uses a code above 255. You almost certainly do not want to use it.


wchar_t is an integral type, so your compiler won't complain if you actually do:

char x = (char)wc;

but because it's an integral type, there's absolutely no reason to do this. If you accidentally read Herbert Schildt's C: The Complete Reference, or any C book based on it, then you're completely and grossly misinformed. Characters should be of type int or better. That means you should be writing this:

int x = getchar();

and not this:

char x = getchar(); /* <- WRONG! */

As far as integral types go, char is worthless. You shouldn't make functions that take parameters of type char, and you should not create temporary variables of type char, and the same advice goes for wchar_t as well.

char* may be a convenient typedef for a character string, but it is a novice mistake to think of this as an "array of characters" or a "pointer to an array of characters" - despite what the cdecl tool says. Treating it as an actual array of characters with nonsense like this:

for(int i = 0; s[i]; ++i) {
  wchar_t wc = s[i];
  char c = doit(wc);
  out[i] = c;
}

is absurdly wrong. It will not do what you want; it will break in subtle and serious ways, behave differently on different platforms, and you will most certainly confuse the hell out of your users. If you see this, you are trying to reimplement wctombs() which is part of ANSI C already, but it's still wrong.

You're really looking for iconv(), which converts a character string from one encoding (even if it's packed into a wchar_t array), into a character string of another encoding.

Now go read this, to learn what's wrong with iconv.

How to create a generic array in Java?

I have found a quick and easy way that works for me. Note that i have only used this on Java JDK 8. I don't know if it will work with previous versions.

Although we cannot instantiate a generic array of a specific type parameter, we can pass an already created array to a generic class constructor.

class GenArray <T> {
    private T theArray[]; // reference array

    // ...

    GenArray(T[] arr) {
        theArray = arr;
    }

    // Do whatever with the array...
}

Now in main we can create the array like so:

class GenArrayDemo {
    public static void main(String[] args) {
        int size = 10; // array size
        // Here we can instantiate the array of the type we want, say Character (no primitive types allowed in generics)
        Character[] ar = new Character[size];

        GenArray<Character> = new Character<>(ar); // create the generic Array

        // ...

    }
}

For more flexibility with your arrays you can use a linked list eg. the ArrayList and other methods found in the Java.util.ArrayList class.

TextView - setting the text size programmatically doesn't seem to work

Please see this link for more information on setting the text size in code. Basically it says:

public void setTextSize (int unit, float size)

Since: API Level 1 Set the default text size to a given unit and value. See TypedValue for the possible dimension units. Related XML Attributes

android:textSize Parameters

unit The desired dimension unit.
size The desired size in the given units.

Getting value from appsettings.json in .net core

For ASP.NET Core 3.1 you can follow this guide:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

When you create a new ASP.NET Core 3.1 project you will have the following configuration line in Program.cs:

Host.CreateDefaultBuilder(args)

This enables the following:

  1. ChainedConfigurationProvider : Adds an existing IConfiguration as a source. In the default configuration case, adds the host configuration and setting it as the first source for the app configuration.
  2. appsettings.json using the JSON configuration provider.
  3. appsettings.Environment.json using the JSON configuration provider. For example, appsettings.Production.json and appsettings.Development.json.
  4. App secrets when the app runs in the Development environment.
  5. Environment variables using the Environment Variables configuration provider.
  6. Command-line arguments using the Command-line configuration provider.

This means you can inject IConfiguration and fetch values with a string key, even nested values. Like IConfiguration["Parent:Child"];

Example:

appsettings.json

{
  "ApplicationInsights":
    {
        "Instrumentationkey":"putrealikeyhere"
    }
}

WeatherForecast.cs

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IConfiguration _configuration;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var key = _configuration["ApplicationInsights:InstrumentationKey"];

        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

How do I dynamically assign properties to an object in TypeScript?

If you are using Typescript, presumably you want to use the type safety; in which case naked Object and 'any' are counterindicated.

Better to not use Object or {}, but some named type; or you might be using an API with specific types, which you need extend with your own fields. I've found this to work:

class Given { ... }  // API specified fields; or maybe it's just Object {}

interface PropAble extends Given {
    props?: string;  // you can cast any Given to this and set .props
    // '?' indicates that the field is optional
}
let g:Given = getTheGivenObject();
(g as PropAble).props = "value for my new field";

// to avoid constantly casting: 
let k:PropAble = getTheGivenObject();
k.props = "value for props";

How do I collapse a table row in Bootstrap?

Which version of Bootstrap are you using? I was perplexed that I could get @Chad's solution to work in jsfiddle, but not locally. So, I checked the version of Bootstrap used by jsfiddle, and it's using a 3.0.0-rc1 release, while the default download on getbootstrap.com is version 2.3.2.

In 2.3.2 the collapse class wasn't getting replaced by the in class. The in class was simply getting appended when the button was clicked. In version 3.0.0-rc1, the collapse class correctly is removed, and the <tr> collapses.

Use @Chad's solution for the html, and try using these links for referencing Bootstrap:

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css" rel="stylesheet">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>

How to convert date in to yyyy-MM-dd Format?

Use this.

java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);

you will get the output as

2012-12-01

How can I remove a child node in HTML using JavaScript?

A jQuery solution

HTML

<select id="foo">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Javascript

// remove child "option" element with a "value" attribute equal to "2"
$("#foo > option[value='2']").remove();

// remove all child "option" elements
$("#foo > option").remove();

References:

Attribute Equals Selector [name=value]

Selects elements that have the specified attribute with a value exactly equal to a certain value.

Child Selector (“parent > child”)

Selects all direct child elements specified by "child" of elements specified by "parent"

.remove()

Similar to .empty(), the .remove() method takes elements out of the DOM. We use .remove() when we want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

How to find whether a ResultSet is empty or not in Java?

Calculates the size of the java.sql.ResultSet:

int size = 0;
if (rs != null) {
    rs.beforeFirst();
    rs.last();
    size = rs.getRow();
}

(Source)

php var_dump() vs print_r()

Generally, print_r( ) output is nicer, more concise and easier to read, aka more human-readable but cannot show data types.

With print_r() you can also store the output into a variable:

$output = print_r($array, true);

which var_dump() cannot do. Yet var_dump() can show data types.

Batch file include external file for variables

If the external configuration file is also valid batch file, you can just use:

call externalconfig.bat

inside your script. Try creating following a.bat:

@echo off
call b.bat
echo %MYVAR%

and b.bat:

set MYVAR=test

Running a.bat should generate output:

test

Floating Point Exception C++ Why and what is it?

for (i>0; i--;)

is probably wrong and should be

for (; i>0; i--)

instead. Note where I put the semicolons. The condition goes in the middle, not at the start.

How to check if a network port is open on linux?

If you want to use this in a more general context, you should make sure, that the socket that you open also gets closed. So the check should be more like this:

import socket
from contextlib import closing

def check_socket(host, port):
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
        if sock.connect_ex((host, port)) == 0:
            print "Port is open"
        else:
            print "Port is not open"

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

Smooth scrolling when clicking an anchor link

There are already a lot of good answers here - however they are all missing the fact that empty anchors have to be excluded. Otherwise those scripts generate JavaScript errors as soon as an empty anchor is clicked.

In my opinion the correct answer is like this:

$('a[href*=\\#]:not([href$=\\#])').click(function() {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

git: undo all working dir changes including new files

I thought it was (warning: following will wipe out everything)

$ git reset --hard HEAD
$ git clean -fd

The reset to undo changes. The clean to remove any untracked files and directories.

How to center the content inside a linear layout?

android:layout_gravity is used for the layout itself

Use android:gravity="center" for children of your LinearLayout

So your code should be:

<LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_weight="1" >

Can we instantiate an abstract class?

Technical Answer

Abstract classes cannot be instantiated - this is by definition and design.

From the JLS, Chapter 8. Classes:

A named class may be declared abstract (§8.1.1.1) and must be declared abstract if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses.

From JSE 6 java doc for Classes.newInstance():

InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.

You can, of course, instantiate a concrete subclass of an abstract class (including an anonymous subclass) and also carry out a typecast of an object reference to an abstract type.

A Different Angle On This - Teamplay & Social Intelligence:

This sort of technical misunderstanding happens frequently in the real world when we deal with complex technologies and legalistic specifications.

"People Skills" can be more important here than "Technical Skills". If competitively and aggressively trying to prove your side of the argument, then you could be theoretically right, but you could also do more damage in having a fight / damaging "face" / creating an enemy than it is worth. Be reconciliatory and understanding in resolving your differences. Who knows - maybe you're "both right" but working off slightly different meanings for terms??

Who knows - though not likely, it is possible the interviewer deliberately introduced a small conflict/misunderstanding to put you into a challenging situation and see how you behave emotionally and socially. Be gracious and constructive with colleagues, follow advice from seniors, and follow through after the interview to resolve any challenge/misunderstanding - via email or phone call. Shows you're motivated and detail-oriented.

Dump all tables in CSV format using 'mysqldump'

It looks like others had this problem also, and there is a simple Python script now, for converting output of mysqldump into CSV files.

wget https://raw.githubusercontent.com/jamesmishra/mysqldump-to-csv/master/mysqldump_to_csv.py
mysqldump -u username -p --host=rdshostname database table | python mysqldump_to_csv.py > table.csv

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

To answer the initial question "how to properly pass routedata to error controller?":

IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

Then in your ErrorController class, implement a function like this:

[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Error(Exception exception)
{
    return View("Error", exception);
}

This pushes the exception into the View. The view page should be declared as follows:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<System.Exception>" %>

And the code to display the error:

<% if(Model != null) { %>  <p><b>Detailed error:</b><br />  <span class="error"><%= Helpers.General.GetErrorMessage((Exception)Model, false) %></span></p> <% } %>

Here is the function that gathers the all exception messages from the exception tree:

    public static string GetErrorMessage(Exception ex, bool includeStackTrace)
    {
        StringBuilder msg = new StringBuilder();
        BuildErrorMessage(ex, ref msg);
        if (includeStackTrace)
        {
            msg.Append("\n");
            msg.Append(ex.StackTrace);
        }
        return msg.ToString();
    }

    private static void BuildErrorMessage(Exception ex, ref StringBuilder msg)
    {
        if (ex != null)
        {
            msg.Append(ex.Message);
            msg.Append("\n");
            if (ex.InnerException != null)
            {
                BuildErrorMessage(ex.InnerException, ref msg);
            }
        }
    }

Link vs compile vs controller

Compile :

This is the phase where Angular actually compiles your directive. This compile function is called just once for each references to the given directive. For example, say you are using the ng-repeat directive. ng-repeat will have to look up the element it is attached to, extract the html fragment that it is attached to and create a template function.

If you have used HandleBars, underscore templates or equivalent, its like compiling their templates to extract out a template function. To this template function you pass data and the return value of that function is the html with the data in the right places.

The compilation phase is that step in Angular which returns the template function. This template function in angular is called the linking function.

Linking phase :

The linking phase is where you attach the data ( $scope ) to the linking function and it should return you the linked html. Since the directive also specifies where this html goes or what it changes, it is already good to go. This is the function where you want to make changes to the linked html, i.e the html that already has the data attached to it. In angular if you write code in the linking function its generally the post-link function (by default). It is kind of a callback that gets called after the linking function has linked the data with the template.

Controller :

The controller is a place where you put in some directive specific logic. This logic can go into the linking function as well, but then you would have to put that logic on the scope to make it "shareable". The problem with that is that you would then be corrupting the scope with your directives stuff which is not really something that is expected. So what is the alternative if two Directives want to talk to each other / co-operate with each other? Ofcourse you could put all that logic into a service and then make both these directives depend on that service but that just brings in one more dependency. The alternative is to provide a Controller for this scope ( usually isolate scope ? ) and then this controller is injected into another directive when that directive "requires" the other one. See tabs and panes on the first page of angularjs.org for an example.

Sorting Python list based on the length of the string

Write a function lensort to sort a list of strings based on length.

def lensort(a):
    n = len(a)
    for i in range(n):
        for j in range(i+1,n):
            if len(a[i]) > len(a[j]):
                temp = a[i]
                a[i] = a[j]
                a[j] = temp
    return a
print lensort(["hello","bye","good"])

How to round up integer division and have int result in Java?

To round up an integer division you can use

import static java.lang.Math.abs;

public static long roundUp(long num, long divisor) {
    int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
    return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}

or if both numbers are positive

public static long roundUp(long num, long divisor) {
    return (num + divisor - 1) / divisor;
}

Jackson how to transform JsonNode to ArrayNode without casting?

Is there a method equivalent to getJSONArray in org.json so that I have proper error handling in case it isn't an array?

It depends on your input; i.e. the stuff you fetch from the URL. If the value of the "datasets" attribute is an associative array rather than a plain array, you will get a ClassCastException.

But then again, the correctness of your old version also depends on the input. In the situation where your new version throws a ClassCastException, the old version will throw JSONException. Reference: http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)

How to enable support of CPU virtualization on Macbook Pro?

CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.

I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.

Playing Sound In Hidden Tag

That's how I achieved it, which is not visible (HORRIBLE SOUND....)

<!-- horrible is your mp3 file name any other supported format.-->
<audio controls autoplay hidden="" src="horrible.mp3" type ="audio/mp3"">your browser does not support Html5</audio>

How to specify the default error page in web.xml?

You can also do something like that:

<error-page>
    <error-code>403</error-code>
    <location>/403.html</location>
</error-page>

<error-page>
    <location>/error.html</location>
</error-page>

For error code 403 it will return the page 403.html, and for any other error code it will return the page error.html.

How to filter an array of objects based on values in an inner array with jq?

Here is another solution which uses any/2

map(select(any(.Names[]; contains("data"))|not)|.Id)[]

with the sample data and the -r option it produces

cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19

JavaScript, get date of the next day

You can use:

var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);

For example, since there are 30 days in April, the following code will output May 1:

var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000

var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000    

See fiddle.

Running bash script from within python

Making sleep.sh executable and adding shell=True to the parameter list (as suggested in previous answers) works ok. Depending on the search path, you may also need to add ./ or some other appropriate path. (Ie, change "sleep.sh" to "./sleep.sh".)

The shell=True parameter is not needed (under a Posix system like Linux) if the first line of the bash script is a path to a shell; for example, #!/bin/bash.

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Text Editor which shows \r\n?

Slickedit and Notepad2 also show them. In Slickedit you can customize all sorts of invisible characters (whitespace, tabs, CRs, line feeds, ...) and display them with any character you wish.

How can I import Swift code to Objective-C?

If you're using Cocoapods and trying to use a Swift pod in an ObjC project you can simply do the following:

@import <FrameworkName>;

enter image description here

What does the "undefined reference to varName" in C mean?

You need to compile and then link the object files like this:

gcc -c a.c  
gcc -c b.c  
gcc a.o b.o -o prog  

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

I have been using makeaclickablemap for my province maps for some time now and it turned out to be a really good fit.

Pipe output and capture exit status in Bash

There's an array that gives you the exit status of each command in a pipe.

$ cat x| sed 's///'
cat: x: No such file or directory
$ echo $?
0
$ cat x| sed 's///'
cat: x: No such file or directory
$ echo ${PIPESTATUS[*]}
1 0
$ touch x
$ cat x| sed 's'
sed: 1: "s": substitute pattern can not be delimited by newline or backslash
$ echo ${PIPESTATUS[*]}
0 1

How to rearrange Pandas column sequence?

I would suggest you just write a function to do what you're saying probably using drop (to delete columns) and insert to insert columns at a position. There isn't an existing API function to do what you're describing.

How to install CocoaPods?

FOR EL CAPITAN

rvm install ruby-2.2.2.

rvm use ruby-2.2.2.

sudo gem install -n /usr/local/bin cocoapods

How to iterate over arguments in a Bash script

Use "$@" to represent all the arguments:

for var in "$@"
do
    echo "$var"
done

This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:

sh test.sh 1 2 '3 4'
1
2
3 4

How to copy a string of std::string type in C++?

You shouldn't use strcpy() to copy a std::string, only use it for C-Style strings.

If you want to copy a to b then just use the = operator.

string a = "text";
string b = "image";
b = a;

Add a border outside of a UIView (instead of inside)

Unfortunately, there isn't simply a little property you can set to align the border to the outside. It draws aligned to the inside because the UIViews default drawing operations draw within its bounds.

The simplest solution that comes to mind would be to expand the UIView by the size of the border width when applying the border:

CGFloat borderWidth = 2.0f;

self.frame = CGRectInset(self.frame, -borderWidth, -borderWidth);
self.layer.borderColor = [UIColor yellowColor].CGColor;
self.layer.borderWidth = borderWidth;

Total number of items defined in an enum

The question is:

How can I get the number of items defined in an enum?

The number of "items" could really mean two completely different things. Consider the following example.

enum MyEnum
{
    A = 1,
    B = 2,
    C = 1,
    D = 3,
    E = 2
}

What is the number of "items" defined in MyEnum?

Is the number of items 5? (A, B, C, D, E)

Or is it 3? (1, 2, 3)

The number of names defined in MyEnum (5) can be computed as follows.

var namesCount = Enum.GetNames(typeof(MyEnum)).Length;

The number of values defined in MyEnum (3) can be computed as follows.

var valuesCount = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Distinct().Count();

Django - "no module named django.core.management"

In case this is helpful to others... I had this issue because my virtualenv defaulted to python2.7 and I was calling Django using Python3 while using Ubuntu.

to check which python my virtualenv was using:

$ which python3
>> /usr/bin/python3

created new virtualenv with python3 specified (using virtualenv wrapper https://virtualenvwrapper.readthedocs.org/en/latest/):

$ mkvirtualenv --python=/usr/bin/python3 ENV_NAME

the python path should now point to the virtualenv python:

$ which python3
>> /home/user/.virtualenvs/ENV_NAME/bin/python3

How do I set the selected item in a comboBox to match my string using C#?

You don't have that property in the ComboBox. You have SelectedItem or SelectedIndex. If you have the objects you used to fill the combo box then you can use SelectedItem.

If not you can get the collection of items (property Items) and iterate that until you get the value you want and use that with the other properties.

hope it helps.

Best approach to converting Boolean object to string in java

I don't think there would be any significant performance difference between them, but I would prefer the 1st way.

If you have a Boolean reference, Boolean.toString(boolean) will throw NullPointerException if your reference is null. As the reference is unboxed to boolean before being passed to the method.

While, String.valueOf() method as the source code shows, does the explicit null check:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Just test this code:

Boolean b = null;

System.out.println(String.valueOf(b));    // Prints null
System.out.println(Boolean.toString(b));  // Throws NPE

For primitive boolean, there is no difference.

Java: How to access methods from another class

public class WeatherResponse {

private int cod;
private String base;
private Weather main;

public int getCod(){
    return this.cod;
}

public void setCod(int cod){
    this.cod = cod;
}

public String getBase(){
    return base;
}

public void setBase(String base){
    this.base = base;
}

public Weather getWeather() {
    return main;
}

// default constructor, getters and setters
}

another class

public class Weather {

private int id;
private String main;
private String description;

public String getMain(){
    return main;
}

public void setMain(String main){
    this.main = main;
}

public String getDescription(){
    return description;
}

public void setDescription(String description){
    this.description = description;
}

// default constructor, getters and setters
}

// accessing methods
// success!

    Log.i("App", weatherResponse.getBase());
    Log.i("App", weatherResponse.getWeather().getMain());
    Log.i("App", weatherResponse.getWeather().getDescription());

jQuery get the name of a select option

For anyone who comes across this late, like me.

As others have stated, name isn't a valid attribute of an option element. Combining the accepted answer above with the answer from this other question, you get:

$(this).find('option:selected').text();

How to add dll in c# project

The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.

I usually create a libs folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.

(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)

PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...

How to get the element clicked (for the whole document)?

Use delegate and event.target. delegate takes advantage of the event bubbling by letting one element listen for, and handle, events on child elements. target is the jQ-normalized property of the event object representing the object from which the event originated.

$(document).delegate('*', 'click', function (event) {
    // event.target is the element
    // $(event.target).text() gets its text
});

Demo: http://jsfiddle.net/xXTbP/

matplotlib: how to change data points color based on some variable

This is what matplotlib.pyplot.scatter is for.

As a quick example:

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)

plt.scatter(t,x,c=y)
plt.show()

enter image description here

How can I convert a zero-terminated byte array to string?

Use this:

bytes.NewBuffer(byteArray).String()

how to get the 30 days before date from Todays Date

In MS SQL Server, it is:

SELECT getdate() - 30;

How to append multiple items in one line in Python

mylist = [1,2,3]

def multiple_appends(listname, *element):
    listname.extend(element)

multiple_appends(mylist, 4, 5, "string", False)
print(mylist)

OUTPUT:

[1, 2, 3, 4, 5, 'string', False]

Reverse Y-Axis in PyPlot

There is a new API that makes this even simpler.

plt.gca().invert_xaxis()

and/or

plt.gca().invert_yaxis()

Iterating through list of list in Python

if you don't want recursion you could try:

x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
layer1=x
layer2=[]
while True:
    for i in layer1:
        if isinstance(i,list):
            for j in i:
                layer2.append(j)
        else:
            print i
    layer1[:]=layer2
    layer2=[]
    if len(layer1)==0:
        break

which gives:

sam
Test
Test2
(u'file.txt', ['id', 1, 0])
(u'file2.txt', ['id', 1, 2])
one

(note that it didn't look into the tuples for lists because the tuples aren't lists. You can add tuple to the "isinstance" method if you want to fix this)

Absolute Positioning & Text Alignment

This should work:

#my-div { 
  left: 0; 
  width: 100%; 
}

Bootstrap 4 - Inline List?

Inline

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" >
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>


<ul class="list-inline">
  <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
  <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
  <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>
_x000D_
_x000D_
_x000D_

and learn more about https://getbootstrap.com/docs/4.0/content/typography/#inline

What are the differences between 'call-template' and 'apply-templates' in XSL?

The functionality is indeed similar (apart from the calling semantics, where call-template requires a name attribute and a corresponding names template).

However, the parser will not execute the same way.

From MSDN:

Unlike <xsl:apply-templates>, <xsl:call-template> does not change the current node or the current node-list.

Invalid length parameter passed to the LEFT or SUBSTRING function

Something else you can use is isnull:

isnull( SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode ) -1), PostCode)

Checking if a number is a prime number in Python

def isPrime(x):
    if x<2:
        return False
    for i in range(2,x):
        if not x%i:
           return False
    return True  

print isPrime(2)
True
print isPrime(3)
True
print isPrime(9)
False

How do I remove packages installed with Python's easy_install?

All the info is in the other answers, but none summarizes both your requests or seem to make things needlessly complex:

  • For your removal needs use:

    pip uninstall <package>
    

    (install using easy_install pip)

  • For your 'list installed packages' needs either use:

    pip freeze
    

    Or:

    yolk -l
    

    which can output more package details.

    (Install via easy_install yolk or pip install yolk)

Change collations of all columns of all tables in SQL Server

Following script will work with table schema along with latest Types like (MAX), IMAGE, and etc. change your collation type according to your need on this line (SET @collate = 'DATABASE_DEFAULT';)

SQL SCRIPT HERE:

BEGIN
DECLARE @collate nvarchar(100);
declare @schema nvarchar(255);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length varchar(100);
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);

SET @collate = 'DATABASE_DEFAULT';

DECLARE tbl_cursor CURSOR FOR SELECT (s.[name])schemaName, (o.[name])[tableName]
FROM sysobjects sy 
INNER JOIN sys.objects  o on o.name = sy.name
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE OBJECTPROPERTY(sy.id, N'IsUserTable') = 1

OPEN tbl_cursor FETCH NEXT FROM tbl_cursor INTO @schema,@table

WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE tbl_cursor_changed CURSOR FOR
        SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
            , c.name column_name
            , t.Name data_type
            , c.max_length
            , c.column_id
        FROM sys.columns c
        JOIN sys.types t ON c.system_type_id = t.system_type_id
        LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
        LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
    WHERE c.object_id like OBJECT_ID(@schema+'.'+@table)
    ORDER BY c.column_id


    OPEN tbl_cursor_changed 
     FETCH NEXT FROM tbl_cursor_changed
    INTO @row_id, @column_name, @data_type, @max_length, @column_id



    WHILE @@FETCH_STATUS = 0
    BEGIN
    IF (@max_length = -1) SET @max_length = 'MAX';
        IF (@data_type LIKE '%char%')
        BEGIN TRY
            SET @sql = 'ALTER TABLE ' +@schema+'.'+ @table + ' ALTER COLUMN ' + @column_name + ' ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate
            print @sql
            EXEC sp_executesql @sql
        END TRY
        BEGIN CATCH
          PRINT 'ERROR:'
          PRINT @sql
        END CATCH

        FETCH NEXT FROM tbl_cursor_changed
        INTO @row_id, @column_name, @data_type, @max_length, @column_id

    END

    CLOSE tbl_cursor_changed
    DEALLOCATE tbl_cursor_changed

    FETCH NEXT FROM tbl_cursor
    INTO @schema, @table

END

CLOSE tbl_cursor
DEALLOCATE tbl_cursor

PRINT 'Collation For All Tables Done!'
END

difference between primary key and unique key

Unique key :- It should be used when you have to give unique value.In the case of unique key it means null values are also allowed.Unique keys are those keys which are unique and non similar in that column like for example your pet name.it can be nothing like null and if you are asking in context of database then it must be noted that every null is different from another null in the database.EXCEPT-SQL Server where null=null is true


primary key :- It should be used when you have to give uniquely identify a row.primary is key which unique for every row in a database constraint is that it doesn't allow null in it.so, you might have seen that the database have a column which is auto increment and it is the primary key of the table. plus it can be used as a foreign key in another table.example can be orderId on a order Table,billId in a bill Table.

now coming back to situation when to use it:-

1) primary key in the column which can not be null in the table and you are using as foreign key in another table for creating relationship

2) unique key in table where it doesn't affect in table or in the whole database whether you take the null for the particular column like snacks in the restaurant it is possible you don't take snacks in a restaurant

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

How to include a sub-view in Blade templates?

EDIT: Below was the preferred solution in 2014. Nowadays you should use @include, as mentioned in the other answer.


In Laravel views the dot is used as folder separator. So for example I have this code

return View::make('auth.details', array('id' => $id));

which points to app/views/auth/details.blade.php

And to include a view inside a view you do like this:

file: layout.blade.php

<html>
  <html stuff>
  @yield('content')
</html>

file: hello.blade.php

@extends('layout')

@section('content')
  <html stuff>
@stop

What are 'get' and 'set' in Swift?

You should look at Computed Properties

In your code sample, perimeter is a property not backed up by a class variable, instead its value is computed using the get method and stored via the set method - usually referred to as getter and setter.

When you use that property like this:

var cp = myClass.perimeter

you are invoking the code contained in the get code block, and when you use it like this:

myClass.perimeter = 5.0

you are invoking the code contained in the set code block, where newValue is automatically filled with the value provided at the right of the assignment operator.

Computed properties can be readwrite if both a getter and a setter are specified, or readonly if the getter only is specified.

Using switch statement with a range of value in each case?

No you can't do that. The best you can do is that

case 1:
case 2:
case 3:
case 4:
case 5: 
  System.Out.Println("testing case 1 to 5");
break;

How do I measure a time interval in C?

Here's a header file I wrote to do some simple performance profiling (using manual timers):

#ifndef __ZENTIMER_H__
#define __ZENTIMER_H__

#ifdef ENABLE_ZENTIMER

#include <stdio.h>
#ifdef WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h>
#elif HAVE_INTTYPES_H
#include <inttypes.h>
#else
typedef unsigned char uint8_t;
typedef unsigned long int uint32_t;
typedef unsigned long long uint64_t;
#endif

#ifdef __cplusplus
extern "C" {
#pragma }
#endif /* __cplusplus */

#define ZTIME_USEC_PER_SEC 1000000

/* ztime_t represents usec */
typedef uint64_t ztime_t;

#ifdef WIN32
static uint64_t ztimer_freq = 0;
#endif

static void
ztime (ztime_t *ztimep)
{
#ifdef WIN32
    QueryPerformanceCounter ((LARGE_INTEGER *) ztimep);
#else
    struct timeval tv;

    gettimeofday (&tv, NULL);

    *ztimep = ((uint64_t) tv.tv_sec * ZTIME_USEC_PER_SEC) + tv.tv_usec;
#endif
}

enum {
    ZTIMER_INACTIVE = 0,
    ZTIMER_ACTIVE   = (1 << 0),
    ZTIMER_PAUSED   = (1 << 1),
};

typedef struct {
    ztime_t start;
    ztime_t stop;
    int state;
} ztimer_t;

#define ZTIMER_INITIALIZER { 0, 0, 0 }

/* default timer */
static ztimer_t __ztimer = ZTIMER_INITIALIZER;

static void
ZenTimerStart (ztimer_t *ztimer)
{
    ztimer = ztimer ? ztimer : &__ztimer;

    ztimer->state = ZTIMER_ACTIVE;
    ztime (&ztimer->start);
}

static void
ZenTimerStop (ztimer_t *ztimer)
{
    ztimer = ztimer ? ztimer : &__ztimer;

    ztime (&ztimer->stop);
    ztimer->state = ZTIMER_INACTIVE;
}

static void
ZenTimerPause (ztimer_t *ztimer)
{
    ztimer = ztimer ? ztimer : &__ztimer;

    ztime (&ztimer->stop);
    ztimer->state |= ZTIMER_PAUSED;
}

static void
ZenTimerResume (ztimer_t *ztimer)
{
    ztime_t now, delta;

    ztimer = ztimer ? ztimer : &__ztimer;

    /* unpause */
    ztimer->state &= ~ZTIMER_PAUSED;

    ztime (&now);

    /* calculate time since paused */
    delta = now - ztimer->stop;

    /* adjust start time to account for time elapsed since paused */
    ztimer->start += delta;
}

static double
ZenTimerElapsed (ztimer_t *ztimer, uint64_t *usec)
{
#ifdef WIN32
    static uint64_t freq = 0;
    ztime_t delta, stop;

    if (freq == 0)
        QueryPerformanceFrequency ((LARGE_INTEGER *) &freq);
#else
#define freq ZTIME_USEC_PER_SEC
    ztime_t delta, stop;
#endif

    ztimer = ztimer ? ztimer : &__ztimer;

    if (ztimer->state != ZTIMER_ACTIVE)
        stop = ztimer->stop;
    else
        ztime (&stop);

    delta = stop - ztimer->start;

    if (usec != NULL)
        *usec = (uint64_t) (delta * ((double) ZTIME_USEC_PER_SEC / (double) freq));

    return (double) delta / (double) freq;
}

static void
ZenTimerReport (ztimer_t *ztimer, const char *oper)
{
    fprintf (stderr, "ZenTimer: %s took %.6f seconds\n", oper, ZenTimerElapsed (ztimer, NULL));
}

#ifdef __cplusplus
}
#endif /* __cplusplus */

#else /* ! ENABLE_ZENTIMER */

#define ZenTimerStart(ztimerp)
#define ZenTimerStop(ztimerp)
#define ZenTimerPause(ztimerp)
#define ZenTimerResume(ztimerp)
#define ZenTimerElapsed(ztimerp, usec)
#define ZenTimerReport(ztimerp, oper)

#endif /* ENABLE_ZENTIMER */

#endif /* __ZENTIMER_H__ */

The ztime() function is the main logic you need — it gets the current time and stores it in a 64bit uint measured in microseconds. You can then later do simple math to find out the elapsed time.

The ZenTimer*() functions are just helper functions to take a pointer to a simple timer struct, ztimer_t, which records the start time and the end time. The ZenTimerPause()/ZenTimerResume() functions allow you to, well, pause and resume the timer in case you want to print out some debugging information that you don't want timed, for example.

You can find a copy of the original header file at http://www.gnome.org/~fejj/code/zentimer.h in the off chance that I messed up the html escaping of <'s or something. It's licensed under MIT/X11 so feel free to copy it into any project you do.

Accessing elements of Python dictionary by index

mydict = {
'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
'Grapes':{'Arabian':'25','Indian':'20'} }

for n in mydict:
    print(mydict[n])

Select Top and Last rows in a table (SQL server)

You must sort your data according your needs (es. in reverse order) and use select top query

Iterate through dictionary values?

You could search for the corresponding key or you could "invert" the dictionary, but considering how you use it, it would be best if you just iterated over key/value pairs in the first place, which you can do with items(). Then you have both directly in variables and don't need a lookup at all:

for key, value in PIX0.items():
    NUM = input("What is the Resolution of %s?"  % key)
    if NUM == value:

You can of course use that both ways then.

Or if you don't actually need the dictionary for something else, you could ditch the dictionary and have an ordinary list of pairs.

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

php error: Class 'Imagick' not found

From: http://news.ycombinator.com/item?id=1726074

For RHEL-based i386 distributions:

yum install ImageMagick.i386
yum install ImageMagick-devel.i386
pecl install imagick
echo "extension=imagick.so" > /etc/php.d/imagick.ini
service httpd restart

This may also work on other i386 distributions using yum package manager. For x86_64, just replace .i386 with .x86_64

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

By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.

Is there a way to specify which pytest tests to run from a file?

Specifying tests / selecting tests

Pytest supports several ways to run and select tests from the command-line.

Run tests in a module

pytest test_mod.py

Run tests in a directory

pytest testing/

Run tests by keyword expressions

pytest -k "MyClass and not method"

This will run tests which contain names that match the given string expression, which can include Python operators that use filenames, class names and function names as variables. The example above will run TestMyClass.test_something but not TestMyClass.test_method_simple.

Run tests by node ids

Each collected test is assigned a unique nodeid which consist of the module filename followed by specifiers like class names, function names and parameters from parametrization, separated by :: characters.

To run a specific test within a module:

pytest test_mod.py::test_func

Another example specifying a test method in the command line:

pytest test_mod.py::TestClass::test_method

Run tests by marker expressions

pytest -m slow

Will run all tests which are decorated with the @pytest.mark.slow decorator.

For more information see marks.

Run tests from packages

pytest --pyargs pkg.testing

This will import pkg.testing and use its filesystem location to find and run tests from.

Source: https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests

How to detect internet speed in JavaScript?

It's better to use images for testing the speed. But if you have to deal with zip files, the below code works.

var fileURL = "your/url/here/testfile.zip";

var request = new XMLHttpRequest();
var avoidCache = "?avoidcache=" + (new Date()).getTime();;
request.open('GET', fileURL + avoidCache, true);
request.responseType = "application/zip";
var startTime = (new Date()).getTime();
var endTime = startTime;
request.onreadystatechange = function () {
    if (request.readyState == 2)
    {
        //ready state 2 is when the request is sent
        startTime = (new Date().getTime());
    }
    if (request.readyState == 4)
    {
        endTime = (new Date()).getTime();
        var downloadSize = request.responseText.length;
        var time = (endTime - startTime) / 1000;
        var sizeInBits = downloadSize * 8;
        var speed = ((sizeInBits / time) / (1024 * 1024)).toFixed(2);
        console.log(downloadSize, time, speed);
    }
}

request.send();

This will not work very well with files < 10MB. You will have to run aggregated results on multiple download attempts.

Comprehensive beginner's virtualenv tutorial?

Virtualenv is a tool to create isolated Python environments.

Let's say you're working in 2 different projects, A and B. Project A is a web project and the team is using the following packages:

  • Python 2.8.x
  • Django 1.6.x

The project B is also a web project but your team is using:

  • Python 2.7.x
  • Django 1.4.x

The machine that you're working doesn't have any version of django, what should you do? Install django 1.4? django 1.6? If you install django 1.4 globally would be easy to point to django 1.6 to work in project A?

Virtualenv is your solution! You can create 2 different virtualenv's, one for project A and another for project B. Now, when you need to work in project A, just activate the virtualenv for project A, and vice-versa.

A better tip when using virtualenv is to install virtualenvwrapper to manage all the virtualenv's that you have, easily. It's a wrapper for creating, working, removing virtualenv's.

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

An XSD is included with EntLib 5, and is installed in the Visual Studio schema directory. In my case, it could be found at:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas\EnterpriseLibrary.Configuration.xsd

CONTEXT

  • Visual Studio 2010
  • Enterprise Library 5

STEPS TO REMOVE THE WARNINGS

  1. open app.config in your Visual Studio project
  2. right click in the XML Document editor, select "Properties"
  3. add the fully qualified path to the "EnterpriseLibrary.Configuration.xsd"

ASIDE

It is worth repeating that these "Error List" "Messages" ("Could not find schema information for the element") are only visible when you open the app.config file. If you "Close All Documents" and compile... no messages will be reported.

Maven2: Best practice for Enterprise Project (EAR file)

You create a new project. The new project is your EAR assembly project which contains your two dependencies for your EJB project and your WAR project.

So you actually have three maven projects here. One EJB. One WAR. One EAR that pulls the two parts together and creates the ear.

Deployment descriptors can be generated by maven, or placed inside the resources directory in the EAR project structure.

The maven-ear-plugin is what you use to configure it, and the documentation is good, but not quite clear if you're still figuring out how maven works in general.

So as an example you might do something like this:

<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany</groupId>
  <artifactId>myEar</artifactId>
  <packaging>ear</packaging>
  <name>My EAR</name>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-ear-plugin</artifactId>
        <configuration>
          <version>1.4</version>
          <modules>
            <webModule>
              <groupId>com.mycompany</groupId>
              <artifactId>myWar</artifactId>
              <bundleFileName>myWarNameInTheEar.war</bundleFileName>
              <contextRoot>/myWarConext</contextRoot>
            </webModule>
            <ejbModule>
              <groupId>com.mycompany</groupId>
              <artifactId>myEjb</artifactId>
              <bundleFileName>myEjbNameInTheEar.jar</bundleFileName>
            </ejbModule>
          </modules>
          <displayName>My Ear Name displayed in the App Server</displayName>
          <!-- If I want maven to generate the application.xml, set this to true -->
          <generateApplicationXml>true</generateApplicationXml>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
    </plugins>
    <finalName>myEarName</finalName>
  </build>

  <!-- Define the versions of your ear components here -->
  <dependencies>
    <dependency>
      <groupId>com.mycompany</groupId>
      <artifactId>myWar</artifactId>
      <version>1.0-SNAPSHOT</version>
      <type>war</type>
    </dependency>
    <dependency>
      <groupId>com.mycompany</groupId>
      <artifactId>myEjb</artifactId>
      <version>1.0-SNAPSHOT</version>
      <type>ejb</type>
    </dependency>
  </dependencies>
</project>

When to use static methods

Static methods and variables are controlled version of 'Global' functions and variables in Java. In which methods can be accessed as classname.methodName() or classInstanceName.methodName(), i.e. static methods and variables can be accessed using class name as well as instances of the class.

Class can't be declared as static(because it makes no sense. if a class is declared public, it can be accessed from anywhere), inner classes can be declared static.

Best way to store passwords in MYSQL database

You should use one way encryption (which is a way to encrypt a value so that is very hard to revers it). I'm not familiar with MySQL, but a quick search shows that it has a password() function that does exactly this kind of encryption. In the DB you will store the encrypted value and when the user wants to authenticate you take the password he provided, you encrypt it using the same algorithm/function and then you check that the value is the same with the password stored in the database for that user. This assumes that the communication between the browser and your server is secure, namely that you use https.

How to uninstall Apache with command line

sc delete Apache2.4

Remove service in windows

How do I call a function inside of another function?

_x000D_
_x000D_
function function_one()_x000D_
{_x000D_
    alert("The function called 'function_one' has been called.")_x000D_
    //Here u would like to call function_two._x000D_
    function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
    alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
_x000D_
_x000D_

php - push array into array - key issue

Use this..

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $res_arr_values[] = $row;
}

How to return an array from an AJAX call?

well, I know that I'm a bit too late, but I tried all of your solutions and with no success! So here is how I managed to do it. First of all, I'm working on an Asp.Net MVC project. The Only thing I changed was in my c# method getInvitation:

public ActionResult getInvitation (Guid s_ID)
{
    using (var db = new cRM_Verband_BWEntities())
    {
        var listSidsMit = (from data in db.TERMINEINLADUNGEN where data.RECID_KOMMUNIKATIONEN == s_ID select data.RECID_MITARBEITER.ToString()).ToArray();
        return Json(listSidsMit);
    }
}

SuccessFunction in JS :

function successFunction(result) {
    console.log(result);
}

I changed the Method Type from string[] to ActionResult and of course at the end I wrapped my array listSidsMit with the Json method.

How to specify preference of library path?

If one is used to work with DLL in Windows and would like to skip .so version numbers in linux/QT, adding CONFIG += plugin will take version numbers out. To use absolute path to .so, giving it to linker works fine, as Mr. Klatchko mentioned.

INSERT INTO TABLE from comma separated varchar-list

Something like this should work:

INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...

UPDATE:

Apparently this syntax is only available starting on SQL Server 2008.

Number of lines in a file in Java

I concluded that wc -l:s method of counting newlines is fine but returns non-intuitive results on files where the last line doesn't end with a newline.

And @er.vikas solution based on LineNumberReader but adding one to the line count returned non-intuitive results on files where the last line does end with newline.

I therefore made an algo which handles as follows:

@Test
public void empty() throws IOException {
    assertEquals(0, count(""));
}

@Test
public void singleNewline() throws IOException {
    assertEquals(1, count("\n"));
}

@Test
public void dataWithoutNewline() throws IOException {
    assertEquals(1, count("one"));
}

@Test
public void oneCompleteLine() throws IOException {
    assertEquals(1, count("one\n"));
}

@Test
public void twoCompleteLines() throws IOException {
    assertEquals(2, count("one\ntwo\n"));
}

@Test
public void twoLinesWithoutNewlineAtEnd() throws IOException {
    assertEquals(2, count("one\ntwo"));
}

@Test
public void aFewLines() throws IOException {
    assertEquals(5, count("one\ntwo\nthree\nfour\nfive\n"));
}

And it looks like this:

static long countLines(InputStream is) throws IOException {
    try(LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is))) {
        char[] buf = new char[8192];
        int n, previousN = -1;
        //Read will return at least one byte, no need to buffer more
        while((n = lnr.read(buf)) != -1) {
            previousN = n;
        }
        int ln = lnr.getLineNumber();
        if (previousN == -1) {
            //No data read at all, i.e file was empty
            return 0;
        } else {
            char lastChar = buf[previousN - 1];
            if (lastChar == '\n' || lastChar == '\r') {
                //Ending with newline, deduct one
                return ln;
            }
        }
        //normal case, return line number + 1
        return ln + 1;
    }
}

If you want intuitive results, you may use this. If you just want wc -l compatibility, simple use @er.vikas solution, but don't add one to the result and retry the skip:

try(LineNumberReader lnr = new LineNumberReader(new FileReader(new File("File1")))) {
    while(lnr.skip(Long.MAX_VALUE) > 0){};
    return lnr.getLineNumber();
}

what is the use of "response.setContentType("text/html")" in servlet

From JavaEE docs ServletResponse#setContentType

  • Sets the content type of the response being sent to the client, if the response has not been committed yet.

  • The given content type may include a character encoding specification, for example,

response.setContentType("text/html;charset=UTF-8");

  • The response's character encoding is only set from the given content type if this method is called before getWriter is called.

  • This method may be called repeatedly to change content type and character encoding.

  • This method has no effect if called after the response has been committed. It does not set the response's character encoding if it is called after getWriter has been called or after the response has been committed.

  • Containers must communicate the content type and the character encoding used for the servlet response's writer to the client if the protocol provides a way for doing so. In the case of HTTP, the Content-Type header is used.

Laravel Fluent Query Builder Join with subquery

I am on Laravel 7.25 and I don't know if it supports on previous versions or not but Its pretty good.

Syntax for the function:

public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false)

Example:

Showing/Getting the user ID and the total number of posts by them left joining two tables users and posts.

        return DB::table('users')
            ->joinSub('select user_id,count(id) noOfPosts from posts group by user_id', 'totalPosts', 'users.id', '=', 'totalPosts.user_id', 'left')
            ->select('users.name', 'totalPosts.noOfPosts')
            ->get();

Alternative:

If you don't wanna mention 'left' for leftjoin then you can use another prebuilt function

    public function leftJoinSub($query, $as, $first, $operator = null, $second = null)
    {
        return $this->joinSub($query, $as, $first, $operator, $second, 'left');
    }

And yeah, it actually calls the same function but it passes the join type itself. You can apply the same logic for other joins i.e. righJoinSub(...) etc.

How to auto-size an iFrame?

Oli has a solution that will work for me. For the record, the page inside my iFrame is rendered by javascript, so I'll need an infinitesimal delay before reporting back the offsetHeight. It looks like something along these lines:


    $(document).ready(function(){
        setTimeout(setHeight);
    });

    function setHeight() {
        alert(document['body'].offsetHeight);   
    }

What are some uses of template template parameters?

Here's another practical example from my CUDA Convolutional neural network library. I have the following class template:

template <class T> class Tensor

which is actually implements n-dimensional matrices manipulation. There's also a child class template:

template <class T> class TensorGPU : public Tensor<T>

which implements the same functionality but in GPU. Both templates can work with all basic types, like float, double, int, etc And I also have a class template (simplified):

template <template <class> class TT, class T> class CLayerT: public Layer<TT<T> >
{
    TT<T> weights;
    TT<T> inputs;
    TT<int> connection_matrix;
}

The reason here to have template template syntax is because I can declare implementation of the class

class CLayerCuda: public CLayerT<TensorGPU, float>

which will have both weights and inputs of type float and on GPU, but connection_matrix will always be int, either on CPU (by specifying TT = Tensor) or on GPU (by specifying TT=TensorGPU).

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

I think the best solution, though not exactly the same as Eclipse/Netbeans, is to change the 'Optimize Imports' settings.

Under Preferences > Editor > General > Auto Import

Set Add unambiguous imports on the fly

Edit: Using this method, when there are ambiguous imports, IntelliJ will let you know, and you can then use Alt + Enter method outlined in the answer by Wuaner

I find that, almost always, the most appropriate Import is at the top of the list.

How to get to Model or Viewbag Variables in a Script Tag

try this method

<script type="text/javascript">

    function set(value) {
        return value;
    }

    alert(set(@Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
    alert(set(@Html.Raw(Json.Encode(ViewBag.UrMessage))));

</script>

Thanks

Project has no default.properties file! Edit the project properties to set one

Don't import it into Eclipse, use create new project from existing source in Eclipse.

How can I get the assembly file version

Use this:

((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
    Assembly.GetExecutingAssembly(), 
    typeof(AssemblyFileVersionAttribute), false)
).Version;

Or this:

new Version(System.Windows.Forms.Application.ProductVersion);

How can I clear previous output in Terminal in Mac OS X?

To delete the last output only:

? + L

To clear the terminal completely:

? + K

ldap query for group members

Active Directory does not store the group membership on user objects. It only stores the Member list on the group. The tools show the group membership on user objects by doing queries for it.

How about:

(&(objectClass=group)(member=cn=my,ou=full,dc=domain))

(You forgot the (& ) bit in your example in the question as well).

Second line in li starts under the bullet after CSS-reset

I second Dipaks' answer, but often just the text-indent is enough as you may/maynot be positioning the ul for better layout control.

ul li{
text-indent: -1em;
}

Is a new line = \n OR \r\n?

If you are programming in PHP, it is useful to split lines by \n and then trim() each line (provided you don't care about whitespace) to give you a "clean" line regardless.

foreach($line in explode("\n", $data))
{
    $line = trim($line);
    ...
}

Why are primes important in cryptography?

I'm not a mathematician or cryptician, so here's an outside observation in layman's terms (no fancy equations, sorry).

This whole thread is filled with explanations about HOW primes are used in cryptography, it's hard to find anyone in this thread explaining in an easy way WHY primes are used ... most likely because everyone takes that knowledge for granted.

Only looking at the problem from the outside can generate a reaction like; but if they use the sums of two primes, why not create a list of all possible sums any two primes can generate?

On this site there's a list of 455,042,511 primes, where the highest primes is 9,987,500,000 (10 digits).

The largest known prime (as of feb 2015) is 2 to the power of 257,885,161 - 1 which is 17,425,170 digits.

This means that there's no point keeping a list of all the known primes and much less all their possible sums. It's easier to take a number and check if it's a prime.

Calculating big primes in itself is a monumental task, so reverse calculating two primes that has been multiplied with each other both cryptographers and mathematicians would say is hard enough ... today.

What does git rev-parse do?

git rev-parse is an ancillary plumbing command primarily used for manipulation.

One common usage of git rev-parse is to print the SHA1 hashes given a revision specifier. In addition, it has various options to format this output such as --short for printing a shorter unique SHA1.

There are other use cases as well (in scripts and other tools built on top of git) that I've used for:

  • --verify to verify that the specified object is a valid git object.
  • --git-dir for displaying the abs/relative path of the the .git directory.
  • Checking if you're currently within a repository using --is-inside-git-dir or within a work-tree using --is-inside-work-tree
  • Checking if the repo is a bare using --is-bare-repository
  • Printing SHA1 hashes of branches (--branches), tags (--tags) and the refs can also be filtered based on the remote (using --remote)
  • --parse-opt to normalize arguments in a script (kind of similar to getopt) and print an output string that can be used with eval

Massage just implies that it is possible to convert the info from one form into another i.e. a transformation command. These are some quick examples I can think of:

  • a branch or tag name into the commit's SHA1 it is pointing to so that it can be passed to a plumbing command which only accepts SHA1 values for the commit.
  • a revision range A..B for git log or git diff into the equivalent arguments for the underlying plumbing command as B ^A

How to initialize a list of strings (List<string>) with many string values

This is how you initialize and also you can use List.Add() in case you want to make it more dynamic.

List<string> optionList = new List<string> {"AdditionalCardPersonAdressType"};
optionList.Add("AutomaticRaiseCreditLimit");
optionList.Add("CardDeliveryTimeWeekDay");

In this way, if you are taking values in from IO, you can add it to a dynamically allocated list.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

Solutions revolve around:

  • changing MySQL's permissions

    sudo chown -R _mysql:mysql /usr/local/var/mysql
    
  • Starting a MySQL process

    sudo mysql.server start
    

Just to add on a lot of great and useful answers that have been provided here and from many different posts, try specifying the host if the above commands did not resolve this issue for you, i.e

mysql -u root -p h127.0.0.1

Is there a 'box-shadow-color' property?

Yes there is a way

box-shadow 0 0 17px 13px rgba(30,140,255,0.80) inset

Accessing UI (Main) Thread safely in WPF

The best way to go about it would be to get a SynchronizationContext from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher directly). For example:

class MyViewModel
{
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
    {
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;
    }

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
    }
}

How to get a resource id with a known resource name?

I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.

Here's the code:

/**
 * @author Lonkly
 * @param variableName - name of drawable, e.g R.drawable.<b>image</b>
 * @param ? - class of resource, e.g R.drawable.class or R.raw.class
 * @return integer id of resource
 */
public static int getResId(String variableName, Class<?> ?) {

    Field field = null;
    int resId = 0;
    try {
        field = ?.getField(variableName);
        try {
            resId = field.getInt(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resId;

}

Simulate a click on 'a' element using javascript/jquery

The code you've already tried:

document.getElementById("gift-close").click();

...should work as long as the element actually exists in the DOM at the time you run it. Some possible ways to ensure that include:

  1. Run your code from an onload handler for the window. http://jsfiddle.net/LKNYg/
  2. Run your code from a document ready handler if you're using jQuery. http://jsfiddle.net/LKNYg/1/
  3. Put the code in a script block that is after the element in the source html.

So:

$(document).ready(function() {
    document.getElementById("gift-close").click();
    // OR
    $("#gift-close")[0].click();
});

Left padding a String with Zeros

    int number = -1;
    int holdingDigits = 7;
    System.out.println(String.format("%0"+ holdingDigits +"d", number));

Just asked this in an interview........

My answer below but this (mentioned above) is much nicer->

String.format("%05d", num);

My answer is:

static String leadingZeros(int num, int digitSize) {
    //test for capacity being too small.

    if (digitSize < String.valueOf(num).length()) {
        return "Error : you number  " + num + " is higher than the decimal system specified capacity of " + digitSize + " zeros.";

        //test for capacity will exactly hold the number.
    } else if (digitSize == String.valueOf(num).length()) {
        return String.valueOf(num);

        //else do something here to calculate if the digitSize will over flow the StringBuilder buffer java.lang.OutOfMemoryError 

        //else calculate and return string
    } else {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digitSize; i++) {
            sb.append("0");
        }
        sb.append(String.valueOf(num));
        return sb.substring(sb.length() - digitSize, sb.length());
    }
}

How can I get file extensions with JavaScript?

In node.js, this can be achieved by the following code:

var file1 ="50.xsl";
var path = require('path');
console.log(path.parse(file1).name);

Compiler warning - suggest parentheses around assignment used as truth value

While that particular idiom is common, even more common is for people to use = when they mean ==. The convention when you really mean the = is to use an extra layer of parentheses:

while ((list = list->next)) { // yes, it's an assignment

How to use LINQ Distinct() with multiple fields

This is my solution, it supports keySelectors of different types:

public static IEnumerable<TSource> DistinctBy<TSource>(this IEnumerable<TSource> source, params Func<TSource, object>[] keySelectors)
{
    // initialize the table
    var seenKeysTable = keySelectors.ToDictionary(x => x, x => new HashSet<object>());

    // loop through each element in source
    foreach (var element in source)
    {
        // initialize the flag to true
        var flag = true;

        // loop through each keySelector a
        foreach (var (keySelector, hashSet) in seenKeysTable)
        {                    
            // if all conditions are true
            flag = flag && hashSet.Add(keySelector(element));
        }

        // if no duplicate key was added to table, then yield the list element
        if (flag)
        {
            yield return element;
        }
    }
}

To use it:

list.DistinctBy(d => d.CategoryId, d => d.CategoryName)

Array of strings in groovy

If you really want to create an array rather than a list use either

String[] names = ["lucas", "Fred", "Mary"]

or

def names = ["lucas", "Fred", "Mary"].toArray()

SQL Server - NOT IN

Use a LEFT JOIN checking the right side for nulls.

SELECT a.Id
FROM TableA a
LEFT JOIN TableB on a.Id = b.Id
WHERE b.Id IS NULL

The above would match up TableA and TableB based on the Id column in each, and then give you the rows where the B side is empty.

HTML Canvas Full Screen

The newest Chrome and Firefox support a fullscreen API, but setting to fullscreen is like a window resize. Listen to the onresize-Event of the window-object:

$(window).bind("resize", function(){
    var w = $(window).width();
    var h = $(window).height();

    $("#mycanvas").css("width", w + "px");
    $("#mycanvas").css("height", h + "px"); 
});

//using HTML5 for fullscreen (only newest Chrome + FF)
$("#mycanvas")[0].webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); //Chrome
$("#mycanvas")[0].mozRequestFullScreen(); //Firefox

//...

//now i want to cancel fullscreen
document.webkitCancelFullScreen(); //Chrome
document.mozCancelFullScreen(); //Firefox

This doesn't work in every browser. You should check if the functions exist or it will throw an js-error.

for more info on html5-fullscreen check this: http://updates.html5rocks.com/2011/10/Let-Your-Content-Do-the-Talking-Fullscreen-API

How to get the indices list of all NaN value in numpy array?

np.isnan combined with np.argwhere

x = np.array([[1,2,3,4],
              [2,3,np.nan,5],
              [np.nan,5,2,3]])
np.argwhere(np.isnan(x))

output:

array([[1, 2],
       [2, 0]])

Android ACTION_IMAGE_CAPTURE Intent

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CANCELED)
    {
        //do not process data, I use return; to resume activity calling camera intent
        enter code here
    }
}

How do I properly force a Git push?

If I'm on my local branch A, and I want to force push local branch B to the origin branch C I can use the following syntax:

git push --force origin B:C

Vertically centering a div inside another div

Vertically centering div items inside another div

Just set the container to display:table and then the inner items to display:table-cell. Set a height on the container, and then set vertical-align:middle on the inner items. This has broad compatibility back as far as the days of IE9.

Just note that the vertical alignment will depend on the height of the parent container.

_x000D_
_x000D_
.cn_x000D_
{_x000D_
display:table;_x000D_
height:80px;_x000D_
background-color:#555;_x000D_
}_x000D_
_x000D_
.inner_x000D_
{_x000D_
display:table-cell;_x000D_
vertical-align:middle;_x000D_
color:#FFF;_x000D_
padding-left:10px;_x000D_
padding-right:10px;_x000D_
}
_x000D_
<div class="cn">_x000D_
  <div class="inner">Item 1</div>_x000D_
  <div class="inner">Item 2</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Standard deviation of a list

Here's some pure-Python code you can use to calculate the mean and standard deviation.

All code below is based on the statistics module in Python 3.4+.

def mean(data):
    """Return the sample arithmetic mean of data."""
    n = len(data)
    if n < 1:
        raise ValueError('mean requires at least one data point')
    return sum(data)/n # in Python 2 use sum(data)/float(n)

def _ss(data):
    """Return sum of square deviations of sequence data."""
    c = mean(data)
    ss = sum((x-c)**2 for x in data)
    return ss

def stddev(data, ddof=0):
    """Calculates the population standard deviation
    by default; specify ddof=1 to compute the sample
    standard deviation."""
    n = len(data)
    if n < 2:
        raise ValueError('variance requires at least two data points')
    ss = _ss(data)
    pvar = ss/(n-ddof)
    return pvar**0.5

Note: for improved accuracy when summing floats, the statistics module uses a custom function _sum rather than the built-in sum which I've used in its place.

Now we have for example:

>>> mean([1, 2, 3])
2.0
>>> stddev([1, 2, 3]) # population standard deviation
0.816496580927726
>>> stddev([1, 2, 3], ddof=1) # sample standard deviation
0.1

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

Android image caching

I had been wrestling with this for some time; the answers using SoftReferences would lose their data too quickly. The answers that suggest instantiating a RequestCache were too messy, plus I could never find a full example.

But ImageDownloader.java works wonderfully for me. It uses a HashMap until the capacity is reached or until the purge timeout occurs, then things get moved to a SoftReference, thereby using the best of both worlds.

How to execute a file within the python interpreter?

Surprised I haven't seen this yet. You can execute a file and then leave the interpreter open after execution terminates using the -i option:

| foo.py |
----------
testvar = 10

def bar(bing):
  return bing*3

--------



$ python -i foo.py
>>> testvar 
10
>>> bar(6)
18

Basic example of using .ajax() with JSONP?

JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

So - instead of using XMLHttpRequest we have to use script HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?

Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";

You will end up with a script segment that looks like this after it loads the data:

<script>
{['some string 1', 'some data', 'whatever data']}
</script>

However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better (and it is):

script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";

Notice my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:

my_callback({['some string 1', 'some data', 'whatever data']});

See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data. That's all there is to know about JSONP: it's a callback and script tags.


NOTE:
These are simple examples of JSONP usage, these are not production ready scripts.

RAW JavaScript demonstration (simple Twitter feed using JSONP):

<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>


Basic jQuery example (simple Twitter feed using JSONP):

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html>


JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)

What's the best UI for entering date of birth?

I think a date picker just make the move more complicated to enter one's birth date.

As already mentioned, a combination of drop lists for days and months with a text box for the year seems the most efficient for a user. It takes just less than 10 seconds to enter a birth date this way, which is far quicker than a date picker: thanks to the tab key (which all users should learn to use to complete a form), it's fast to go from one form element to the next one.

At least under Macintosh (I don't know about Windows), you also can use the keyboard to access date inside select boxes: thanks to the tab key, you get the focus onto the form element, then press the arrow key to drop down the list, then type for instance 1967 and you get there in the blink of an eye…

Jquery each - Stop loop and return object

Try this ...

  someArray = new Array();
  someArray[0] = 't5';
  someArray[1] = 'z12';
  someArray[2] = 'b88';
  someArray[3] = 's55';
  someArray[4] = 'e51';
  someArray[5] = 'o322';
  someArray[6] = 'i22';
  someArray[7] = 'k954';  

  var test =  findXX('o322'); 
  console.log(test);



function findXX(word)
{  
  for(var i in someArray){


    if(someArray[i] == word)
    {
      return someArray[i]; //<---  stop the loop!
    }   
  }
}

JFrame.dispose() vs System.exit()

  • If you have multiple windows open and only want to close the one that was closed use JFrame.dispose().

  • If you want to close all windows and terminate the application use System.exit()

How do I delete an entity from symfony2

DELETE FROM ... WHERE id=...;

protected function templateRemove($id){
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('XXXBundle:Templates')->findOneBy(array('id' => $id));

            if ($entity != null){
                $em->remove($entity);
                $em->flush();
            }
        }

Symfony2 Setting a default choice field selection

If you want to pass in an array of Doctrine entities, try something like this (Symfony 3.0+):

protected $entities;
protected $selectedEntities;

public function __construct($entities = null, $selectedEntities = null)
{
    $this->entities = $entities;
    $this->selectedEntities = $selectedEntities;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('entities', 'entity', [
        'class' => 'MyBundle:MyEntity',
        'choices' => $this->entities,
        'property' => 'id',
        'multiple' => true,
        'expanded' => true,
        'data' => $this->selectedEntities,
    ]);
}

How to build a DataTable from a DataGridView?

I don't know anything provided by the Framework (beyond what you want to avoid) that would do what you want but (as I suspect you know) it would be pretty easy to create something simple yourself:

private DataTable GetDataTableFromDGV(DataGridView dgv) {
    var dt = new DataTable();
    foreach (DataGridViewColumn column in dgv.Columns) {
        if (column.Visible) {
            // You could potentially name the column based on the DGV column name (beware of dupes)
            // or assign a type based on the data type of the data bound to this DGV column.
            dt.Columns.Add();
        }
    }

    object[] cellValues = new object[dgv.Columns.Count];
    foreach (DataGridViewRow row in dgv.Rows) {
        for (int i = 0; i < row.Cells.Count; i++) {
            cellValues[i] = row.Cells[i].Value;
        }
        dt.Rows.Add(cellValues);
    }

    return dt;
}

How should I load files into my Java application?

I haven't had a problem just using Unix-style path separators, even on Windows (though it is good practice to check File.separatorChar).

The technique of using ClassLoader.getResource() is best for read-only resources that are going to be loaded from JAR files. Sometimes, you can programmatically determine the application directory, which is useful for admin-configurable files or server applications. (Of course, user-editable files should be stored somewhere in the System.getProperty("user.home") directory.)

Firebase FCM force onTokenRefresh() to be called

Guys it has very simple solution

https://developers.google.com/instance-id/guides/android-implementation#generate_a_token

Note: If your app used tokens that were deleted by deleteInstanceID, your app will need to generate replacement tokens.

In stead of deleting instance Id, delete only token:

String authorizedEntity = PROJECT_ID;
String scope = "GCM";
InstanceID.getInstance(context).deleteToken(authorizedEntity,scope);

ImportError: No module named 'pygame'

Resolved !

Here is an example

C:\Users\user\AppData\Local\Programs\Python\Python36-32\Scripts>pip install pygame

How to open in default browser in C#

After researching a lot I feel most of the given answer will not work with dotnet core. 1.System.Diagnostics.Process.Start("http://google.com"); -- Will not work with dotnet core

2.It will work but it will block the new window opening in case default browser is chrome

 myProcess.StartInfo.UseShellExecute = true; 
    myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
    myProcess.Start();

Below is the simplest and will work in all the scenarios.

Process.Start("explorer", url);

How to encode a URL in Swift

Adding to Bryan Chen's answer above:

Just incase anyone else is getting something similar with Alamofire:

error: Alamofire was compiled with optimization - stepping may behave oddly; variables may not be available.

It's not a very descriptive error. I was getting that error when constructing a URL for google geo services. I was appending a street address to the end of the URL WITHOUT encoding the street address itself first. I was able to fix it using Bryan Chen's solution:

var streetAdress = "123 fake street, new york, ny"
var escapedStreetAddress = streetAddress.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let url = "\(self.baseUrl)&address=\(escapedAddress!)"

That fixed it for me! It didnt like that the address had spaces and commas, etc.

Hope this helps someone else!

How to count the occurrence of certain item in an ndarray?

Numpy has a module for this. Just a small hack. Put your input array as bins.

numpy.histogram(y, bins=y)

The output are 2 arrays. One with the values itself, other with the corresponding frequencies.

Replacing some characters in a string with another character

Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single _:

$ var=AxxBCyyyDEFzzLMN
$ echo "${var//+([xyz])/_}"
A_BC_DEF_LMN

Notice that the +(pattern) pattern requires extended pattern matching, turned on with

shopt -s extglob

Alternatively, with the -s ("squeeze") option of tr:

$ tr -s xyz _ <<< "$var"
A_BC_DEF_LMN

How do I check if a Key is pressed on C++

As mentioned by others there's no cross platform way to do this, but on Windows you can do it like this:

The Code below checks if the key 'A' is down.

if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/)
{
    // Do stuff
}

In case of shift or similar you will need to pass one of these: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx

if(GetKeyState(VK_SHIFT) & 0x8000)
{
    // Shift down
}

The low-order bit indicates if key is toggled.

SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/);
bool isToggled = keyState & 1;
bool isDown = keyState & 0x8000;

Oh and also don't forget to

#include <Windows.h>

How to compare timestamp dates with date-only parameter in MySQL?

 WHERE cast(timestamp as date) = '2012-05-05'

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

In my case, WebStrom auto-complete inserted lowercased *ngfor, even when it looks like you choose the right camel cased one (*ngFor).

Converting string to byte array in C#

This has been answered quite a lot, but for me, the only working method is this one:

    public static byte[] StringToByteArray(string str)
    {
        byte[] array = Convert.FromBase64String(str);
        return array;
    }

Java JSON serialization - best practice

Well, when writing it out to file, you do know what class T is, so you can store that in dump. Then, when reading it back in, you can dynamically call it using reflection.

public JSONObject dump() throws JSONException {
    JSONObject result = new JSONObject();
    JSONArray a = new JSONArray();
    for(T i : items){
        a.put(i.dump());
        // inside this i.dump(), store "class-name"
    }
    result.put("items", a);
    return result;
}

public void load(JSONObject obj) throws JSONException {
    JSONArray arrayItems = obj.getJSONArray("items");
    for (int i = 0; i < arrayItems.length(); i++) {
        JSONObject item = arrayItems.getJSONObject(i);
        String className = item.getString("class-name");
        try {
            Class<?> clazzy = Class.forName(className);
            T newItem = (T) clazzy.newInstance();
            newItem.load(obj);
            items.add(newItem);
        } catch (InstantiationException e) {
            // whatever
        } catch (IllegalAccessException e) {
            // whatever
        } catch (ClassNotFoundException e) {
            // whatever
        }
    }

Min / Max Validator in Angular 2 Final

Find the custom validator for min number validation. The selector name of our directive is customMin.

custom-min-validator.directive.ts

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, FormControl } from '@angular/forms';

@Directive({
  selector: '[customMin][formControlName],[customMin][formControl],[customMin][ngModel]',
  providers: [{provide: NG_VALIDATORS, useExisting: CustomMinDirective, multi: true}]
})
export class CustomMinDirective implements Validator {
  @Input()
  customMin: number;

  validate(c: FormControl): {[key: string]: any} {
      let v = c.value;
      return ( v < this.customMin)? {"customMin": true} : null;
  }
} 

Find the custom validator for max number validation. The selector name of our directive is customMax.

custom-max-validator.directive.ts

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, FormControl } from '@angular/forms';

@Directive({
  selector: '[customMax][formControlName],[customMax][formControl],[customMax][ngModel]',
  providers: [{provide: NG_VALIDATORS, useExisting: CustomMaxDirective, multi: true}]
})
export class CustomMaxDirective implements Validator {
  @Input()
  customMax: number;

  validate(c: FormControl): {[key: string]: any} {
      let v = c.value;
      return ( v > this.customMax)? {"customMax": true} : null;
  }
} 

We can use customMax with formControlName, formControl and ngModel attributes.

Using Custom Min and Max Validator in Template-driven Form

We will use our custom min and max validator in template-driven form. For min number validation we have customMin attribute and for max number validation we have customMax attribute. Now find the code snippet for validation.

<input name="num1" [ngModel]="user.num1" customMin="15" #numberOne="ngModel">
<input name="num2" [ngModel]="user.num2" customMax="50"  #numberTwo="ngModel"> 

We can show validation error messages as following.

<div *ngIf="numberOne.errors?.customMin"> 
     Minimum required number is 15.
</div>  

<div *ngIf="numberTwo.errors?.customMax"> 
     Maximum number can be 50.
</div> 

To assign min and max number we can also use property biding. Suppose we have following component properties.

minNum = 15;
maxNum = 50; 

Now use property binding for customMin and customMax as following.

<input name="num1" [ngModel]="user.num1" [customMin]="minNum" #numberOne="ngModel">
<input name="num2" [ngModel]="user.num2" [customMax]="maxNum"  #numberTwo="ngModel">