Programs & Examples On #Batch rename

Renaming files in a folder to sequential numbers

Let us assume we have these files in a directory, listed in order of creation, the first being the oldest:

a.jpg
b.JPG
c.jpeg
d.tar.gz
e

then ls -1cr outputs exactly the list above. You can then use rename:

ls -1cr | xargs rename -n 's/^[^\.]*(\..*)?$/our $i; sprintf("%03d$1", $i++)/e'

which outputs

rename(a.jpg, 000.jpg)
rename(b.JPG, 001.JPG)
rename(c.jpeg, 002.jpeg)
rename(d.tar.gz, 003.tar.gz)
Use of uninitialized value $1 in concatenation (.) or string at (eval 4) line 1.
rename(e, 004)

The warning ”use of uninitialized value […]” is displayed for files without an extension; you can ignore it.

Remove -n from the rename command to actually apply the renaming.

This answer is inspired by Luke’s answer of April 2014. It ignores Gnutt’s requirement of setting the number of leading zeroes depending on the total amount of files.

Rename multiple files based on pattern in Unix

There are several ways, but using rename will probably be the easiest.

Using one version of rename:

rename 's/^fgh/jkl/' fgh*

Using another version of rename (same as Judy2K's answer):

rename fgh jkl fgh*

You should check your platform's man page to see which of the above applies.

Batch Renaming of Files in a Directory

I have this to simply rename all files in subfolders of folder

import os

def replace(fpath, old_str, new_str):
    for path, subdirs, files in os.walk(fpath):
        for name in files:
            if(old_str.lower() in name.lower()):
                os.rename(os.path.join(path,name), os.path.join(path,
                                            name.lower().replace(old_str,new_str)))

I am replacing all occurences of old_str with any case by new_str.

How do I completely rename an Xcode project (i.e. inclusive of folders)?

Step 1 - Rename the project

  1. Click on the project you want to rename in the "Project navigator" in the left panel of the Xcode window.
  2. In the right panel, select the "File inspector", and the name of your project should be found under "Identity and Type". Change it to your new name.
  3. When the dialog asks whether to rename or not rename the project's content items, click "Rename". Say yes to any warning about uncommitted changes.

Step 2 - Rename the scheme

  1. At the top of the window, next to the "Stop" button, there is a scheme for your product under its old name; click on it, then choose "Manage Schemes…".
  2. Click on the old name in the scheme and it will become editable; change the name and click "Close".

Step 3 - Rename the folder with your assets

  1. Quit Xcode. Rename the master folder that contains all your project files.
  2. In the correctly-named master folder, beside your newly-named .xcodeproj file, there is probably a wrongly-named OLD folder containing your source files. Rename the OLD folder to your new name (if you use Git, you could run git mv oldname newname so that Git recognizes this is a move, rather than deleting/adding new files).
  3. Re-open the project in Xcode. If you see a warning "The folder OLD does not exist", dismiss the warning. The source files in the renamed folder will be grayed out because the path has broken.
  4. In the "Project navigator" in the left-hand panel, click on the top-level folder representing the OLD folder you renamed.
  5. In the right-hand panel, under "Identity and Type", change the "Name" field from the OLD name to the new name.
  6. Just below that field is a "Location" menu. If the full path has not corrected itself, click on the nearby folder icon and choose the renamed folder.

Step 4 - Rename the Build plist data

  1. Click on the project in the "Project navigator" on the left, and in the main panel select "Build Settings".
  2. Search for "plist" in the settings.
  3. In the Packaging section, you will see Info.plist and Product Bundle Identifier.
  4. If there is a name entered in Info.plist, update it.
  5. Do the same for Product Bundle Identifier, unless it is utilizing the ${PRODUCT_NAME} variable. In that case, search for "product" in the settings and update Product Name. If Product Name is based on ${TARGET_NAME}, click on the actual target item in the TARGETS list on the left of the settings pane and edit it, and all related settings will update immediately.
  6. Search the settings for "prefix" and ensure that Prefix Header's path is also updated to the new name.
  7. If you use SwiftUI, search for "Development Assets" and update the path.

Step 5 - Repeat step 3 for tests (if you have them)

Step 6 - Repeat step 3 for core data if its name matches project name (if you have it)

Step 7 - Clean and rebuild your project

  1. Command + Shift + K to clean
  2. Command + B to build

Rename multiple files in a folder, add a prefix (Windows)

This worked for me, first cd in the directory that you would like to change the filenames to and then run the following command:

Get-ChildItem | rename-item -NewName { "house chores-" + $_.Name }

How to extract HTTP response body from a Python requests call?


import requests

site_request = requests.get("https://abhiunix.in")

site_response = str(site_request.content)

print(site_response)

You can do it either way.

How can I introduce multiple conditions in LIKE operator?

SELECT * From tbl WHERE col LIKE '[0-9,a-z]%';

simply use this condition of like in sql and you will get your desired answer

How to delete columns that contain ONLY NAs?

Here is a dplyr solution:

df %>% select_if(~sum(!is.na(.)) > 0)

Update: The summarise_if() function is superseded as of dplyr 1.0. Here are two other solutions that use the where() tidyselect function:

df %>% 
  select(
    where(
      ~sum(!is.na(.x)) > 0
    )
  )
df %>% 
  select(
    where(
      ~!all(is.na(.x))
    )
  )

Call a child class method from a parent class object

A parent class should not have knowledge of child classes. You can implement a method calculate() and override it in every subclass:

class Person {
    String name;
    void getName(){...}
    void calculate();
}

and then

class Student extends Person{
    String class;
    void getClass(){...}

    @Override
    void calculate() {
        // do something with a Student
    }
}

and

class Teacher extends Person{
    String experience;
    void getExperience(){...}

    @Override
    void calculate() {
        // do something with a Student
    }

}

By the way. Your statement about abstract classes is confusing. You can call methods defined in an abstract class, but of course only of instances of subclasses.

In your example you can make Person abstract and the use getName() on instanced of Student and Teacher.

SyntaxError: missing ) after argument list

use:

my_function({width:12});

Instead of:

my_function(width:12);

Creating a BLOB from a Base64 string in JavaScript

The method with fetch is the best solution, but if anyone needs to use a method without fetch then here it is, as the ones mentioned previously didn't work for me:

function makeblob(dataURL) {
    const BASE64_MARKER = ';base64,';
    const parts = dataURL.split(BASE64_MARKER);
    const contentType = parts[0].split(':')[1];
    const raw = window.atob(parts[1]);
    const rawLength = raw.length;
    const uInt8Array = new Uint8Array(rawLength);

    for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }

    return new Blob([uInt8Array], { type: contentType });
}

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

How to resolve git stash conflict without commit?

git add .
git reset

git add . will stage ALL the files telling git that you have resolved the conflict

git reset will unstage ALL the staged files without creating a commit

Echoing the last command run in Bash?

The command history is an interactive feature. Only complete commands are entered in the history. For example, the case construct is entered as a whole, when the shell has finished parsing it. Neither looking up the history with the history built-in (nor printing it through shell expansion (!:p)) does what you seem to want, which is to print invocations of simple commands.

The DEBUG trap lets you execute a command right before any simple command execution. A string version of the command to execute (with words separated by spaces) is available in the BASH_COMMAND variable.

trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
…
echo "last command is $previous_command"

Note that previous_command will change every time you run a command, so save it to a variable in order to use it. If you want to know the previous command's return status as well, save both in a single command.

cmd=$previous_command ret=$?
if [ $ret -ne 0 ]; then echo "$cmd failed with error code $ret"; fi

Furthermore, if you only want to abort on a failed commands, use set -e to make your script exit on the first failed command. You can display the last command from the EXIT trap.

set -e
trap 'echo "exit $? due to $previous_command"' EXIT

Note that if you're trying to trace your script to see what it's doing, forget all this and use set -x.

How to add 30 minutes to a JavaScript Date object?

You should get the value of the current date to get the date with (ms) and add (30 * 60 *1000) to it. Now you have (current date + 30 min) with ms

_x000D_
_x000D_
console.log('with ms', Date.now() + (30 * 60 * 1000))_x000D_
console.log('new Date', new Date(Date.now() + (30 * 60 * 1000)))
_x000D_
_x000D_
_x000D_

How do you implement a circular buffer in C?

C style, simple ring buffer for integers. First use init than use put and get. If buffer does not contain any data it returns "0" zero.

//=====================================
// ring buffer address based
//=====================================
#define cRingBufCount   512
int     sRingBuf[cRingBufCount];    // Ring Buffer
int     sRingBufPut;                // Input index address
int     sRingBufGet;                // Output index address
Bool    sRingOverWrite;

void    GetRingBufCount(void)
{
int     r;
`       r= sRingBufPut - sRingBufGet;
        if ( r < cRingBufCount ) r+= cRingBufCount;
        return r; 
}

void    InitRingBuffer(void)
{
        sRingBufPut= 0;
        sRingBufGet= 0;
}       

void    PutRingBuffer(int d)
{
        sRingBuffer[sRingBufPut]= d;
        if (sRingBufPut==sRingBufGet)// both address are like ziro
        {
            sRingBufPut= IncRingBufferPointer(sRingBufPut);
            sRingBufGet= IncRingBufferPointer(sRingBufGet);
        }
        else //Put over write a data
        {
            sRingBufPut= IncRingBufferPointer(sRingBufPut);
            if (sRingBufPut==sRingBufGet)
            {
                sRingOverWrite= Ture;
                sRingBufGet= IncRingBufferPointer(sRingBufGet);
            }
        }
}

int     GetRingBuffer(void)
{
int     r;
        if (sRingBufGet==sRingBufPut) return 0;
        r= sRingBuf[sRingBufGet];
        sRingBufGet= IncRingBufferPointer(sRingBufGet);
        sRingOverWrite=False;
        return r;
}

int     IncRingBufferPointer(int a)
{
        a+= 1;
        if (a>= cRingBufCount) a= 0;
        return a;
}

How to resolve /var/www copy/write permission denied?

Encountered a similar problem today. Did not see my fix listed here, so I thought I'd share.

Root could not erase a file.

I did my research. Turns out there's something called an immutable bit.

# lsattr /path/file
----i-------- /path/file
#

This bit being configured prevents even root from modifying/removing it.

To remove this I did:

# chattr -i /path/file

After that I could rm the file.

In reverse, it's a neat trick to know if you have something you want to keep from being gone.

:)

How to find out if an item is present in a std::vector?

In C++11 you can use any_of. For example if it is a vector<string> v; then:

if (any_of(v.begin(), v.end(), bind(equal_to<string>(), _1, item)))
   do_this();
else
   do_that();

Alternatively, use a lambda:

if (any_of(v.begin(), v.end(), [&](const std::string& elem) { return elem == item; }))
   do_this();
else
   do_that();

Blank HTML SELECT without blank item in dropdown list

Simply using

<option value="" selected disabled>Please select an option...</option>

will work anywhere without script and allow you to instruct the user at the same time.

All shards failed

It is possible on your restart some shards were not recovered, causing the cluster to stay red.
If you hit:
http://<yourhost>:9200/_cluster/health/?level=shards you can look for red shards.

I have had issues on restart where shards end up in a non recoverable state. My solution was to simply delete that index completely. That is not an ideal solution for everyone.

It is also nice to visualize issues like this with a plugin like:
Elasticsearch Head

How to recover closed output window in netbeans?

In the right bottom edge there are information about NetBeans updates. Left to it, there's the tasks running (building, running application etc). Click on it, right click the process you want and select Show Output.

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

I had the same problem in Pre Lollipop devices. To solve that I did as follows. Meantime I was using multiDex in the project.

1. add this for build.gradle in module: app

multiDexEnabled = true

dexOptions {
    javaMaxHeapSize "4g"
}

2. add this dependancy

compile 'com.android.support:multidex:1.0.1'

3.Then in the MainApplication

public class MainApplication extends MultiDexApplication {

private static MainApplication mainApplication;

@Override
public void onCreate() {
    super.onCreate();
    mainApplication = this;
}

@Override
protected void attachBaseContext(Context context) {
    super.attachBaseContext(context);
    MultiDex.install(this);
}


public static synchronized MainApplication getInstance() {
    return mainApplication;
}
}

4.In the manifests file

<application
    android:allowBackup="true"
    android:name="android.support.multidex.MultiDexApplication"

This works for me. Hope this Helps you too :)

Row Offset in SQL Server

I use this technique for pagination. I do not fetch all the rows. For example, if my page needs to display the top 100 rows I fetch only the 100 with where clause. The output of the SQL should have a unique key.

The table has the following:

ID, KeyId, Rank

The same rank will be assigned for more than one KeyId.

SQL is select top 2 * from Table1 where Rank >= @Rank and ID > @Id

For the first time I pass 0 for both. The second time pass 1 & 14. 3rd time pass 2 and 6....

The value of the 10th record Rank & Id is passed to the next

11  21  1
14  22  1
7   11  1
6   19  2
12  31  2
13  18  2

This will have the least stress on the system

Android Crop Center of Bitmap

enter image description here

This can be achieved with: Bitmap.createBitmap(source, x, y, width, height)

if (srcBmp.getWidth() >= srcBmp.getHeight()){

  dstBmp = Bitmap.createBitmap(
     srcBmp, 
     srcBmp.getWidth()/2 - srcBmp.getHeight()/2,
     0,
     srcBmp.getHeight(), 
     srcBmp.getHeight()
     );

}else{

  dstBmp = Bitmap.createBitmap(
     srcBmp,
     0, 
     srcBmp.getHeight()/2 - srcBmp.getWidth()/2,
     srcBmp.getWidth(),
     srcBmp.getWidth() 
     );
}

A non well formed numeric value encountered

if $_GET['start_date'] is a string then convert it in integer or double to deal numerically.

$int = (int) $_GET['start_date']; //Integer
$double = (double) $_GET['start_date']; //It takes in floating value with 2 digits

Syntax behind sorted(key=lambda: ...)

Since the usage of lambda was asked in the context of sorted(), take a look at this as well https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions

How to clear the text of all textBoxes in the form?

And this for clearing all controls in form like textbox, checkbox, radioButton

you can add different types you want..

private void ClearTextBoxes(Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c is TextBox)
            {
                ((TextBox)c).Clear();
            }

            if (c.HasChildren)
            {
                ClearTextBoxes(c);
            }


            if (c is CheckBox)
            {

                ((CheckBox)c).Checked = false;
            }

            if (c is RadioButton)
            {
                ((RadioButton)c).Checked = false;
            }
        }
    }

How to inject window into a service?

It's also a good idea to mark the DOCUMENT as optional. Per the Angular docs:

Document might not be available in the Application Context when Application and Rendering Contexts are not the same (e.g. when running the application into a Web Worker).

Here's an example of using the DOCUMENT to see whether the browser has SVG support:

import { Optional, Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common'

...

constructor(@Optional() @Inject(DOCUMENT) document: Document) {
   this.supportsSvg = !!(
   document &&
   document.createElementNS &&
   document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect
);

How do you Change a Package's Log Level using Log4j?

Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.

Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).

In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:

log4j.rootLogger=DEBUG, R 
log4j.appender.R=org.apache.log4j.RollingFileAppender 
log4j.appender.R.File=${catalina.home}/logs/tomcat.log 
log4j.appender.R.MaxFileSize=10MB 
log4j.appender.R.MaxBackupIndex=10 
log4j.appender.R.layout=org.apache.log4j.PatternLayout 
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

Simplest would be to change the line:

log4j.rootLogger=DEBUG, R

To something like:

log4j.rootLogger=WARN, R

But if you still want your own DEBUG level output from your own classes add a line that says:

log4j.category.com.mypackage=DEBUG

Reading up a bit on Log4J and Commons-Logging will help you understand all this.

Running Bash commands in Python

To run the command without a shell, pass the command as a list and implement the redirection in Python using [subprocess]:

#!/usr/bin/env python
import subprocess

with open('test.nt', 'wb', 0) as file:
    subprocess.check_call("cwm --rdf test.rdf --ntriples".split(),
                          stdout=file)

Note: no > test.nt at the end. stdout=file implements the redirection.


To run the command using the shell in Python, pass the command as a string and enable shell=True:

#!/usr/bin/env python
import subprocess

subprocess.check_call("cwm --rdf test.rdf --ntriples > test.nt",
                      shell=True)

Here's the shell is responsible for the output redirection (> test.nt is in the command).


To run a bash command that uses bashisms, specify the bash executable explicitly e.g., to emulate bash process substitution:

#!/usr/bin/env python
import subprocess

subprocess.check_call('program <(command) <(another-command)',
                      shell=True, executable='/bin/bash')

How should I make my VBA code compatible with 64-bit Windows?

Office 2007 is 32 bit only so there is no issue there. Your problems arise only with Office 64 bit which has both 32 and 64 bit versions.

You cannot hope to support users with 64 bit Office 2010 when you only have Office 2007. The solution is to upgrade.

If the only Declare that you have is that ShellExecute then you won't have much to do once you get hold of 64 bit Office, but it's not really viable to support users when you can't run the program that you ship! Just think what you would do you do when they report a bug?

Is this the proper way to do boolean test in SQL?

MS SQL 2008 can also use the string version of true or false...

select * from users where active = 'true'
-- or --
select * from users where active = 'false'

Is it possible to return empty in react render function?

Slightly off-topic but if you ever needed a class-based component that never renders anything and you are happy to use some yet-to-be-standardised ES syntax, you might want to go:

render = () => null

This is basically an arrow method that currently requires the transform-class-properties Babel plugin. React will not let you define a component without the render function and this is the most concise form satisfying this requirement that I can think of.

I'm currently using this trick in a variant of ScrollToTop borrowed from the react-router documentation. In my case, there's only a single instance of the component and it doesn't render anything, so a short form of "render null" fits nice in there.

C/C++ NaN constant (literal)?

As others have pointed out you are looking for std::numeric_limits<double>::quiet_NaN() although I have to say I prefer the cppreference.com documents. Especially because this statement is a little vague:

Only meaningful if std::numeric_limits::has_quiet_NaN == true.

and it was simple to figure out what this means on this site, if you check their section on std::numeric_limits::has_quiet_NaN it says:

This constant is meaningful for all floating-point types and is guaranteed to be true if std::numeric_limits::is_iec559 == true.

which as explained here if true means your platform supports IEEE 754 standard. This previous thread explains this should be true for most situations.

How to zip a whole folder using PHP

Why not Try EFS PhP-ZiP MultiVolume Script ... I zipped and transferred hundreds of gigs and millions of files ... ssh is needed to effectively create archives.

But i belive that resulting files can be used with exec directly from php:

exec('zip -r backup-2013-03-30_0 . -i@backup-2013-03-30_0.txt');

I do not know if it works. I have not tried ...

"the secret" is that the execution time for archiving should not exceed the time allowed for execution of PHP code.

How do I initialize a dictionary of empty lists in Python?

Use defaultdict instead:

from collections import defaultdict
data = defaultdict(list)
data[1].append('hello')

This way you don't have to initialize all the keys you want to use to lists beforehand.

What is happening in your example is that you use one (mutable) list:

alist = [1]
data = dict.fromkeys(range(2), alist)
alist.append(2)
print data

would output {0: [1, 2], 1: [1, 2]}.

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

I experienced the same problem when I copied a text that has an apostrophe from a Word document to my HTML code.

To resolve the issue, all I did was deleted the particular word in my HTML and typed it directly, including the apostrophe. This action nullified the original copy and paste acton and displayed the newly typed apostrophe correctly

Export query result to .csv file in SQL Server 2008

Using the native SQL Server Management Studio technique to export to CSV (as @8kb suggested) doesn't work if your values contain commas, because SSMS doesn't wrap values in double quotes. A more robust way that worked for me is to simply copy the results (click inside the grid and then CTRL-A, CTRL-C) and paste it into Excel. Then save as CSV file from Excel.

Is there a label/goto in Python?

Python offers you the ability to do some of the things you could do with a goto using first class functions. For example:

void somefunc(int a)
{
    if (a == 1)
        goto label1;
    if (a == 2)
        goto label2;

    label1:
        ...
    label2:
        ...
}

Could be done in python like this:

def func1():
    ...

def func2():
    ...

funcmap = {1 : func1, 2 : func2}

def somefunc(a):
    funcmap[a]()  #Ugly!  But it works.

Granted, that isn't the best way to substitute for goto. But without knowing exactly what you're trying to do with the goto, it's hard to give specific advice.

@ascobol:

Your best bet is to either enclose it in a function or use an exception. For the function:

def loopfunc():
    while 1:
        while 1:
            if condition:
                return

For the exception:

try:
    while 1:
        while 1:
            raise BreakoutException #Not a real exception, invent your own
except BreakoutException:
    pass

Using exceptions to do stuff like this may feel a bit awkward if you come from another programming language. But I would argue that if you dislike using exceptions, Python isn't the language for you. :-)

SQL Column definition : default value and not null redundant?

In other words, doesn't DEFAULT render NOT NULL redundant ?

No, it is not redundant. To extended accepted answer. For column col which is nullable awe can insert NULL even when DEFAULT is defined:

CREATE TABLE t(id INT PRIMARY KEY, col INT DEFAULT 10);

-- we just inserted NULL into column with DEFAULT
INSERT INTO t(id, col) VALUES(1, NULL);

+-----+------+
| ID  | COL  |
+-----+------+
|   1 | null |
+-----+------+

Oracle introduced additional syntax for such scenario to overide explicit NULL with default DEFAULT ON NULL:

CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10);
-- same as
--CREATE TABLE t2(id INT PRIMARY KEY, col INT DEFAULT ON NULL 10 NOT NULL); 

INSERT INTO t2(id, col) VALUES(1, NULL);

+-----+-----+
| ID  | COL |
+-----+-----+
|  1  |  10 |
+-----+-----+

Here we tried to insert NULL but get default instead.

db<>fiddle demo

ON NULL

If you specify the ON NULL clause, then Oracle Database assigns the DEFAULT column value when a subsequent INSERT statement attempts to assign a value that evaluates to NULL.

When you specify ON NULL, the NOT NULL constraint and NOT DEFERRABLE constraint state are implicitly specified.

How does the Java 'for each' loop work?

It would look something like this. Very crufty.

for (Iterator<String> i = someList.iterator(); i.hasNext(); )
        System.out.println(i.next());

There is a good writeup on for each in the Sun documentation.

Convert boolean result into number/integer

The unary + operator will take care of this:

var test = true;
// +test === 1
test = false;
// +test === 0

You'll naturally want to sanity-check this on the server before storing it, so that might be a more sensible place to do this anyway, though.

Attach (open) mdf file database with SQL Server Management Studio

I found this detailed post about how to open (attach) the MDF file in SQL Server Management Studio: http://learningsqlserver.wordpress.com/2011/02/13/how-can-i-open-mdf-and-ldf-files-in-sql-server-attach-tutorial-troublshooting/

I also have the issue of not being able to navigate to the file. The reason is most likely this:

The reason it won't "open" the folder is because the service account running the SQL Server Engine service does not have read permission on the folder in question. Assign the windows user group for that SQL Server instance the rights to read and list contents at the WINDOWS level. Then you should see the files that you want to attach inside of the folder.

(source: http://social.msdn.microsoft.com/Forums/sqlserver/en-US/c80d8e6a-4665-4be8-b9f5-37eaaa677226/cannot-navigate-to-some-folders-when-attempting-to-attach-mdf-files-to-database-in-management?forum=sqlkjmanageability)

One solution to this problem is described here: http://technet.microsoft.com/en-us/library/jj219062.aspx I haven't tried this myself yet. Once I do, I'll update the answer.

Hope this helps.

How to find the socket buffer size of linux

If you want see your buffer size in terminal, you can take a look at:

  • /proc/sys/net/ipv4/tcp_rmem (for read)
  • /proc/sys/net/ipv4/tcp_wmem (for write)

They contain three numbers, which are minimum, default and maximum memory size values (in byte), respectively.

How to delete duplicates on a MySQL table?

Love @eric's answer but it doesn't seem to work if you have a really big table (I'm getting The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET MAX_JOIN_SIZE=# if the SELECT is okay when I try to run it). So I limited the join query to only consider the duplicate rows and I ended up with:

DELETE a FROM penguins a
    LEFT JOIN (SELECT COUNT(baz) AS num, MIN(baz) AS keepBaz, foo
        FROM penguins
        GROUP BY deviceId HAVING num > 1) b
        ON a.baz != b.keepBaz
        AND a.foo = b.foo
    WHERE b.foo IS NOT NULL

The WHERE clause in this case allows MySQL to ignore any row that doesn't have a duplicate and will also ignore if this is the first instance of the duplicate so only subsequent duplicates will be ignored. Change MIN(baz) to MAX(baz) to keep the last instance instead of the first.

How do I list all the files in a directory and subdirectories in reverse chronological order?

If the number of files you want to view fits within the maximum argument limit you can use globbing to get what you want, with recursion if you have globstar support.

For exactly 2 layers deep use: ls -d * */*

With globstar, for recursion use: ls -d **/*

The -d argument to ls tells it not to recurse directories passed as arguments (since you are using the shell globbing to do the recursion). This prevents ls using its recursion formatting.

Server is already running in Rails

kill -9 $(lsof -i tcp:3000 -t)

Can I dynamically add HTML within a div tag from C# on load event?

You can add a div with runat="server" to the page:

<div runat="server" id="myDiv">
</div>

and then set its InnerHtml property from the code-behind:

myDiv.InnerHtml = "your html here";

If you want to modify the DIV's contents on the client side, then you can use javascript code similar to this:

<script type="text/javascript">
    Sys.Application.add_load(MyLoad);
    function MyLoad(sender) {
        $get('<%= div.ClientID %>').innerHTML += " - text added on client";
    }
</script>

Mark error in form using Bootstrap

Bootstrap V3:

Once i was searching for laravel features then i got to know this amazing form validation. Later on, i amended glyphicon icon features. Now, it looks great.

<div class="col-md-12">
<div class="form-group has-error has-feedback">
    <input id="enter email" name="email" type="text" placeholder="Enter email" class="form-control ">
    <span class="glyphicon glyphicon-remove form-control-feedback"></span>       
    <span class="help-block"><p>The Email field is required.</p></span>                                        
</div>
</div>
<div class="clearfix"></div>

<div class="col-md-6">
<div class="form-group has-error has-feedback">
    <input id="account_holder_name" name="name" type="text" placeholder="Name" class="form-control ">
    <span class="glyphicon glyphicon-remove form-control-feedback"></span>                                            
    <span class="help-block"><p>The Name field is required.</p></span>                                        
</div>
</div>
<div class="col-md-6">
<div class="form-group has-error has-feedback">
 <input id="check_np" name="check_no" type="text" placeholder="Check no" class="form-control ">
 <span class="glyphicon glyphicon-remove form-control-feedback"></span>
<span class="help-block"><p>The Check No. field is required.</p></span>                                       
</div>
</div>

This is what it looks like: enter image description here

Once i completed it i thought i should implement it in Codeigniter as well. So here is the Codeigniter-3 validation with Bootstrap:

Controller

function addData()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|max_length[128]');
if($this->form_validation->run() == FALSE)
{
//validation fails. Load your view.
$this->loadViews('Load your view','pass your data to view if any');
}
else
{  
 //validation pass. Your code here.
}
}

View

<div class="col-md-12">
<?php 
 $email_error = (form_error('email') ? 'has-error has-feedback' : '');
 if(!empty($email_error)){
 $emailData = '<span class="help-block">'.form_error('email').'</span>';
 $emailClass = $email_error;
 $emailIcon = '<span class="glyphicon glyphicon-remove form-control-feedback"></span>';
}
else{
    $emailClass = $emailIcon = $emailData = '';
 } 
 ?>
<div class="form-group <?= $emailClass ?>">
<input id="enter email" name="email" type="text" placeholder="Enter email" class="form-control ">
<?= $emailIcon ?>
<?= $emailData ?>
</div>
</div>

Output: enter image description here

Removing trailing newline character from fgets() input

Perhaps the simplest solution uses one of my favorite little-known functions, strcspn():

buffer[strcspn(buffer, "\n")] = 0;

If you want it to also handle '\r' (say, if the stream is binary):

buffer[strcspn(buffer, "\r\n")] = 0; // works for LF, CR, CRLF, LFCR, ...

The function counts the number of characters until it hits a '\r' or a '\n' (in other words, it finds the first '\r' or '\n'). If it doesn't hit anything, it stops at the '\0' (returning the length of the string).

Note that this works fine even if there is no newline, because strcspn stops at a '\0'. In that case, the entire line is simply replacing '\0' with '\0'.

Build error: "The process cannot access the file because it is being used by another process"

For those who are developing in VS with Docker, restart the docker for windows service and the problem will be solved immediately.

Before restarting docker I tried all the mentioned answers, didn't find a msbuild.exe process running, also tried restarting VS without avail, only restarting docker worked.

Toolbar Navigation Hamburger Icon missing

For that you just need write to some lines

   DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
   ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
   drawer.addDrawerListener(toggle);
   toggle.setDrawerIndicatorEnabled(true);
   toggle.syncState();

toggle.setDrawerIndicatorEnabled(true); if this is false make it true or remove this line

class << self idiom in Ruby

Usually, instance methods are global methods. That means they are available in all instances of the class on which they were defined. In contrast, a singleton method is implemented on a single object.

Ruby stores methods in classes and all methods must be associated with a class. The object on which a singleton method is defined is not a class (it is an instance of a class). If only classes can store methods, how can an object store a singleton method? When a singleton method is created, Ruby automatically creates an anonymous class to store that method. These anonymous classes are called metaclasses, also known as singleton classes or eigenclasses. The singleton method is associated with the metaclass which, in turn, is associated with the object on which the singleton method was defined.

If multiple singleton methods are defined within a single object, they are all stored in the same metaclass.

class Zen
end

z1 = Zen.new
z2 = Zen.new

class << z1
  def say_hello
    puts "Hello!"
  end
end

z1.say_hello    # Output: Hello!
z2.say_hello    # Output: NoMethodError: undefined method `say_hello'…

In the above example, class << z1 changes the current self to point to the metaclass of the z1 object; then, it defines the say_hello method within the metaclass.

Classes are also objects (instances of the built-in class called Class). Class methods are nothing more than singleton methods associated with a class object.

class Zabuton
  class << self
    def stuff
      puts "Stuffing zabuton…"
    end
  end
end

All objects may have metaclasses. That means classes can also have metaclasses. In the above example, class << self modifies self so it points to the metaclass of the Zabuton class. When a method is defined without an explicit receiver (the class/object on which the method will be defined), it is implicitly defined within the current scope, that is, the current value of self. Hence, the stuff method is defined within the metaclass of the Zabuton class. The above example is just another way to define a class method. IMHO, it's better to use the def self.my_new_clas_method syntax to define class methods, as it makes the code easier to understand. The above example was included so we understand what's happening when we come across the class << self syntax.

Additional info can be found at this post about Ruby Classes.

"message failed to fetch from registry" while trying to install any module

The below method worked for me, Kudos to github user : midnightcodr

Make sure You remove any nodejs/npm packages already installed.

sudo apt-get purge nodejs

sudo apt-get purge npm

Now Install Node js using the command below( Thanks to midnightcodr on github)

curl -L https://raw.github.com/midnightcodr/rpi_node_install/master/setup.sh | bash -s 0.10.24

Note that you can invoke node with command node and not nodejs.

Once node is installed , Install npm

sudo apt-get install npm

How do I reverse a commit in git?

You can do git push --force but be aware that you are rewriting history and anyone using the repo will have issue with this.

If you want to prevent this problem, don't use reset, but instead use git revert

"Application tried to present modally an active controller"?

I have the same problem. I try to present view controller just after dismissing.

[self dismissModalViewControllerAnimated:YES];

When I try to do it without animation it works perfectly so the problem is that controller is still alive. I think that the best solution is to use dismissViewControllerAnimated:completion: for iOS5

At least one JAR was scanned for TLDs yet contained no TLDs

(tomcat 7.0.32) I had problems to see debug messages althought was enabling TldLocationsCache row in tomcat/conf/logging.properties file. All I could see was a warning but not what libs were scanned. Changed every loglevel tried everything no luck. Then I went rogue debug mode (=remove one by one, clean install etc..) and finally found a reason.

My webapp had a customized tomcat/webapps/mywebapp/WEB-INF/classes/logging.properties file. I copied TldLocationsCache row to this file, finally I could see jars filenames.

# To see debug messages in TldLocationsCache, uncomment the following line: org.apache.jasper.compiler.TldLocationsCache.level = FINE

TERM environment variable not set

You can see if it's really not set. Run the command set | grep TERM.

If not, you can set it like that: export TERM=xterm

When to use HashMap over LinkedList or ArrayList and vice-versa

I will put here some real case examples and scenarios when to use one or another, it might be of help for somebody else:

HashMap

When you have to use cache in your application. Redis and membase are some type of extended HashMap. (Doesn't matter the order of the elements, you need quick ( O(1) ) read access (a value), using a key).

LinkedList

When the order is important (they are ordered as they were added to the LinkedList), the number of elements are unknown (don't waste memory allocation) and you require quick insertion time ( O(1) ). A list of to-do items that can be listed sequentially as they are added is a good example.

How to fill background image of an UIView

Repeat:

UIImage *img = [UIImage imageNamed:@"bg.png"];
view.backgroundColor = [UIColor colorWithPatternImage:img];

Stretched

UIImage *img = [UIImage imageNamed:@"bg.png"];
view.layer.contents = img.CGImage;

How to align checkboxes and their labels consistently cross-browsers

label {
    display: inline-block;
    padding-right: 10px;
}
input[type=checkbox] {
    position: relative;
    top: 2px;
}

Reading binary file and looping over each byte

If the file is not too big that holding it in memory is a problem:

with open("filename", "rb") as f:
    bytes_read = f.read()
for b in bytes_read:
    process_byte(b)

where process_byte represents some operation you want to perform on the passed-in byte.

If you want to process a chunk at a time:

with open("filename", "rb") as f:
    bytes_read = f.read(CHUNKSIZE)
    while bytes_read:
        for b in bytes_read:
            process_byte(b)
        bytes_read = f.read(CHUNKSIZE)

The with statement is available in Python 2.5 and greater.

How to clamp an integer to some range?

many interesting answers here, all about the same, except... which one's faster?

import numpy
np_clip = numpy.clip
mm_clip = lambda x, l, u: max(l, min(u, x))
s_clip = lambda x, l, u: sorted((x, l, u))[1]
py_clip = lambda x, l, u: l if x < l else u if x > u else x
>>> import random
>>> rrange = random.randrange
>>> %timeit mm_clip(rrange(100), 10, 90)
1000000 loops, best of 3: 1.02 µs per loop

>>> %timeit s_clip(rrange(100), 10, 90)
1000000 loops, best of 3: 1.21 µs per loop

>>> %timeit np_clip(rrange(100), 10, 90)
100000 loops, best of 3: 6.12 µs per loop

>>> %timeit py_clip(rrange(100), 10, 90)
1000000 loops, best of 3: 783 ns per loop

paxdiablo has it!, use plain ol' python. The numpy version is, perhaps not surprisingly, the slowest of the lot. Probably because it's looking for arrays, where the other versions just order their arguments.

How to delete the first row of a dataframe in R?

While I agree with the most voted answer, here is another way to keep all rows except the first:

dat <- tail(dat, -1)

This can also be accomplished using Hadley Wickham's dplyr package.

dat <- dat %>% slice(-1)

Update value of a nested dictionary of varying depth

@Alex's answer is good, but doesn't work when replacing an element such as an integer with a dictionary, such as update({'foo':0},{'foo':{'bar':1}}). This update addresses it:

import collections
def update(d, u):
    for k, v in u.iteritems():
        if isinstance(d, collections.Mapping):
            if isinstance(v, collections.Mapping):
                r = update(d.get(k, {}), v)
                d[k] = r
            else:
                d[k] = u[k]
        else:
            d = {k: u[k]}
    return d

update({'k1': 1}, {'k1': {'k2': {'k3': 3}}})

Maven: repository element was not specified in the POM inside distributionManagement?

The ID of the two repos are both localSnap; that's probably not what you want and it might confuse Maven.

If that's not it: There might be more repository elements in your POM. Search the output of mvn help:effective-pom for repository to make sure the number and place of them is what you expect.

Getting unique values in Excel by using formulas only

noticed its a very old question but people seem still having trouble using a formula for extracting unique items. here's a solution that returns the values them selfs.

Lets say you have "red", "blue", "red", "green", "blue", "black" in column A2:A7

then put this in B2 as an array formula and copy down =IFERROR(INDEX(A$2:A$7;SMALL(IF(FREQUENCY(MATCH(A$2:A$7;A$2:A$7;0);ROW(INDIRECT("1:"&COUNTA(A$2:A$7))));ROW(INDIRECT("1:"&COUNTA(A$2:A$7)));"");ROW(A1)));"")

then it should look something like this; enter image description here

How can I show and hide elements based on selected option with jQuery?

To show the div while selecting one value and hide while selecting another value from dropdown box: -

 $('#yourselectorid').bind('change', function(event) {

           var i= $('#yourselectorid').val();

            if(i=="sometext") // equal to a selection option
             {
                 $('#divid').show();
             }
           elseif(i=="othertext")
             {
               $('#divid').hide(); // hide the first one
               $('#divid2').show(); // show the other one

              }
});

Difference between Relative path and absolute path in javascript

Relative Paths

A relative path assumes that the file is on the current server. Using relative paths allows you to construct your site offline and fully test it before uploading it.

For example:

php/webct/itr/index.php

.

Absolute Paths

An absolute path refers to a file on the Internet using its full URL. Absolute paths tell the browser precisely where to go.

For example:

http://www.uvsc.edu/disted/php/webct/itr/index.php

Absolute paths are easier to use and understand. However, it is not good practice on your own website. For one thing, using relative paths allows you to construct your site offline and fully test it before uploading it. If you were to use absolute paths you would have to change your code before uploading it in order to get it to work. This would also be the case if you ever had to move your site or if you changed domain names.

Reference: http://openhighschoolcourses.org/mod/book/tool/print/index.php?id=12503

Get escaped URL parameter

For example , a function which returns value of any parameters variable.

function GetURLParameter(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}?

And this is how you can use this function assuming the URL is,

"http://example.com/?technology=jquery&blog=jquerybyexample".

var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');

So in above code variable "tech" will have "jQuery" as value and "blog" variable's will be "jquerybyexample".

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

If you use the procedural style, you have to provide both a connection and a string:

$name = mysqli_real_escape_string($conn, $name);

Only the object oriented version can be done with just a string:

$name = $link->real_escape_string($name);

The documentation should hopefully make this clear.

Debugging in Maven?

I use the MAVEN_OPTS option, and find it useful to set suspend to "suspend=y" as my exec:java programs tend to be small generators which are finished before I have manage to attach a debugger.... :) With suspend on it will wait for a debugger to attach before proceding.

Garbage collector in Android

Quick note for Xamarin developers.

If you would like to call System.gc() in Xamarin.Android apps you should call Java.Lang.JavaSystem.Gc()

Are the days of passing const std::string & as a parameter over?

The problem is that "const" is a non-granular qualifier. What is usually meant by "const string ref" is "don't modify this string", not "don't modify the reference count". There is simply no way, in C++, to say which members are "const". They either all are, or none of them are.

In order to hack around this language issue, STL could allow "C()" in your example to make a move-semantic copy anyway, and dutifully ignore the "const" with regard to the reference count (mutable). As long as it was well-specified, this would be fine.

Since STL doesn't, I have a version of a string that const_casts<> away the reference counter (no way to retroactively make something mutable in a class hierarchy), and - lo and behold - you can freely pass cmstring's as const references, and make copies of them in deep functions, all day long, with no leaks or issues.

Since C++ offers no "derived class const granularity" here, writing up a good specification and making a shiny new "const movable string" (cmstring) object is the best solution I've seen.

How to get out of while loop in java with Scanner method "hasNext" as condition?

The Scanner will continue to read until it finds an "end of file" condition.

As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.

Eclipse internal error while initializing Java tooling

In my case, I had two of three projects with this problem in my current workspace. I opened workspace catalog and made a backup of corrupted projects, deleted them afterwards. Then opened eclipse once again. Obviously there was missing data to work with. Closed eclipse once again and added back earlier saved projects without metadata catalogs.

TL;DR. Just remove metadata catalogs from projects in your workspace.

fs.writeFile in a promise, asynchronous-synchronous stuff

What worked for me was fs.promises.

Example One:

const fs = require("fs")

fs.promises
  .writeFile(__dirname + '/test.json', "data", { encoding: 'utf8' })
  .then(() => {
    // Do whatever you want to do.
    console.log('Done');
  });

Example Two. Using Async-Await:

const fs = require("fs")

async function writeToFile() {
  await fs.promises.writeFile(__dirname + '/test-22.json', "data", {
    encoding: 'utf8'
  });

  console.log("done")
}

writeToFile()

Convert HashBytes to VarChar

I have found the solution else where:

SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', 'HelloWorld')), 3, 32)

Declaring static constants in ES6 classes?

You can make the "constants" read-only (immutable) by freezing the class. e.g.

class Foo {
    static BAR = "bat"; //public static read-only
}

Object.freeze(Foo); 

/*
Uncaught TypeError: Cannot assign to read only property 'BAR' of function 'class Foo {
    static BAR = "bat"; //public static read-only
}'
*/
Foo.BAR = "wut";

One time page refresh after first page load

use window.localStorage... like this

var refresh = $window.localStorage.getItem('refresh');
console.log(refresh);
if (refresh===null){
    window.location.reload();
    $window.localStorage.setItem('refresh', "1");
}

It's work for me

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

How to change an element's title attribute using jQuery

Another option, if you prefer, would be to get the DOM element from the jQuery object and use standard DOM accessors on it:

$("#myElement")[0].title = "new title value";

The "jQuery way", as mentioned by others, is to use the attr() method. See the API documentation for attr() here.

Why Anaconda does not recognize conda command?

I had a similar problem and I did something like the below mentioned steps with my Path environment variable to fix the problem

  1. Located where my Anaconda3 was installed. I run Windows 7. Mine is located at C:\ProgramData\Anaconda3.

  2. Open Control Panel - System - Advanced System Settings, under Advanced tab click on Environment Variables.

  3. Under System Variables, located "Path" add the following: C:\ProgramData\Anaconda3\Scripts;C:\ProgramData\Anaconda3\;

Save and open new terminal. type in "conda". It worked for me.

Hope these steps help

Pip install - Python 2.7 - Windows 7

It is possible that in python 2.7 pip is installed by default. if it is not then you can execute

python -m ensurepip --default-pip

This worked for me.

Source: https://docs.python.org/2/installing/

What are valid values for the id attribute in HTML?

Strictly it should match

[A-Za-z][-A-Za-z0-9_:.]*

But jquery seems to have problems with colons so it might be better to avoid them.

Check folder size in Bash

if you just want to see the aggregate size of the folder and probably in MB or GB format, please try the below script

$du -s --block-size=M /path/to/your/directory/

How do I validate a date in rails?

You can validate the date and time like so (in a method somewhere in your controller with access to your params if you are using custom selects) ...

# Set parameters
year = params[:date][:year].to_i
month = params[:date][:month].to_i
mday = params[:date][:mday].to_i
hour = params[:date][:hour].to_i
minute = params[:date][:minute].to_i

# Validate date, time and hour
valid_date    = Date.valid_date? year, month, mday
valid_hour    = (0..23).to_a.include? hour
valid_minute  = (0..59).to_a.include? minute
valid_time    = valid_hour && valid_minute

# Check if parameters are valid and generate appropriate date
if valid_date && valid_time
  second = 0
  offset = '0'
  DateTime.civil(year, month, mday, hour, minute, second, offset)
else
  # Some fallback if you want like ...
  DateTime.current.utc
end

resource error in android studio after update: No Resource Found

Method 1: It is showing.you did not install Api 23. So please install API 23.

Method 2:

Change the appcompat version in your build.gradle file back to 22.0.1 (or less).

How to change heatmap.2 color range in R?

You could try to create your own color palette using the RColorBrewer package

my_palette <- colorRampPalette(c("green", "black", "red"))(n = 1000)

and see how this looks like. But I assume in your case only scaling would help if you really want to keep the black in "the middle". You can simply use my_palette instead of the redgreen()

I recommend that you check out the RColorBrewer package, they have pretty nice in-built palettes, and see interactive website for colorbrewer.

Asyncio.gather vs asyncio.wait

asyncio.wait is more low level than asyncio.gather.

As the name suggests, asyncio.gather mainly focuses on gathering the results. It waits on a bunch of futures and returns their results in a given order.

asyncio.wait just waits on the futures. And instead of giving you the results directly, it gives done and pending tasks. You have to manually collect the values.

Moreover, you could specify to wait for all futures to finish or just the first one with wait.

Parameter "stratify" from method "train_test_split" (scikit Learn)

For my future self who comes here via Google:

train_test_split is now in model_selection, hence:

from sklearn.model_selection import train_test_split

# given:
# features: xs
# ground truth: ys

x_train, x_test, y_train, y_test = train_test_split(xs, ys,
                                                    test_size=0.33,
                                                    random_state=0,
                                                    stratify=ys)

is the way to use it. Setting the random_state is desirable for reproducibility.

How can I execute a PHP function in a form action?

You can put the username() function in another page, and send the form to that page...

Bootstrap 3 hidden-xs makes row narrower

.row {
    margin-right: 15px;
}

throw this in your CSS

Strip all non-numeric characters from string in JavaScript

we are in 2017 now you can also use ES2016

var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));

or

console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));  

The result is

1238

Simple JavaScript problem: onClick confirm not preventing default action

I had issue alike (click on button, but after cancel clicked it still removes my object), so made this in such way, hope it helps someone in the future:

 $('.deleteObject').click(function () {
    var url = this.href;
    var confirmText = "Are you sure you want to delete this object?";
    if(confirm(confirmText)) {
        $.ajax({
            type:"POST",
            url:url,
            success:function () {
            // Here goes something...
            },
        });
    }
    return false;
});

How do you set the max number of characters for an EditText in Android?

In XML you can add this line to the EditText View where 140 is the maximum number of characters:

android:maxLength="140"

How to get the current user in ASP.NET MVC

If you are inside your login page, in LoginUser_LoggedIn event for instance, Current.User.Identity.Name will return an empty value, so you have to use yourLoginControlName.UserName property.

MembershipUser u = Membership.GetUser(LoginUser.UserName);

How to modify the nodejs request default timeout time?

Try this:

var options = {
    url:  'http://url',
    timeout: 120000
}

request(options, function(err, resp, body) {});

Refer to request's documentation for other options.

nodejs get file name from absolute path?

If you already know that the path separator is / (i.e. you are writing for a specific platform/environment), as implied by the example in your question, you could keep it simple and split the string by separator:

'/foo/bar/baz/asdf/quux.html'.split('/').pop()

That would be faster (and cleaner imo) than replacing by regular expression.

Again: Only do this if you're writing for a specific environment, otherwise use the path module, as paths are surprisingly complex. Windows, for instance, supports / in many cases but not for e.g. the \\?\? style prefixes used for shared network folders and the like. On Windows the above method is doomed to fail, sooner or later.

How can I get the content of CKEditor using JQuery?

I was having issues with the getData() not working every time especially when dealing with live ajax.

Was able to get around it by running:

for(var instanceName in CKEDITOR.instances){
    CKEDITOR.instances[instanceName].updateElement();
}

Then use jquery to get the value from the textarea.

How to convert float value to integer in php?

I just want to WARN you about:

>>> (int) (290.15 * 100);
=> 29014
>>> (int) round((290.15 * 100), 0);
=> 29015

Git keeps prompting me for a password

I had this issue. A repo was requiring me to input credentials every time. All my other repos were not asking for my credentials. They were even set up to track GitLab using HTTPS under the same account credentials, so it was weird that they all worked fine except one.

Comparing the .git/config files, I found that there were 2 key differences in the URLs which was causing the issue:

Does ask for credentials:

https://gitlab.com/myaccount/myproject

Does not ask for credentials:

https://[email protected]/myaccount/myproject.git 

So adding the "myaccount@" and ".git" resolved the issue in my case.

See last changes in svn

svn log -r {2009-09-17}:HEAD

where 2009-09-17 is the date you went on holiday. To see the changed files as well as the summary, add a -v option:

svn log -r {2009-09-17}:HEAD -v

I haven't used WebSVN but there will be a log viewer somewhere that does the equivalent of these commands under the hood.

Is it possible to have placeholders in strings.xml for runtime values?

If you want to write percent (%), duplicate it:

<string name="percent">%1$d%%</string>

label.text = getString(R.string.percent, 75) // Output: 75%.

If you write simply %1$d%, you will get the error: Format string 'percent' is not a valid format string so it should not be passed to String.format.

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files (x86)\OpenERP 6.1-20121026-233219\PostgreSQL\data

Laravel whereIn OR whereIn

$query = DB::table('dms_stakeholder_permissions');
$query->select(DB::raw('group_concat(dms_stakeholder_permissions.fid) as fid'),'dms_stakeholder_permissions.rights');
$query->where('dms_stakeholder_permissions.stakeholder_id','4');
$query->orWhere(function($subquery)  use ($stakeholderId){
            $subquery->where('dms_stakeholder_permissions.stakeholder_id',$stakeholderId);
            $subquery->whereIn('dms_stakeholder_permissions.rights',array('1','2','3'));
    });

 $result = $query->get();

return $result;

// OUTPUT @input $stakeholderId = 1

//select group_concat(dms_stakeholder_permissions.fid) as fid, dms_stakeholder_permissionss.rights from dms_stakeholder_permissions where dms_stakeholder_permissions.stakeholder_id = 4 or (dms_stakeholder_permissions.stakeholder_id = 1 and dms_stakeholder_permissions.rights in (1, 2, 3))

Android: Create a toggle button with image and no text

  1. Can I replace the toggle text with an image

    No, we can not, although we can hide the text by overiding the default style of the toggle button, but still that won't give us a toggle button you want as we can't replace the text with an image.

  2. How can I make a normal toggle button

    Create a file ic_toggle in your res/drawable folder

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:state_checked="false"
              android:drawable="@drawable/ic_slide_switch_off" />
    
        <item android:state_checked="true"
              android:drawable="@drawable/ic_slide_switch_on" />
    
    </selector>
    

    Here @drawable/ic_slide_switch_on & @drawable/ic_slide_switch_off are images you create.

    Then create another file in the same folder, name it ic_toggle_bg

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
        <item android:id="@+android:id/background"  
              android:drawable="@android:color/transparent" />
    
        <item android:id="@+android:id/toggle"
              android:drawable="@drawable/ic_toggle" />
    
    </layer-list>
    

    Now add to your custom theme, (if you do not have one create a styles.xml file in your res/values/folder)

    <style name="Widget.Button.Toggle" parent="android:Widget">
       <item name="android:background">@drawable/ic_toggle_bg</item>
       <item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
    </style>
    
    <style name="toggleButton"  parent="@android:Theme.Black">
       <item name="android:buttonStyleToggle">@style/Widget.Button.Toggle</item>
       <item name="android:textOn"></item>
       <item name="android:textOff"></item>
    </style>
    

    This creates a custom toggle button for you.

  3. How to use it

    Use the custom style and background in your view.

      <ToggleButton
            android:id="@+id/toggleButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            style="@style/toggleButton"
            android:background="@drawable/ic_toggle_bg"/>
    

Node.js quick file server (static files over HTTP)

Here's another simple web server.

https://www.npmjs.com/package/hostr

Install

npm install -g hostr

Change working director

cd myprojectfolder/

And start

hostr

Circular dependency in Spring

The Spring container is able to resolve Setter-based circular dependencies but gives a runtime exception BeanCurrentlyInCreationException in case of Constructor-based circular dependencies. In case of Setter-based circular dependency, the IOC container handles it differently from a typical scenario wherein it would fully configure the collaborating bean before injecting it. For eg., if Bean A has a dependency on Bean B and Bean B on Bean C, the container fully initializes C before injecting it to B and once B is fully initialized it is injected to A. But in case of circular dependency, one of the beans is injected to the other before it is fully initialized.

How to filter for multiple criteria in Excel?

Maybe not as elegant but another possibility would be to write a formula to do the check and fill it in an adjacent column. You could then filter on that column.

The following looks in cell b14 and would return true for all the file types you mention. This assumes that the file extension is by itself in the column. If it's not it would be a little more complicated but you could still do it this way.

=OR(B14=".pdf",B14=".doc",B14=".docx",B14=".xls",B14=".xlsx",B14=".rtf",B14=".txt",B14=".csv",B14=".pps")

Like I said, not as elegant as the advanced filters but options are always good.

UIScrollView not scrolling

I made it working at my first try. With auto layout and everything, no additional code. Then a collection view went banana, crashing at run time, I couldn't find what was wrong, so I deleted and recreated it (I am using Xcode 10 Beta 4. It felt like a bug) and then the scrolling was gone. The Collection view worked again, though!

Many hours later.. this is what fixed it for me. I had the following layout:

UIView

  • Safe Area
  • Scroll view
    • Content view

It's all in the constraints. Safe Area is automatically defined by the system. In the worst case remove all constraints for scroll and content views and do not have IB resetting/creating them for you. Make them manually, it works.

  • For Scroll view I did: Align Trailing/Top to Safe Area. Equal Width/Height to Safe area.
  • For Content view I did: Align Trailing/Leading/Top/Bottom to Superview (the scroll view)

basically the concept is to have Content view fitting Scrollview, which is fitting Safe Area.

But as such it didn't work. Content view missed the height. I tried all I could and the only one doing the trick has been a Content view height created control-dragging Content view.. to itself. That defined a fixed height, which value has been computed from the Size of the the view controller (defined as freeform, longer than the real display, to containing all my subviews) and finally it worked again!

Python glob multiple filetypes

Chain the results:

import itertools as it, glob

def multiple_file_types(*patterns):
    return it.chain.from_iterable(glob.iglob(pattern) for pattern in patterns)

Then:

for filename in multiple_file_types("*.txt", "*.sql", "*.log"):
    # do stuff

How to inspect FormData?

I use the formData.entries() method. I'm not sure about all browser support, but it works fine on Firefox.

Taken from https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries

// Create a test FormData object
var formData = new FormData();
formData.append('key1','value1');
formData.append('key2','value2');

// Display the key/value pairs
for (var pair of formData.entries())
{
 console.log(pair[0]+ ', '+ pair[1]); 
}

There is also formData.get() and formData.getAll() with wider browser support, but they only bring up the Values and not the Key. See the link for more info.

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

For anyone who stumbles across this post looking for a solution and you've set up SMTP sendgrid via Azure.

The username is not the username you set up when you've created the sendgrid object in azure. To find your username;

  • Click on your sendgrid object in azure and click manage. You will be redirected to the SendGrid site.
  • Confirm your email and then copy down the username displayed there.. it's an automatically generated username.
  • Add the username from SendGrid into your SMTP settings in the web.config file.

Hope this helps!

Combine a list of data frames into one data frame by row

How it should be done in the tidyverse:

df.dplyr.purrr <- listOfDataFrames %>% map_df(bind_rows)

Accessing Object Memory Address

Just in response to Torsten, I wasn't able to call addressof() on a regular python object. Furthermore, id(a) != addressof(a). This is in CPython, don't know about anything else.

>>> from ctypes import c_int, addressof
>>> a = 69
>>> addressof(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: invalid type
>>> b = c_int(69)
>>> addressof(b)
4300673472
>>> id(b)
4300673392

How to kill all processes with a given partial name?

Also you can use killall -r my_pattern. -r Interpret process name pattern as an extended regular expression.

killall -r my_pattern

Conversion from Long to Double in Java

I think it is good for you.

BigDecimal.valueOf([LONG_VALUE]).doubleValue()

How about this code? :D

Round a double to 2 decimal places

double value= 200.3456;
DecimalFormat df = new DecimalFormat("0.00");      
System.out.println(df.format(value));

Passing an array as an argument to a function in C

Passing a multidimensional array as argument to a function. Passing an one dim array as argument is more or less trivial. Let's take a look on more interesting case of passing a 2 dim array. In C you can't use a pointer to pointer construct (int **) instead of 2 dim array. Let's make an example:

void assignZeros(int(*arr)[5], const int rows) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < 5; j++) {
            *(*(arr + i) + j) = 0;
            // or equivalent assignment
            arr[i][j] = 0;
        }
    }

Here I have specified a function that takes as first argument a pointer to an array of 5 integers. I can pass as argument any 2 dim array that has 5 columns:

int arr1[1][5]
int arr1[2][5]
...
int arr1[20][5]
...

You may come to an idea to define a more general function that can accept any 2 dim array and change the function signature as follows:

void assignZeros(int ** arr, const int rows, const int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            *(*(arr + i) + j) = 0;
        }
    }
}

This code would compile but you will get a runtime error when trying to assign the values in the same way as in the first function. So in C a multidimensional arrays are not the same as pointers to pointers ... to pointers. An int(*arr)[5] is a pointer to array of 5 elements, an int(*arr)[6] is a pointer to array of 6 elements, and they are a pointers to different types!

Well, how to define functions arguments for higher dimensions? Simple, we just follow the pattern! Here is the same function adjusted to take an array of 3 dimensions:

void assignZeros2(int(*arr)[4][5], const int dim1, const int dim2, const int dim3) {
    for (int i = 0; i < dim1; i++) {
        for (int j = 0; j < dim2; j++) {
            for (int k = 0; k < dim3; k++) {
                *(*(*(arr + i) + j) + k) = 0;
                // or equivalent assignment
                arr[i][j][k] = 0;
            }
        }
    }
}

How you would expect, it can take as argument any 3 dim arrays that have in the second dimensions 4 elements and in the third dimension 5 elements. Anything like this would be OK:

arr[1][4][5]
arr[2][4][5]
...
arr[10][4][5]
...

But we have to specify all dimensions sizes up to the first one.

What does $1 [QSA,L] mean in my .htaccess file?

This will capture requests for files like version, release, and README.md, etc. which should be treated either as endpoints, if defined (as in the case of /release), or as "not found."

MySQL Data Source not appearing in Visual Studio

Tried everything but on Visual Studio 2015 Community edition I got it working when I installed MySQL for Visual Studio 1.2.4+ from http://dev.mysql.com/downloads/windows/visualstudio/ At time of writing I could download 1.2.6 which worked for me.

enter image description here

Release notes of 1.2.4 which adds support for VS2015 can be found at http://forums.mysql.com/read.php?3,633391

Return array from function

neater:

function BlockID() {
  return {
    "s":"Images/Block_01.png",
    "g":"Images/Block_02.png",
    "C":"Images/Block_03.png",
    "d":"Images/Block_04.png"
   }
}

or just

var images = {
  "s":"Images/Block_01.png",
  "g":"Images/Block_02.png",
  "C":"Images/Block_03.png",
  "d":"Images/Block_04.png"
}

Run .jar from batch-file

Just the same way as you would do in command console. Copy exactly those commands in the batch file.

MVVM: Tutorial from start to finish?

I really liked these articles:

  1. MVVM for Tarded Folks Like Me
  2. How Tards Like Me Make MVVM Apps

He really dumbs down the concept in a humorous way. Worth reading.

Binding a generic list to a repeater - ASP.NET

Code Behind:

public class Friends
{
    public string   ID      { get; set; }
    public string   Name    { get; set; }
    public string   Image   { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
        List <Friends> friendsList = new List<Friends>();

        foreach (var friend  in friendz)
        {
            friendsList.Add(
                new Friends { ID = friend.id, Name = friend.name }    
            );

        }

        this.rptFriends.DataSource = friendsList;
        this.rptFriends.DataBind();
}

.aspx Page

<asp:Repeater ID="rptFriends" runat="server">
            <HeaderTemplate>
                <table border="0" cellpadding="0" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
            </HeaderTemplate>
            <ItemTemplate>
                    <tr>
                        <td><%# Eval("ID") %></td>
                        <td><%# Eval("Name") %></td>
                    </tr>
            </ItemTemplate>
            <FooterTemplate>
                    </tbody>
                </table>
            </FooterTemplate>
        </asp:Repeater>

Use bash to find first folder name that contains a string

pattern="foo"
for _dir in *"${pattern}"*; do
    [ -d "${_dir}" ] && dir="${_dir}" && break
done
echo "${dir}"

This is better than the other shell solution provided because

  • it will be faster for huge directories as the pattern is part of the glob and not checked inside the loop
  • actually works as expected when there is no directory matching your pattern (then ${dir} will be empty)
  • it will work in any POSIX-compliant shell since it does not rely on the =~ operator (if you need this depends on your pattern)
  • it will work for directories containing newlines in their name (vs. find)

Why doesn't list have safe "get" method like dictionary?

Ultimately it probably doesn't have a safe .get method because a dict is an associative collection (values are associated with names) where it is inefficient to check if a key is present (and return its value) without throwing an exception, while it is super trivial to avoid exceptions accessing list elements (as the len method is very fast). The .get method allows you to query the value associated with a name, not directly access the 37th item in the dictionary (which would be more like what you're asking of your list).

Of course, you can easily implement this yourself:

def safe_list_get (l, idx, default):
  try:
    return l[idx]
  except IndexError:
    return default

You could even monkeypatch it onto the __builtins__.list constructor in __main__, but that would be a less pervasive change since most code doesn't use it. If you just wanted to use this with lists created by your own code you could simply subclass list and add the get method.

Proper way to wait for one function to finish before continuing?

An elegant way to wait for one function to complete first is to use Promises with async/await function.


  1. Firstly, create a Promise. The function I created will be completed after 2s. I used setTimeout in order to demonstrate the situation where the instructions would take some time to execute.
  2. For the second function, you can use async/await function where you will await for the first function to complete before proceeding with the instructions.

Example:

_x000D_
_x000D_
    //1. Create a new function that returns a promise
    function firstFunction() {
      return new Promise((resolve, reject) => {
          let y = 0
          setTimeout(() => {
            for(i=0; i<10; i++){
               y++
            }
             console.log('loop completed')  
             resolve(y)
          }, 2000)
      })
    }
    
    //2. Create an async function
    async function secondFunction() {
        console.log('before promise call')
        //3. Await for the first function to complete
        let result = await firstFunction()
        console.log('promise resolved: ' + result)
        console.log('next step')
    }; 

    secondFunction()
_x000D_
_x000D_
_x000D_


Note:

You could simply resolve the Promise without any value like so resolve(). In my example, I resolved the Promise with the value of y that I can then use in the second function.

Boolean operators && and ||

The shorter ones are vectorized, meaning they can return a vector, like this:

((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE  TRUE FALSE FALSE

The longer form evaluates left to right examining only the first element of each vector, so the above gives

((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE

As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."

So you want to use the long forms only when you are certain the vectors are length one.

You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.

The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.

One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.

a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found

Finally, see section 8.2.17 in The R Inferno, titled "and and andand".

How to verify a method is called two times with mockito verify()

Using the appropriate VerificationMode:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

XPath to fetch SQL XML value

Update

My recomendation would be to shred the XML into relations and do searches and joins on the resulted relation, in a set oriented fashion, rather than the procedural fashion of searching specific nodes in the XML. Here is a simple XML query that shreds out the nodes and attributes of interest:

select x.value(N'../../../../@stepId', N'int') as StepID
  , x.value(N'../../@id', N'int') as ComponentID
  , x.value(N'@nom',N'nvarchar(100)') as Nom
  , x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box/components/component/variables/variable') t(x)

However, if you must use an XPath that retrieves exactly the value of interest:

select x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
       variables/variable[@nom="Enabled"]') t(x)

If the stepID and component ID are columns, not variables, the you should use sql:column() instead of sql:variable in the XPath filters. See Binding Relational Data Inside XML Data.

And finaly if all you need is to check for existance you can use the exist() XML method:

select @x.exist(
  N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
      variables/variable[@nom="Enabled" and @valeur="Yes"]') 

Database cluster and load balancing

Clustering uses shared storage of some kind (a drive cage or a SAN, for example), and puts two database front-ends on it. The front end servers share an IP address and cluster network name that clients use to connect, and they decide between themselves who is currently in charge of serving client requests.

If you're asking about a particular database server, add that to your question and we can add details on their implementation, but at its core, that's what clustering is.

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

Add another option, maybe not the most lightweight.

_x000D_
_x000D_
dayjs.extend(dayjs_plugin_customParseFormat)
console.log(dayjs('2018-09-06 17:00:00').format( 'YYYY-MM-DDTHH:mm:ss.000ZZ'))
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/plugin/customParseFormat.js"></script>
_x000D_
_x000D_
_x000D_

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

Perhaps the error message is somewhat misleading, but the gist is that X_train is a list, not a numpy array. You cannot use array indexing on it. Make it an array first:

out_images = np.array(X_train)[indices.astype(int)]

What is an undefined reference/unresolved external symbol error and how do I fix it?

Visual Studio NuGet package needs to be updated for new toolset version

I just had this problem trying to link libpng with Visual Studio 2013. The problem is that the package file only had libraries for Visual Studio 2010 and 2012.

The correct solution is to hope the developer releases an updated package and then upgrade, but it worked for me by hacking in an extra setting for VS2013, pointing at the VS2012 library files.

I edited the package (in the packages folder inside the solution's directory) by finding packagename\build\native\packagename.targets and inside that file, copying all the v110 sections. I changed the v110 to v120 in the condition fields only being very careful to leave the filename paths all as v110. This simply allowed Visual Studio 2013 to link to the libraries for 2012, and in this case, it worked.

Can we instantiate an abstract class?

Just observations you could make:

  1. Why poly extends my? This is useless...
  2. What is the result of the compilation? Three files: my.class, poly.class and poly$1.class
  3. If we can instantiate an abstract class like that, we can instantiate an interface too... weird...


Can we instantiate an abstract class?

No, we can't. What we can do is, create an anonymous class (that's the third file) and instantiate it.


What about a super class instantiation?

The abstract super class is not instantiated by us but by java.

EDIT: Ask him to test this

public static final void main(final String[] args) {
    final my m1 = new my() {
    };
    final my m2 = new my() {
    };
    System.out.println(m1 == m2);

    System.out.println(m1.getClass().toString());
    System.out.println(m2.getClass().toString());

}

output is:

false
class my$1
class my$2

How do I rename a local Git branch?

Git version 2.9.2

If you want to change the name of the local branch you are on:

git branch -m new_name

If you want to change the name of a different branch:

git branch -m old_name new_name

If you want to change the name of a different branch to a name that already exists:

git branch -M old_name new_name_that_already_exists

Note: The last command is destructive and will rename your branch, but you will lose the old branch with that name and those commits because branch names must be unique.

List<Object> and List<?>

package com.test;

import java.util.ArrayList;
import java.util.List;

public class TEst {

    public static void main(String[] args) {

        List<Integer> ls=new ArrayList<>();
        ls.add(1);
        ls.add(2);
        List<Integer> ls1=new ArrayList<>();
        ls1.add(3);
        ls1.add(4);
        List<List<Integer>> ls2=new ArrayList<>();
        ls2.add(ls);
        ls2.add(ls1);

        List<List<List<Integer>>> ls3=new ArrayList<>();
        ls3.add(ls2);


        m1(ls3);
    }

    private static void m1(List ls3) {
        for(Object ls4:ls3)
        {
             if(ls4 instanceof List)    
             {
                m1((List)ls4);
             }else {
                 System.out.print(ls4);
             }

        }
    }

}

UILabel - auto-size label to fit text?

you can show one line output then set property Line=0 and show multiple line output then set property Line=1 and more

[self.yourLableName sizeToFit];

Pandas groupby month and year

There are different ways to do that.

  • I created the data frame to showcase the different techniques to filter your data.
df = pd.DataFrame({'Date':['01-Jun-13','03-Jun-13', '15-Aug-13', '20-Jan-14', '21-Feb-14'],

'abc':[100,-20,40,25,60],'xyz':[200,50,-5,15,80] })

  • I separated months/year/day and seperated month-year as you explained.
def getMonth(s):
  return s.split("-")[1]

def getDay(s):
  return s.split("-")[0]

def getYear(s):
  return s.split("-")[2]

def getYearMonth(s):
  return s.split("-")[1]+"-"+s.split("-")[2]
  • I created new columns: year, month, day and 'yearMonth'. In your case, you need one of both. You can group using two columns 'year','month' or using one column yearMonth
df['year']= df['Date'].apply(lambda x: getYear(x))
df['month']= df['Date'].apply(lambda x: getMonth(x))
df['day']= df['Date'].apply(lambda x: getDay(x))
df['YearMonth']= df['Date'].apply(lambda x: getYearMonth(x))

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
3  20-Jan-14   25   15   14   Jan  20    Jan-14
4  21-Feb-14   60   80   14   Feb  21    Feb-14
  • You can go through the different groups in groupby(..) items.

In this case, we are grouping by two columns:

for key,g in df.groupby(['year','month']):
    print key,g

Output:

('13', 'Jun')         Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
('13', 'Aug')         Date  abc  xyz year month day YearMonth
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
('14', 'Jan')         Date  abc  xyz year month day YearMonth
3  20-Jan-14   25   15   14   Jan  20    Jan-14
('14', 'Feb')         Date  abc  xyz year month day YearMonth

In this case, we are grouping by one column:

for key,g in df.groupby(['YearMonth']):
    print key,g

Output:

Jun-13         Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
Aug-13         Date  abc  xyz year month day YearMonth
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
Jan-14         Date  abc  xyz year month day YearMonth
3  20-Jan-14   25   15   14   Jan  20    Jan-14
Feb-14         Date  abc  xyz year month day YearMonth
4  21-Feb-14   60   80   14   Feb  21    Feb-14
  • In case you wanna access to specific item, you can use get_group

print df.groupby(['YearMonth']).get_group('Jun-13')

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
  • Similar to get_group. This hack would help to filter values and get the grouped values.

This also would give the same result.

print df[df['YearMonth']=='Jun-13'] 

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13

You can select list of abc or xyz values during Jun-13

print df[df['YearMonth']=='Jun-13'].abc.values
print df[df['YearMonth']=='Jun-13'].xyz.values

Output:

[100 -20]  #abc values
[200  50]  #xyz values

You can use this to go through the dates that you have classified as "year-month" and apply cretiria on it to get related data.

for x in set(df.YearMonth): 
    print df[df['YearMonth']==x].abc.values
    print df[df['YearMonth']==x].xyz.values

I recommend also to check this answer as well.

Swift do-try-catch syntax

Create enum like this:

//Error Handling in swift
enum spendingError : Error{
case minus
case limit
}

Create method like:

 func calculateSpending(morningSpending:Double,eveningSpending:Double) throws ->Double{
if morningSpending < 0 || eveningSpending < 0{
    throw spendingError.minus
}
if (morningSpending + eveningSpending) > 100{
    throw spendingError.limit
}
return morningSpending + eveningSpending
}

Now check error is there or not and handle it:

do{
try calculateSpending(morningSpending: 60, eveningSpending: 50)
} catch spendingError.minus{
print("This is not possible...")
} catch spendingError.limit{
print("Limit reached...")
}

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

document.getElementsByClassName returns a NodeList, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()

or if you want plain JS try :

function toggle_by_class(cls, on) {
    var lst = document.getElementsByClassName(cls);
    for(var i = 0; i < lst.length; ++i) {
        lst[i].style.display = on ? '' : 'none';
    }
}

How to extract the hostname portion of a URL in JavaScript

Check this:

alert(window.location.hostname);

this will return host name as www.domain.com

and:

window.location.host

will return domain name with port like www.example.com:80

For complete reference check Mozilla developer site.

Find length of 2D array Python

In addition, correct way to count total item number would be:

sum(len(x) for x in input)

Java - escape string to prevent SQL injection

After searching an testing alot of solution for prevent sqlmap from sql injection, in case of legacy system which cant apply prepared statments every where.

java-security-cross-site-scripting-xss-and-sql-injection topic WAS THE SOLUTION

i tried @Richard s solution but did not work in my case. i used a filter

The goal of this filter is to wrapper the request into an own-coded wrapper MyHttpRequestWrapper which transforms:

the HTTP parameters with special characters (<, >, ‘, …) into HTML codes via the org.springframework.web.util.HtmlUtils.htmlEscape(…) method. Note: There is similar classe in Apache Commons : org.apache.commons.lang.StringEscapeUtils.escapeHtml(…) the SQL injection characters (‘, “, …) via the Apache Commons classe org.apache.commons.lang.StringEscapeUtils.escapeSql(…)

<filter>
<filter-name>RequestWrappingFilter</filter-name>
<filter-class>com.huo.filter.RequestWrappingFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>RequestWrappingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>




package com.huo.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletReponse;
import javax.servlet.http.HttpServletRequest;

public class RequestWrappingFilter implements Filter{

    public void doFilter(ServletRequest req, ServletReponse res, FilterChain chain) throws IOException, ServletException{
        chain.doFilter(new MyHttpRequestWrapper(req), res);
    }

    public void init(FilterConfig config) throws ServletException{
    }

    public void destroy() throws ServletException{
    }
}




package com.huo.filter;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang.StringEscapeUtils;

public class MyHttpRequestWrapper extends HttpServletRequestWrapper{
    private Map<String, String[]> escapedParametersValuesMap = new HashMap<String, String[]>();

    public MyHttpRequestWrapper(HttpServletRequest req){
        super(req);
    }

    @Override
    public String getParameter(String name){
        String[] escapedParameterValues = escapedParametersValuesMap.get(name);
        String escapedParameterValue = null; 
        if(escapedParameterValues!=null){
            escapedParameterValue = escapedParameterValues[0];
        }else{
            String parameterValue = super.getParameter(name);

            // HTML transformation characters
            escapedParameterValue = org.springframework.web.util.HtmlUtils.htmlEscape(parameterValue);

            // SQL injection characters
            escapedParameterValue = StringEscapeUtils.escapeSql(escapedParameterValue);

            escapedParametersValuesMap.put(name, new String[]{escapedParameterValue});
        }//end-else

        return escapedParameterValue;
    }

    @Override
    public String[] getParameterValues(String name){
        String[] escapedParameterValues = escapedParametersValuesMap.get(name);
        if(escapedParameterValues==null){
            String[] parametersValues = super.getParameterValues(name);
            escapedParameterValue = new String[parametersValues.length];

            // 
            for(int i=0; i<parametersValues.length; i++){
                String parameterValue = parametersValues[i];
                String escapedParameterValue = parameterValue;

                // HTML transformation characters
                escapedParameterValue = org.springframework.web.util.HtmlUtils.htmlEscape(parameterValue);

                // SQL injection characters
                escapedParameterValue = StringEscapeUtils.escapeSql(escapedParameterValue);

                escapedParameterValues[i] = escapedParameterValue;
            }//end-for

            escapedParametersValuesMap.put(name, escapedParameterValues);
        }//end-else

        return escapedParameterValues;
    }
}

Xcode couldn't find any provisioning profiles matching

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

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

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

Thanks for help.

React-Router open Link in new tab

The simples way is to use 'to' property:

<Link to="chart" target="_blank" to="http://link2external.page.com" >Test</Link>

How to set the image from drawable dynamically in android?

getDrawable() is deprecated. now you can use

imageView.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.msg_status_client_read)) 

How do I prompt for Yes/No/Cancel input in a Linux shell script?

You can use the default REPLY on a read, convert to lowercase and compare to a set of variables with an expression.
The script also supports ja/si/oui

read -rp "Do you want a demo? [y/n/c] "

[[ ${REPLY,,} =~ ^(c|cancel)$ ]] && { echo "Selected Cancel"; exit 1; }

if [[ ${REPLY,,} =~ ^(y|yes|j|ja|s|si|o|oui)$ ]]; then
   echo "Positive"
fi

What is the best project structure for a Python application?

In my experience, it's just a matter of iteration. Put your data and code wherever you think they go. Chances are, you'll be wrong anyway. But once you get a better idea of exactly how things are going to shape up, you're in a much better position to make these kinds of guesses.

As far as extension sources, we have a Code directory under trunk that contains a directory for python and a directory for various other languages. Personally, I'm more inclined to try putting any extension code into its own repository next time around.

With that said, I go back to my initial point: don't make too big a deal out of it. Put it somewhere that seems to work for you. If you find something that doesn't work, it can (and should) be changed.

Python Write bytes to file

If you want to write bytes then you should open the file in binary mode.

f = open('/tmp/output', 'wb')

How can I download a file from a URL and save it in Rails?

I think this is the clearest way:

require 'open-uri'

File.write 'image.png', open('http://example.com/image.png').read

Send push to Android by C# using FCM (Firebase Cloud Messaging)

Here is another approach of writing Notification Service inside ASP.Net REST API.

public async Task<bool> NotifyAsync(string to, string title, string body)
{
    try
    {
        // Get the server key from FCM console
        var serverKey = string.Format("key={0}", "Your server key - use app config");

        // Get the sender id from FCM console
        var senderId = string.Format("id={0}", "Your sender id - use app config");

        var data = new
        {
            to, // Recipient device token
            notification = new { title, body }
        };

        // Using Newtonsoft.Json
        var jsonBody = JsonConvert.SerializeObject(data);

        using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/fcm/send"))
        {
            httpRequest.Headers.TryAddWithoutValidation("Authorization", serverKey);
            httpRequest.Headers.TryAddWithoutValidation("Sender", senderId);
            httpRequest.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

            using (var httpClient = new HttpClient())
            {
                var result = await httpClient.SendAsync(httpRequest);

                if (result.IsSuccessStatusCode)
                {
                    return true;
                }
                else
                {
                    // Use result.StatusCode to handle failure
                    // Your custom error handler here
                    _logger.LogError($"Error sending notification. Status Code: {result.StatusCode}");
                }
            }
        }
    }
    catch (Exception ex)
    {
        _logger.LogError($"Exception thrown in Notify Service: {ex}");
    }

    return false;
}

References:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

<button> background image

Replace button #rock With #rock

No need for additional selector scope. You're using an id which is as specific as you can be.

JsBin example: http://jsbin.com/idobar/1/edit

How can I set the request header for curl?

To pass multiple headers in a curl request you simply add additional -H or --header to your curl command.

Example

//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL

//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json'  https://www.example.com

Going Further

For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:

  • -A (or --user-agent): set "User-Agent" field.
  • -b (or --cookie): set "Cookie" field.
  • -e (or --referer): set "Referer" field.
  • -H (or --header): set "Header" field

For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.

    $ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
    $ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com

Instantiate and Present a viewController in Swift

I know it's an old thread, but I think the current solution (using hardcoded string identifier for given view controller) is very prone to errors.

I've created a build time script (which you can access here), which will create a compiler safe way for accessing and instantiating view controllers from all storyboard within the given project.

For example, view controller named vc1 in Main.storyboard will be instantiated like so:

let vc: UIViewController = R.storyboard.Main.vc1^  // where the '^' character initialize the controller

How to parse a month name (string) to an integer for comparison in C#?

DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month

Although, for your purposes, you'll probably be better off just creating a Dictionary<string, int> mapping the month's name to its value.

How to return value from an asynchronous callback function?

It makes no sense to return values from a callback. Instead, do the "foo()" work you want to do inside your callback.

Asynchronous callbacks are invoked by the browser or by some framework like the Google geocoding library when events happen. There's no place for returned values to go. A callback function can return a value, in other words, but the code that calls the function won't pay attention to the return value.

Is it possible to open developer tools console in Chrome on Android phone?

Please do yourself a favor and just hit the easy button:

download Web Inspector (Open Source) from the Play store.

A CAVEAT: ATTOW, console output does not accept rest params! I.e. if you have something like this:

console.log('one', 'two', 'three');

you will only see

one

logged to the console. You'll need to manually wrap the params in an Array and join, like so:

console.log([ 'one', 'two', 'three' ].join(' '));

to see the expected output.

But the app is open source! A patch may be imminent! The patcher could even be you!

How to Publish Web with msbuild?

Using the deployment profiles introduced in VS 2012, you can publish with the following command line:

msbuild MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=<profile-name> /p:Password=<insert-password> /p:VisualStudioVersion=11.0

For more information on the parameters see this.

The values for the /p:VisualStudioVersion parameter depend on your version of Visual Studio. Wikipedia has a table of Visual Studio releases and their versions.

Delete specified file from document directory

You can double protect your file removal with NSFileManager.defaultManager().isDeletableFileAtPath(PathName) As of now you MUST use do{}catch{} as the old error methods no longer work. isDeletableFileAtPath() is not a "throws" (i.e. "public func removeItemAtPath(path: String) throws") so it does not need the do...catch

let killFile = NSFileManager.defaultManager()

            if (killFile.isDeletableFileAtPath(PathName)){


                do {
                  try killFile.removeItemAtPath(arrayDictionaryFilePath)
                }
                catch let error as NSError {
                    error.description
                }
            }

Creating a LINQ select from multiple tables

You must create a new anonymous type:

 select new { op, pg }

Refer to the official guide.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

Add a build task to concatenate and register your html partials in the Angular $templateCache. (This answer is a more detailed variant of karlgold's answer.)

For grunt, use grunt-angular-templates. For gulp, use gulp-angular-templatecache.

Below are config/code snippets to illustrate.

gruntfile.js Example:

ngtemplates: {
  app: {                
    src: ['app/partials/**.html', 'app/views/**.html'],
    dest: 'app/scripts/templates.js'
  },
  options: {
    module: 'myModule'
  }
}

gulpfile.js Example:

var templateCache = require('gulp-angular-templatecache');
var paths = ['app/partials/.html', 'app/views/.html'];

gulp.task('createTemplateCache', function () {
return gulp.src(paths)
    .pipe(templateCache('templates.js', { module: 'myModule', root:'app/views'}))
    .pipe(gulp.dest('app/scripts'));
    });

templates.js (this file is autogenerated by the build task)

$templateCache.put('app/views/main.html', "<div class=\"main\">\r"...

index.html

<script src="app/scripts/templates.js"></script>
<div ng-include ng-controller="main as vm" src="'app/views/main.html'"></div>

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

If statement in select (ORACLE)

use the variable, Oracle does not support SQL in that context without an INTO. With a properly named variable your code will be more legible anyway.

Git: How to pull a single file from a server repository in Git?

This scenario comes up when you -- or forces greater than you -- have mangled a file in your local repo and you just want to restore a fresh copy of the latest version of it from the repo. Simply deleting the file with /bin/rm (not git rm) or renaming/hiding it and then issuing a git pull will not work: git notices the file's absence and assumes you probably want it gone from the repo (git diff will show all lines deleted from the missing file).

git pull not restoring locally missing files has always frustrated me about git, perhaps since I have been influenced by other version control systems (e.g. svn update which I believe will restore files that have been locally hidden).

git reset --hard HEAD is an alternative way to restore the file of interest as it throws away any uncommitted changes you have. However, as noted here, git reset is is a potentially dangerous command if you have any other uncommitted changes that you care about.

The git fetch ... git checkout strategy noted above by @chrismillah is a nice surgical way to restore the file in question.

Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

short answer - add following line in the jsp which will define the base
base href="/{root of your application}/"

How can I kill a process by name instead of PID?

awk oneliner, which parses the header of ps output, so you don't need to care about column numbers (but column names). Support regex. For example, to kill all processes, which executable name (without path) contains word "firefox" try

ps -fe | awk 'NR==1{for (i=1; i<=NF; i++) {if ($i=="COMMAND") Ncmd=i; else if ($i=="PID") Npid=i} if (!Ncmd || !Npid) {print "wrong or no header" > "/dev/stderr"; exit} }$Ncmd~"/"name"$"{print "killing "$Ncmd" with PID " $Npid; system("kill "$Npid)}' name=.*firefox.*

What is the difference between java and core java?

There are two categories as follows

  1. Core Java
  2. Java EE

Core java is a language basics. For example (Data structures, Semantics..etc) https://malalanayake.wordpress.com/category/java/data-structures/

But if you see the Java EE you can see the Sevlet, JSP, JSF all the web technologies and the patterns. https://malalanayake.wordpress.com/2014/10/10/jsp-servlet-scope-variables-and-init-parameters/

PHP How to fix Notice: Undefined variable:

Define the variables at the beginning of the function so if there are no records, the variables exist and you won't get the error. Check for null values in the returned array.

$hn = null;
$pid = null;
$datereg = null;
$prefix = null;
$fname = null;
$lname = null;
$age = null;
$sex = null;

Get the cartesian product of a series of lists?

Here is a recursive generator, which doesn't store any temporary lists

def product(ar_list):
    if not ar_list:
        yield ()
    else:
        for a in ar_list[0]:
            for prod in product(ar_list[1:]):
                yield (a,)+prod

print list(product([[1,2],[3,4],[5,6]]))

Output:

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

How can I run PowerShell with the .NET 4 runtime?

If you don't want to modify the registry or app.config files, an alternate way is to create a simple .NET 4 console app that mimicks what PowerShell.exe does and hosts the PowerShell ConsoleShell.

See Option 2 – Hosting Windows PowerShell yourself

First, add a reference to the System.Management.Automation and Microsoft.PowerShell.ConsoleHost assemblies which can be found under %programfiles%\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0

Then use the following code:

using System;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;

namespace PSHostCLRv4
{
    class Program
    {
        static int Main(string[] args)
        {
            var config = RunspaceConfiguration.Create();
                return ConsoleShell.Start(
                config,
                "Windows PowerShell - Hosted on CLR v4\nCopyright (C) 2010 Microsoft Corporation. All rights reserved.",
                "",
                args
            );
        }
    }
}

file_put_contents(meta/services.json): failed to open stream: Permission denied

  1. First, delete the storage folder then again create the storage folder.
  2. Inside storage folder create a new folder name as framework.
  3. Inside framework folder create three folders name as cache, sessions and views.

I have solved my problem by doing this.

How can I get list of values from dict?

Follow the below example --

songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]

print("====================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')

playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')

# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

Methods for Aligning Flex Items along the Main Axis

As stated in the question:

To align flex items along the main axis there is one property: justify-content

To align flex items along the cross axis there are three properties: align-content, align-items and align-self.

The question then asks:

Why are there no justify-items and justify-self properties?

One answer may be: Because they're not necessary.

The flexbox specification provides two methods for aligning flex items along the main axis:

  1. The justify-content keyword property, and
  2. auto margins

justify-content

The justify-content property aligns flex items along the main axis of the flex container.

It is applied to the flex container but only affects flex items.

There are five alignment options:

  • flex-start ~ Flex items are packed toward the start of the line.

    enter image description here

  • flex-end ~ Flex items are packed toward the end of the line.

    enter image description here

  • center ~ Flex items are packed toward the center of the line.

    enter image description here

  • space-between ~ Flex items are evenly spaced, with the first item aligned to one edge of the container and the last item aligned to the opposite edge. The edges used by the first and last items depends on flex-direction and writing mode (ltr or rtl).

    enter image description here

  • space-around ~ Same as space-between except with half-size spaces on both ends.

    enter image description here


Auto Margins

With auto margins, flex items can be centered, spaced away or packed into sub-groups.

Unlike justify-content, which is applied to the flex container, auto margins go on flex items.

They work by consuming all free space in the specified direction.


Align group of flex items to the right, but first item to the left

Scenario from the question:

  • making a group of flex items align-right (justify-content: flex-end) but have the first item align left (justify-self: flex-start)

    Consider a header section with a group of nav items and a logo. With justify-self the logo could be aligned left while the nav items stay far right, and the whole thing adjusts smoothly ("flexes") to different screen sizes.

enter image description here

enter image description here


Other useful scenarios:

enter image description here

enter image description here

enter image description here


Place a flex item in the corner

Scenario from the question:

  • placing a flex item in a corner .box { align-self: flex-end; justify-self: flex-end; }

enter image description here


Center a flex item vertically and horizontally

enter image description here

margin: auto is an alternative to justify-content: center and align-items: center.

Instead of this code on the flex container:

.container {
    justify-content: center;
    align-items: center;
}

You can use this on the flex item:

.box56 {
    margin: auto;
}

This alternative is useful when centering a flex item that overflows the container.


Center a flex item, and center a second flex item between the first and the edge

A flex container aligns flex items by distributing free space.

Hence, in order to create equal balance, so that a middle item can be centered in the container with a single item alongside, a counterbalance must be introduced.

In the examples below, invisible third flex items (boxes 61 & 68) are introduced to balance out the "real" items (box 63 & 66).

enter image description here

enter image description here

Of course, this method is nothing great in terms of semantics.

Alternatively, you can use a pseudo-element instead of an actual DOM element. Or you can use absolute positioning. All three methods are covered here: Center and bottom-align flex items

NOTE: The examples above will only work – in terms of true centering – when the outermost items are equal height/width. When flex items are different lengths, see next example.


Center a flex item when adjacent items vary in size

Scenario from the question:

  • in a row of three flex items, affix the middle item to the center of the container (justify-content: center) and align the adjacent items to the container edges (justify-self: flex-start and justify-self: flex-end).

    Note that values space-around and space-between on justify-content property will not keep the middle item centered in relation to the container if the adjacent items have different widths (see demo).

As noted, unless all flex items are of equal width or height (depending on flex-direction), the middle item cannot be truly centered. This problem makes a strong case for a justify-self property (designed to handle the task, of course).

_x000D_
_x000D_
#container {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  background-color: lightyellow;_x000D_
}_x000D_
.box {_x000D_
  height: 50px;_x000D_
  width: 75px;_x000D_
  background-color: springgreen;_x000D_
}_x000D_
.box1 {_x000D_
  width: 100px;_x000D_
}_x000D_
.box3 {_x000D_
  width: 200px;_x000D_
}_x000D_
#center {_x000D_
  text-align: center;_x000D_
  margin-bottom: 5px;_x000D_
}_x000D_
#center > span {_x000D_
  background-color: aqua;_x000D_
  padding: 2px;_x000D_
}
_x000D_
<div id="center">_x000D_
  <span>TRUE CENTER</span>_x000D_
</div>_x000D_
_x000D_
<div id="container">_x000D_
  <div class="box box1"></div>_x000D_
  <div class="box box2"></div>_x000D_
  <div class="box box3"></div>_x000D_
</div>_x000D_
_x000D_
<p>The middle box will be truly centered only if adjacent boxes are equal width.</p>
_x000D_
_x000D_
_x000D_

Here are two methods for solving this problem:

Solution #1: Absolute Positioning

The flexbox spec allows for absolute positioning of flex items. This allows for the middle item to be perfectly centered regardless of the size of its siblings.

Just keep in mind that, like all absolutely positioned elements, the items are removed from the document flow. This means they don't take up space in the container and can overlap their siblings.

In the examples below, the middle item is centered with absolute positioning and the outer items remain in-flow. But the same layout can be achieved in reverse fashion: Center the middle item with justify-content: center and absolutely position the outer items.

enter image description here

Solution #2: Nested Flex Containers (no absolute positioning)

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
}_x000D_
.box {_x000D_
  flex: 1;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}_x000D_
.box71 > span { margin-right: auto; }_x000D_
.box73 > span { margin-left: auto;  }_x000D_
_x000D_
/* non-essential */_x000D_
.box {_x000D_
  align-items: center;_x000D_
  border: 1px solid #ccc;_x000D_
  background-color: lightgreen;_x000D_
  height: 40px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box box71"><span>71 short</span></div>_x000D_
  <div class="box box72"><span>72 centered</span></div>_x000D_
  <div class="box box73"><span>73 loooooooooooooooong</span></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's how it works:

  • The top-level div (.container) is a flex container.
  • Each child div (.box) is now a flex item.
  • Each .box item is given flex: 1 in order to distribute container space equally.
  • Now the items are consuming all space in the row and are equal width.
  • Make each item a (nested) flex container and add justify-content: center.
  • Now each span element is a centered flex item.
  • Use flex auto margins to shift the outer spans left and right.

You could also forgo justify-content and use auto margins exclusively.

But justify-content can work here because auto margins always have priority. From the spec:

8.1. Aligning with auto margins

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.


justify-content: space-same (concept)

Going back to justify-content for a minute, here's an idea for one more option.

  • space-same ~ A hybrid of space-between and space-around. Flex items are evenly spaced (like space-between), except instead of half-size spaces on both ends (like space-around), there are full-size spaces on both ends.

This layout can be achieved with ::before and ::after pseudo-elements on the flex container.

enter image description here

(credit: @oriol for the code, and @crl for the label)

UPDATE: Browsers have begun implementing space-evenly, which accomplishes the above. See this post for details: Equal space between flex items


PLAYGROUND (includes code for all examples above)

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

I had same problem and this accepted solution didn't helped me, if someone has same problem you can use my code snippet:

// example of filtering and sharing multiple images with texts
// remove facebook from sharing intents
private void shareFilter(){

    String share = getShareTexts();
    ArrayList<Uri> uris = getImageUris();

    List<Intent> targets = new ArrayList<>();
    Intent template = new Intent(Intent.ACTION_SEND_MULTIPLE);
    template.setType("image/*");
    List<ResolveInfo> candidates = getActivity().getPackageManager().
            queryIntentActivities(template, 0);

    // remove facebook which has a broken share intent
    for (ResolveInfo candidate : candidates) {
        String packageName = candidate.activityInfo.packageName;
        if (!packageName.equals("com.facebook.katana")) {
            Intent target = new Intent(Intent.ACTION_SEND_MULTIPLE);
            target.setType("image/*");
            target.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
            target.putExtra(Intent.EXTRA_TEXT, share);
            target.setPackage(packageName);
            targets.add(target);
        }
    }
    Intent chooser = Intent.createChooser(targets.remove(0), "Share Via");
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, targets.toArray(new Parcelable[targets.size()]));
    startActivity(chooser);

}

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

In Git, what is the difference between origin/master vs origin master?

origin/master is the remote master branch

Usually after doing a git fetch origin to bring all the changes from the server, you would do a git rebase origin/master, to rebase your changes and move the branch to the latest index. Here, origin/master is referring to the remote branch, because you are basically telling GIT to rebase the origin/master branch onto the current branch.

You would use origin master when pushing, for example. git push origin master is simply telling GIT to push to the remote repository the local master branch.

What are the retransmission rules for TCP?

What exactly are the rules for requesting retransmission of lost data?

The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.

Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ

are detailed in the RFC 3366.

At what time frequency are the retransmission requests performed?

The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)

The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.

Is there an upper bound on the number?

Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.

Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?

The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)

Circular gradient in android

You can get a circular gradient using android:type="radial":

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:type="radial" android:gradientRadius="250dp"
        android:startColor="#E9E9E9" android:endColor="#D4D4D4" />
</shape>

A cron job for rails: best practices?

Use Craken (rake centric cron jobs)

When to use MongoDB or other document oriented database systems?

The 2 main reason why you might want to prefer Mongo are

  • Flexibility in schema design (JSON type document store).
  • Scalability - Just add up nodes and it can scale horizontally quite well.

It is suitable for big data applications. RDBMS is not good for big data.

How to copy a file along with directory structure/path using python?

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

Nullable types: better way to check for null or zero in c#

One step further from Joshua Shannon's nice answer. Now with preventing boxing/unboxing:

public static class NullableEx
{
    public static bool IsNullOrDefault<T>(this T? value)
        where T : struct
    {
        return EqualityComparer<T>.Default.Equals(value.GetValueOrDefault(), default(T));
    }
}

Determine whether an array contains a value

It's almost always safer to use a library like lodash simply because of all the issues with cross-browser compatibilities and efficiency.

Efficiency because you can be guaranteed that at any given time, a hugely popular library like underscore will have the most efficient method of accomplishing a utility function like this.

_.includes([1, 2, 3], 3); // returns true

If you're concerned about the bulk that's being added to your application by including the whole library, know that you can include functionality separately:

var includes = require('lodash/collections/includes');

NOTICE: With older versions of lodash, this was _.contains() rather than _.includes().

Can I embed a .png image into an html page?

Quick google search says you can embed it like this:

<img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
/ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" 
width="16" height="14" alt="embedded folder icon">

But you need a different implementation in Internet Explorer.

http://www.websiteoptimization.com/speed/tweak/inline-images/

How to read text files with ANSI encoding and non-English letters?

If I remember correctly the XmlDocument.Load(string) method always assumes UTF-8, regardless of the XML encoding. You would have to create a StreamReader with the correct encoding and use that as the parameter.

xmlDoc.Load(new StreamReader(
                     File.Open("file.xml"), 
                     Encoding.GetEncoding("iso-8859-15"))); 

I just stumbled across KB308061 from Microsoft. There's an interesting passage: Specify the encoding declaration in the XML declaration section of the XML document. For example, the following declaration indicates that the document is in UTF-16 Unicode encoding format:

<?xml version="1.0" encoding="UTF-16"?>

Note that this declaration only specifies the encoding format of an XML document and does not modify or control the actual encoding format of the data.

Link Source:

XmlDocument.Load() method fails to decode € (euro)

Load an image from a url into a PictureBox

Here's the solution I use. I can't remember why I couldn't just use the PictureBox.Load methods. I'm pretty sure it's because I wanted to properly scale & center the downloaded image into the PictureBox control. If I recall, all the scaling options on PictureBox either stretch the image, or will resize the PictureBox to fit the image. I wanted a properly scaled and centered image in the size I set for PictureBox.

Now, I just need to make a async version...

Here's my methods:

   #region Image Utilities

    /// <summary>
    /// Loads an image from a URL into a Bitmap object.
    /// Currently as written if there is an error during downloading of the image, no exception is thrown.
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static Bitmap LoadPicture(string url)
    {
        System.Net.HttpWebRequest wreq;
        System.Net.HttpWebResponse wresp;
        Stream mystream;
        Bitmap bmp;

        bmp = null;
        mystream = null;
        wresp = null;
        try
        {
            wreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
            wreq.AllowWriteStreamBuffering = true;

            wresp = (System.Net.HttpWebResponse)wreq.GetResponse();

            if ((mystream = wresp.GetResponseStream()) != null)
                bmp = new Bitmap(mystream);
        }
        catch
        {
            // Do nothing... 
        }
        finally
        {
            if (mystream != null)
                mystream.Close();

            if (wresp != null)
                wresp.Close();
        }

        return (bmp);
    }

    /// <summary>
    /// Takes in an image, scales it maintaining the proper aspect ratio of the image such it fits in the PictureBox's canvas size and loads the image into picture box.
    /// Has an optional param to center the image in the picture box if it's smaller then canvas size.
    /// </summary>
    /// <param name="image">The Image you want to load, see LoadPicture</param>
    /// <param name="canvas">The canvas you want the picture to load into</param>
    /// <param name="centerImage"></param>
    /// <returns></returns>

    public static Image ResizeImage(Image image, PictureBox canvas, bool centerImage ) 
    {
        if (image == null || canvas == null)
        {
            return null;
        }

        int canvasWidth = canvas.Size.Width;
        int canvasHeight = canvas.Size.Height;
        int originalWidth = image.Size.Width;
        int originalHeight = image.Size.Height;

        System.Drawing.Image thumbnail =
            new Bitmap(canvasWidth, canvasHeight); // changed parm names
        System.Drawing.Graphics graphic =
                     System.Drawing.Graphics.FromImage(thumbnail);

        graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphic.SmoothingMode = SmoothingMode.HighQuality;
        graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphic.CompositingQuality = CompositingQuality.HighQuality;

        /* ------------------ new code --------------- */

        // Figure out the ratio
        double ratioX = (double)canvasWidth / (double)originalWidth;
        double ratioY = (double)canvasHeight / (double)originalHeight;
        double ratio = ratioX < ratioY ? ratioX : ratioY; // use whichever multiplier is smaller

        // now we can get the new height and width
        int newHeight = Convert.ToInt32(originalHeight * ratio);
        int newWidth = Convert.ToInt32(originalWidth * ratio);

        // Now calculate the X,Y position of the upper-left corner 
        // (one of these will always be zero)
        int posX = Convert.ToInt32((canvasWidth - (image.Width * ratio)) / 2);
        int posY = Convert.ToInt32((canvasHeight - (image.Height * ratio)) / 2);

        if (!centerImage)
        {
            posX = 0;
            posY = 0;
        }
        graphic.Clear(Color.White); // white padding
        graphic.DrawImage(image, posX, posY, newWidth, newHeight);

        /* ------------- end new code ---------------- */

        System.Drawing.Imaging.ImageCodecInfo[] info =
                         ImageCodecInfo.GetImageEncoders();
        EncoderParameters encoderParameters;
        encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
                         100L);

        Stream s = new System.IO.MemoryStream();
        thumbnail.Save(s, info[1],
                          encoderParameters);

        return Image.FromStream(s);
    }

    #endregion

Here's the required includes. (Some might be needed by other code, but including all to be safe)

using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Drawing;

How I generally use it:

 ImageUtil.ResizeImage(ImageUtil.LoadPicture( "http://someurl/img.jpg", pictureBox1, true);

How to change the height of a <br>?

This did the trick for me when I couldn't get the style spacing to work from the span tag:

        <p style='margin-bottom: 5px' >
            <span>I Agree</span>
        </p>
        <span>I Don't Agree</span>

double free or corruption (!prev) error in c program

1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory

Here is the program with all the changes needed. I compiled and ran... no errors or warnings.

#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h>  //sine
#include <string.h>

#define TIME 255
#define HARM 32

int main (void) {
    double sineRads;
    double sine;
    int tcount = 0;
    int hcount = 0;
    /* allocate some heap memory for the large array of waveform data */
    double *ptr = malloc(sizeof(double) * TIME);
     //memset( ptr, 0x00, sizeof(double) * TIME);  may not always set double to 0
    for( tcount = 0; tcount < TIME; tcount++ )
    {
         ptr[tcount] = 0; 
    }

    tcount = 0;
    if (NULL == ptr) {
        printf("ERROR: couldn't allocate waveform memory!\n");
    } else {
        /*evaluate and add harmonic amplitudes for each time step */
        for(tcount = 0; tcount < TIME; tcount++){
            for(hcount = 0; hcount <= HARM; hcount++){
                sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
                sineRads *= (hcount + 1); //scale frequency by harmonic number
                sine = sin(sineRads); 
                ptr[tcount] += sine; //add to other results for this time step
            }
        }
        free(ptr);
        ptr = NULL;     
    }
    return 0;
}

Android translate animation - permanently move View to new position using AnimationListener

This is what worked for me perfectly:-

// slide the view from its current position to below itself
public void slideUp(final View view, final View llDomestic){

    ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY",0f);
    animation.setDuration(100);
    llDomestic.setVisibility(View.GONE);
    animation.start();

}

// slide the view from below itself to the current position
public void slideDown(View view,View llDomestic){
    llDomestic.setVisibility(View.VISIBLE);
    ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY",   0f);
    animation.setDuration(100);
    animation.start();
}

llDomestic : The view which you want to hide. view: The view which you want to move down or up.

Remove files from Git commit

git checkout HEAD~ path/to/file
git commit --amend

Override default Spring-Boot application.properties settings in Junit Test

Otherwise we may change the default property configurator name, setting the property spring.config.name=test and then having class-path resource src/test/test.properties our native instance of org.springframework.boot.SpringApplication will be auto-configured from this separated test.properties, ignoring application properties;

Benefit: auto-configuration of tests;

Drawback: exposing "spring.config.name" property at C.I. layer

ref: http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

spring.config.name=application # Config file name

Format decimal for percentage values?

This code may help you:

double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

AngularJS: How can I pass variables between controllers?

I'd like to contribute to this question by pointing out that the recommended way to share data between controllers, and even directives, is by using services (factories) as it has been already pointed out, but also I'd like to provide a working practical example of how to that should be done.

Here is the working plunker: http://plnkr.co/edit/Q1VdKJP2tpvqqJL1LF6m?p=info

First, create your service, that will have your shared data:

app.factory('SharedService', function() {
  return {
    sharedObject: {
      value: '',
      value2: ''
    }
  };
});

Then, simply inject it on your controllers and grab the shared data on your scope:

app.controller('FirstCtrl', function($scope, SharedService) {
  $scope.model = SharedService.sharedObject;
});

app.controller('SecondCtrl', function($scope, SharedService) {
  $scope.model = SharedService.sharedObject;
});

app.controller('MainCtrl', function($scope, SharedService) {
  $scope.model = SharedService.sharedObject;
});

You can also do that for your directives, it works the same way:

app.directive('myDirective',['SharedService', function(SharedService){
  return{
    restrict: 'E',
    link: function(scope){
      scope.model = SharedService.sharedObject;
    },
    template: '<div><input type="text" ng-model="model.value"/></div>'
  }
}]);

Hope this practical and clean answer can be helpful to someone.

Loading .sql files from within PHP

mysqli can run multiple queries separated by a ;

you could read in the whole file and run it all at once using mysqli_multi_query()

But, I'll be the first to say that this isn't the most elegant solution.

Regex Explanation ^.*$

"^.*$"

literally just means select everything

"^"  // anchors to the beginning of the line
".*" // zero or more of any character
"$"  // anchors to end of line

android.app.Application cannot be cast to android.app.Activity

You can also try this one.

override fun registerWith( registry: PluginRegistry) {
        GeneratedPluginRegistrant.registerWith(registry as FlutterEngine)       
    //registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")
    }

I think this one is far better solution than creating a new class.