Programs & Examples On #Database programming

How To Run PHP From Windows Command Line in WAMPServer

UPDATED After few research, best solution was to use that info another stackoverflow thread to avoid ctrl+z input and also from the scree output. So, instead of php -a you should use call "php.exe" -f NAMED_SCRIPT.php

OLD Readline not possible under Windows, so none of existent php shells written in php will work. But there's a workaround using -a interactive mode.

2 commmon problems here. You cannot see result until executes CTRL Z command to indicate the final of code/file like EOF. When you do, result in most cases is printed result and fast closed window. Anyway, you will be returned to cmd not the -a interactive mode.

Save this content into a .bat file, and define your PHP PATH into Windows variables, or modify php.exe to "full path to exe" instead:

::
:: PHP Shell launch wrapper
::
@ECHO off
call "php.exe" -a

echo.
echo.

call "PHP Shell.bat"

This is a simple Batch launching -a mode of php.exe. When it launchs php, stop script even no pause is wrote because is "into" the interactive waiting for input. When you hit CTRL Z, gets the SIGSTEP (next step) not the SIGSTOP (close, CTRL+C usually), then read the next intruction, wich is a recursive call to .bat itself. Because you're always into PHP -a mode, no exit command. You must use CTRL+C or hit the exit cross with mouse. (No alt+f4)

You can also use "Bat to Exe" converter to easy use.

How do I programmatically determine operating system in Java?

String osName = System.getProperty("os.name");
System.out.println("Operating system " + osName);

Cannot checkout, file is unmerged

i resolved by doing below 2 easy steps :

step 1: git reset Head step 2: git add .

How to check for a Null value in VB.NET

 If Short.TryParse(editTransactionRow.pay_id, New Short) Then editTransactionRow.pay_id.ToString()

Whitespaces in java

For a non-regular expression approach, you can check Character.isWhitespace for each character.

boolean containsWhitespace(String s) {
    for (int i = 0; i < s.length(); ++i) {
        if (Character.isWhitespace(s.charAt(i)) {
            return true;
        }
    }
    return false;
}

Which are the white spaces in Java?

The documentation specifies what Java considers to be whitespace:

public static boolean isWhitespace(char ch)

Determines if the specified character is white space according to Java. A character is a Java whitespace character if and only if it satisfies one of the following criteria:

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
  • It is '\u0009', HORIZONTAL TABULATION.
  • It is '\u000A', LINE FEED.
  • It is '\u000B', VERTICAL TABULATION.
  • It is '\u000C', FORM FEED.
  • It is '\u000D', CARRIAGE RETURN.
  • It is '\u001C', FILE SEPARATOR.
  • It is '\u001D', GROUP SEPARATOR.
  • It is '\u001E', RECORD SEPARATOR.
  • It is '\u001F', UNIT SEPARATOR.

How can I do an asc and desc sort using underscore.js?

The Array prototype's reverse method modifies the array and returns a reference to it, which means you can do this:

var sortedAsc = _.sortBy(collection, 'propertyName');
var sortedDesc = _.sortBy(collection, 'propertyName').reverse();

Also, the underscore documentation reads:

In addition, the Array prototype's methods are proxied through the chained Underscore object, so you can slip a reverse or a push into your chain, and continue to modify the array.

which means you can also use .reverse() while chaining:

var sortedDescAndFiltered = _.chain(collection)
    .sortBy('propertyName')
    .reverse()
    .filter(_.property('isGood'))
    .value();

How can I use regex to get all the characters after a specific character, e.g. comma (",")

Another idea is to do myVar.split(',')[1];

For simple case, not using a regexp is a good idea...

Selenium and xpath: finding a div with a class/id and verifying text inside

For class and text xpath-

//div[contains(@class,'Caption') and (text(),'Model saved')]

and

For class and id xpath-

//div[contains(@class,'gwt-HTML') and @id="alertLabel"]

Are there benefits of passing by pointer over passing by reference in C++?

Allen Holub's "Enough Rope to Shoot Yourself in the Foot" lists the following 2 rules:

120. Reference arguments should always be `const`
121. Never use references as outputs, use pointers

He lists several reasons why references were added to C++:

  • they are necessary to define copy constructors
  • they are necessary for operator overloads
  • const references allow you to have pass-by-value semantics while avoiding a copy

His main point is that references should not be used as 'output' parameters because at the call site there's no indication of whether the parameter is a reference or a value parameter. So his rule is to only use const references as arguments.

Personally, I think this is a good rule of thumb as it makes it more clear when a parameter is an output parameter or not. However, while I personally agree with this in general, I do allow myself to be swayed by the opinions of others on my team if they argue for output parameters as references (some developers like them immensely).

How to decrypt hash stored by bcrypt

You simply can't.

bcrypt uses salting, of different rounds, I use 10 usually.

bcrypt.hash(req.body.password,10,function(error,response){ }

This 10 is salting random string into your password.

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

In an instance where you want to set a placeholder and not have a default value be selected, you can use this option.

      <select defaultValue={'DEFAULT'} >
        <option value="DEFAULT" disabled>Choose a salutation ...</option>
        <option value="1">Mr</option>
        <option value="2">Mrs</option>
        <option value="3">Ms</option>
        <option value="4">Miss</option>
        <option value="5">Dr</option>
      </select>

Here the user is forced to pick an option!

EDIT

If this is a controlled component

In this case unfortunately you will have to use both defaultValue and value violating React a bit. This is because react by semantics does not allow setting a disabled value as active.

 function TheSelectComponent(props){
     let currentValue = props.curentValue || "DEFAULT";
     return(
      <select value={currentValue} defaultValue={'DEFAULT'} onChange={props.onChange}>
        <option value="DEFAULT" disabled>Choose a salutation ...</option>
        <option value="1">Mr</option>
        <option value="2">Mrs</option>
        <option value="3">Ms</option>
        <option value="4">Miss</option>
        <option value="5">Dr</option>
      </select>
    )
}

How to specify font attributes for all elements on an html web page?

If you specify CSS attributes for your body element it should apply to anything within <body></body> so long as you don't override them later in the stylesheet.

Passing a dictionary to a function as keyword parameters

Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary

So my example becomes:

d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(**d)

How to loop through files matching wildcard in batch file

Assuming you have two programs that process the two files, process_in.exe and process_out.exe:

for %%f in (*.in) do (
    echo %%~nf
    process_in "%%~nf.in"
    process_out "%%~nf.out"
)

%%~nf is a substitution modifier, that expands %f to a file name only. See other modifiers in https://technet.microsoft.com/en-us/library/bb490909.aspx (midway down the page) or just in the next answer.

matplotlib savefig in jpeg format

Matplotlib can handle directly and transparently jpg if you have installed PIL. You don't need to call it, it will do it by itself. If Python cannot find PIL, it will raise an error.

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Many people set their cookie path to /. That will cause every favicon request to send a copy of the sites cookies, at least in chrome. Addressing your favicon to your cookieless domain should correct this.

<link rel="icon" href="https://cookieless.MySite.com/favicon.ico" type="image/x-icon" />

Depending on how much traffic you get, this may be the most practical reason for adding the link.

Info on setting up a cookieless domain:

http://www.ravelrumba.com/blog/static-cookieless-domain/

Open file by its full path in C++

For those who are getting the path dynamicly... e.g. drag&drop:

Some main constructions get drag&dropped file with double quotes like:

"C:\MyPath\MyFile.txt"

Quick and nice solution is to use this function to remove chars from string:

void removeCharsFromString( string &str, char* charsToRemove ) {
   for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
      str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
   }
} 

string myAbsolutepath; //fill with your absolute path
removeCharsFromString( myAbsolutepath, "\"" );

myAbsolutepath now contains just C:\MyPath\MyFile.txt

The function needs these libraries: <iostream> <algorithm> <cstring>.
The function was based on this answer.

Working Fiddle: http://ideone.com/XOROjq

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Starting from Framework v4.5 you can use Activator.CreateInstanceFrom() to easily instantiate classes within assemblies. The following example shows how to use it and how to call a method passing parameters and getting return value.

    // Assuming moduleFileName contains full or valid relative path to assembly    
    var moduleInstance = Activator.CreateInstanceFrom(moduleFileName, "MyNamespace.MyClass");
    MethodInfo mi = moduleInstance.Unwrap().GetType().GetMethod("MyMethod");
    // Assuming the method returns a boolean and accepts a single string parameter
    bool rc = Convert.ToBoolean(mi.Invoke(moduleInstance.Unwrap(), new object[] { "MyParamValue" } ));

Using a cursor with dynamic SQL in a stored procedure

Another option in SQL Server is to do all of your dynamic querying into table variable in a stored proc, then use a cursor to query and process that. As to the dreaded cursor debate :), I have seen studies that show that in some situations, a cursor can actually be faster if properly set up. I use them myself when the required query is too complex, or just not humanly (for me ;) ) possible.

Sourcetree - undo unpushed commits

If you select the log entry to which you want to revert to then you can click on "Reset to this commit". Only use this option if you didn't push the reverse commit changes. If you're worried about losing the changes then you can use the soft mode which will leave a set of uncommitted changes (what you just changed). Using the mixed resets the working copy but keeps those changes, and a hard will just get rid of the changes entirely. Here's some screenshots:

enter image description here

How to alter a column and change the default value?

For DEFAULT CURRENT_TIMESTAMP:

ALTER TABLE tablename
 CHANGE COLUMN columnname1 columname1 DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
 CHANGE COLUMN columnname2 columname2 DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

Please note double columnname declaration

Removing DEFAULT CURRENT_TIMESTAMP:

ALTER TABLE tablename
 ALTER COLUMN columnname1 DROP DEFAULT,
 ALTER COLUMN columnname2 DROPT DEFAULT;

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

Infact this worked for me

 SELECT * 
 FROM myTable
 WHERE CAST(ReadDate AS DATETIME) + ReadTime BETWEEN '2010-09-16 5:00PM' AND '2010-09-21 9:00AM'

Calculating time difference between 2 dates in minutes

I am using below code for today and database date.

TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20

According to the documentation, the first argument can be any of the following:

MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR

Groovy - Convert object to JSON string

You can use JsonBuilder for that.

Example Code:

import groovy.json.JsonBuilder

class Person {
    String name
    String address
}

def o = new Person( name: 'John Doe', address: 'Texas' )

println new JsonBuilder( o ).toPrettyString()

How to add items into a numpy array

Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python list will. You'll find that every "append" action requires re-allocation of the array memory and short-term doubling of memory requirements. So, the more general solution to the problem is to try to allocate arrays to be as large as the final output of your algorithm. Then perform all your operations on sub-sets (slices) of that array. Array creation and destruction should ideally be minimized.

That said, It's often unavoidable and the functions that do this are:

for 2-D arrays:

for 3-D arrays (the above plus):

for N-D arrays:

How can I use interface as a C# generic type constraint?

Solution A: This combination of constraints should guarantee that TInterface is an interface:

class example<TInterface, TStruct>
    where TStruct : struct, TInterface
    where TInterface : class
{ }

It requires a single struct TStruct as a Witness to proof that TInterface is a struct.

You can use single struct as a witness for all your non-generic types:

struct InterfaceWitness : IA, IB, IC 
{
    public int DoA() => throw new InvalidOperationException();
    //...
}

Solution B: If you don't want to make structs as witnesses you can create an interface

interface ISInterface<T>
    where T : ISInterface<T>
{ }

and use a constraint:

class example<TInterface>
    where TInterface : ISInterface<TInterface>
{ }

Implementation for interfaces:

interface IA :ISInterface<IA>{ }

This solves some of the problems, but requires trust that noone implements ISInterface<T> for non-interface types, but that is pretty hard to do accidentally.

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.

More details here.

How do I call a dynamically-named method in Javascript?

Here is a working and simple solution for checking existence of a function and triaging that function dynamically by another function;

Trigger function

function runDynmicFunction(functionname){ 

    if (typeof window[functionname] == "function"  ) { //check availability

        window[functionname]("this is from the function it "); //run function and pass a parameter to it
    }
}

and you can now generate the function dynamically maybe using php like this

function runThis_func(my_Parameter){

    alert(my_Parameter +" triggerd");
}

now you can call the function using dynamically generated event

<?php

$name_frm_somware ="runThis_func";

echo "<input type='button' value='Button' onclick='runDynmicFunction(\"".$name_frm_somware."\");'>";

?>

the exact HTML code you need is

<input type="button" value="Button" onclick="runDynmicFunction('runThis_func');">

Split output of command by columns using Bash?

Bash's set will parse all output into position parameters.

For instance, with set $(free -h) command, echo $7 will show "Mem:"

Filter items which array contains any of given values

You should use Terms Query

{
    "query" : {
        "terms" : {
            "tags" : ["c", "d"]
        }
    }
}

AngularJS Error: $injector:unpr Unknown Provider

I was getting this problem and it turned out I had included my controller both in ui.router and in the html template as in

.config(['$stateProvider',
  function($stateProvider) {
    $stateProvider.state('dashboard', {
      url: '/dashboard',
      templateUrl: 'dashboard/views/index.html',
      controller: 'DashboardController'
    });
  }
]);

and

<section data-ng-controller="DashboardController">

2D cross-platform game engine for Android and iOS?

Here is just a reply from Richard Pickup on LinkedIn to a similar question of mine:

I've used cocos 2dx marmalade and unity on both iOS and android. For 2d games cocos2dx is the way to go every time. Unity is just too much overkill for 2d games and as already stated marmalade is just a thin abstraction layer not really a game engine. You can even run cocos2d on top of marmalade. My approach would be to use cocos2dx on iOS and android then in future run cocosd2dx code on top of marmalade as an easy way to port to bb10 and win phone 7

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

Go to cloud Messaging select:  Server key



function sendGCM($message, $deviceToken) {

    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array (
            'registration_ids' => array (
                $id
            ),
            'data' => array (
                "title" =>  "Notification title",
                "body" =>  $message,
            )
    );
    $fields = json_encode ( $fields );
    $headers = array (
        'Authorization: key=' . "YOUR_SERVER_KEY",
        'Content-Type: application/json'
    );
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_POST, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
    $result = curl_exec ( $ch );
    echo $result;

    curl_close ($ch);
}

Ordering issue with date values when creating pivot tables

Try creating a new pivot table, and not just refreshing.

I had a case where I forgot to add in a few dates. After adding them in I updated the pivot table range and hit refresh. They appeared at the end of the pivot table, out of order. I then tried to simply create a new pivot table and the dates where all in order.

Create a List that contain each Line of a File

my_list = [line.split(',') for line in open("filename.txt")]

eval command in Bash and its typical uses

eval takes a string as its argument, and evaluates it as if you'd typed that string on a command line. (If you pass several arguments, they are first joined with spaces between them.)

${$n} is a syntax error in bash. Inside the braces, you can only have a variable name, with some possible prefix and suffixes, but you can't have arbitrary bash syntax and in particular you can't use variable expansion. There is a way of saying “the value of the variable whose name is in this variable”, though:

echo ${!n}
one

$(…) runs the command specified inside the parentheses in a subshell (i.e. in a separate process that inherits all settings such as variable values from the current shell), and gathers its output. So echo $($n) runs $n as a shell command, and displays its output. Since $n evaluates to 1, $($n) attempts to run the command 1, which does not exist.

eval echo \${$n} runs the parameters passed to eval. After expansion, the parameters are echo and ${1}. So eval echo \${$n} runs the command echo ${1}.

Note that most of the time, you must use double quotes around variable substitutions and command substitutions (i.e. anytime there's a $): "$foo", "$(foo)". Always put double quotes around variable and command substitutions, unless you know you need to leave them off. Without the double quotes, the shell performs field splitting (i.e. it splits value of the variable or the output from the command into separate words) and then treats each word as a wildcard pattern. For example:

$ ls
file1 file2 otherfile
$ set -- 'f* *'
$ echo "$1"
f* *
$ echo $1
file1 file2 file1 file2 otherfile
$ n=1
$ eval echo \${$n}
file1 file2 file1 file2 otherfile
$eval echo \"\${$n}\"
f* *
$ echo "${!n}"
f* *

eval is not used very often. In some shells, the most common use is to obtain the value of a variable whose name is not known until runtime. In bash, this is not necessary thanks to the ${!VAR} syntax. eval is still useful when you need to construct a longer command containing operators, reserved words, etc.

Insert data into hive table

Try to use this with single quotes in data:

insert into table test_hive values ('1','puneet');

How to place two divs next to each other?

Try to use flexbox model. It is easy and short to write.

Live Jsfiddle

CSS:

#wrapper {
  display: flex;
  border: 1px solid black;
}
#first {
    border: 1px solid red;
}
#second {
    border: 1px solid green;
}

default direction is row. So, it aligns next to each other inside the #wrapper. But it is not supported IE9 or less than that versions

How to pretty-print a numpy.array without scientific notation and with given precision?

And here is what I use, and it's pretty uncomplicated:

print(np.vectorize("%.2f".__mod__)(sparse))

Print raw string from variable? (not getting the answers)

i wrote a small function.. but works for me

def conv(strng):
    k=strng
    k=k.replace('\a','\\a')
    k=k.replace('\b','\\b')
    k=k.replace('\f','\\f')
    k=k.replace('\n','\\n')
    k=k.replace('\r','\\r')
    k=k.replace('\t','\\t')
    k=k.replace('\v','\\v')
    return k

How to check if a windows form is already open, and close it if it is?

The below actually works very well.

private void networkInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
    var _open = false;
    FormCollection fc = Application.OpenForms;
    foreach (Form frm in fc)
    {
        if (frm.Name == "FormBrowseNetworkInformation")
        {
            _open = true;
            frm.Select();
            break;
        }
    }
    if (_open == false)
    {
        var formBrowseNetworkInformation = new FormBrowseNetworkInformation();
        formBrowseNetworkInformation.Show();
    }
}

Make Font Awesome icons in a circle?

You can simply get round icon using this code:

<a class="facebook-share-button social-icons" href="#" target="_blank">
    <i class="fab fa-facebook socialicons"></i>
</a>

Now your CSS will be:

.social-icons {
display: inline-block;border-radius: 25px;box-shadow: 0px 0px 2px #888;
padding: 0.5em;
background: #0D47A1;
font-size: 20px;
}
.socialicons{color: white;}

How do I make a dotted/dashed line in Android?

By using this class you can apply "dashed and underline" effect to multiple lines text. to use DashPathEffect you have to turn off hardwareAccelerated of your TextView(though DashPathEffect method has a problem with long text). you can find my sample project here: https://github.com/jintoga/Dashed-Underlined-TextView/blob/master/Untitled.png.

public class DashedUnderlineSpan implements LineBackgroundSpan, LineHeightSpan {

    private Paint paint;
    private TextView textView;
    private float offsetY;
    private float spacingExtra;

    public DashedUnderlineSpan(TextView textView, int color, float thickness, float dashPath,
                               float offsetY, float spacingExtra) {
        this.paint = new Paint();
        this.paint.setColor(color);
        this.paint.setStyle(Paint.Style.STROKE);
        this.paint.setPathEffect(new DashPathEffect(new float[] { dashPath, dashPath }, 0));
        this.paint.setStrokeWidth(thickness);
        this.textView = textView;
        this.offsetY = offsetY;
        this.spacingExtra = spacingExtra;
    }

    @Override
    public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v,
                             Paint.FontMetricsInt fm) {
        fm.ascent -= spacingExtra;
        fm.top -= spacingExtra;
        fm.descent += spacingExtra;
        fm.bottom += spacingExtra;
    }

    @Override
    public void drawBackground(Canvas canvas, Paint p, int left, int right, int top, int baseline,
                               int bottom, CharSequence text, int start, int end, int lnum) {
        int lineNum = textView.getLineCount();
        for (int i = 0; i < lineNum; i++) {
            Layout layout = textView.getLayout();
            canvas.drawLine(layout.getLineLeft(i), layout.getLineBottom(i) - spacingExtra + offsetY,
                    layout.getLineRight(i), layout.getLineBottom(i) - spacingExtra + offsetY,
                    this.paint);
        }
    }
}

Result:

dashed underline

How to store a dataframe using Pandas

Pandas DataFrames have the to_pickle function which is useful for saving a DataFrame:

import pandas as pd

a = pd.DataFrame({'A':[0,1,0,1,0],'B':[True, True, False, False, False]})
print a
#    A      B
# 0  0   True
# 1  1   True
# 2  0  False
# 3  1  False
# 4  0  False

a.to_pickle('my_file.pkl')

b = pd.read_pickle('my_file.pkl')
print b
#    A      B
# 0  0   True
# 1  1   True
# 2  0  False
# 3  1  False
# 4  0  False

LDAP root query syntax to search more than one specific OU

You can!!! In short use this as the connection string:

ldap://<host>:3268/DC=<my>,DC=<domain>?cn

together with your search filter, e.g.

(&(sAMAccountName={0})(&((objectCategory=person)(objectclass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberOf:1.2.840.113556.1.4.1941:=CN=<some-special-nested-group>,OU=<ou3>,OU=<ou2>,OU=<ou1>,DC=<dc3>,DC=<dc2>,DC=<dc1>))))

That will search in the so called Global Catalog, that had been available out-of-the-box in our environment.

Instead of the known/common other versions (or combinations thereof) that did NOT work in our environment with multiple OUs:

ldap://<host>/DC=<my>,DC=<domain>
ldap://<host>:389/DC=<my>,DC=<domain>  (standard port)
ldap://<host>/OU=<someOU>,DC=<my>,DC=<domain>
ldap://<host>/CN=<someCN>,DC=<my>,DC=<domain>
ldap://<host>/(|(OU=<someOU1>)(OU=<someOU2>)),DC=<my>,DC=<domain> (search filters here shouldn't work at all by definition)

(I am a developer, not an AD/LDAP guru:) Damn I had been searching for this solution everywhere for almost 2 days and almost gave up, getting used to the thought I might have to implement this obviously very common scenario by hand (with Jasperserver/Spring security(/Tomcat)). (So this shall be a reminder if somebody else or me should have this problem again in the future :O) )

Here some other related threads I found during my research that had been mostly of little help:

And here I will provide our anonymized Tomcat LDAP config in case it may be helpful (/var/lib/tomcat7/webapps/jasperserver/WEB-INF/applicationContext-externalAUTH-LDAP.xml):

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

<!-- ############ LDAP authentication ############ - Sample configuration 
    of external authentication via an external LDAP server. -->


<bean id="proxyAuthenticationProcessingFilter"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.BaseAuthenticationProcessingFilter">
    <property name="authenticationManager">
        <ref local="ldapAuthenticationManager" />
    </property>
    <property name="externalDataSynchronizer">
        <ref local="externalDataSynchronizer" />
    </property>

    <property name="sessionRegistry">
        <ref bean="sessionRegistry" />
    </property>

    <property name="internalAuthenticationFailureUrl" value="/login.html?error=1" />
    <property name="defaultTargetUrl" value="/loginsuccess.html" />
    <property name="invalidateSessionOnSuccessfulAuthentication"
        value="true" />
    <property name="migrateInvalidatedSessionAttributes" value="true" />
</bean>

<bean id="proxyAuthenticationSoapProcessingFilter"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.DefaultAuthenticationSoapProcessingFilter">
    <property name="authenticationManager" ref="ldapAuthenticationManager" />
    <property name="externalDataSynchronizer" ref="externalDataSynchronizer" />

    <property name="invalidateSessionOnSuccessfulAuthentication"
        value="true" />
    <property name="migrateInvalidatedSessionAttributes" value="true" />
    <property name="filterProcessesUrl" value="/services" />
</bean>

<bean id="proxyRequestParameterAuthenticationFilter"
    class="com.jaspersoft.jasperserver.war.util.ExternalRequestParameterAuthenticationFilter">
    <property name="authenticationManager">
        <ref local="ldapAuthenticationManager" />
    </property>
    <property name="externalDataSynchronizer" ref="externalDataSynchronizer" />

    <property name="authenticationFailureUrl">
        <value>/login.html?error=1</value>
    </property>
    <property name="excludeUrls">
        <list>
            <value>/j_spring_switch_user</value>
        </list>
    </property>
</bean>

<bean id="proxyBasicProcessingFilter"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.ExternalAuthBasicProcessingFilter">
    <property name="authenticationManager" ref="ldapAuthenticationManager" />
    <property name="externalDataSynchronizer" ref="externalDataSynchronizer" />

    <property name="authenticationEntryPoint">
        <ref local="basicProcessingFilterEntryPoint" />
    </property>
</bean>

<bean id="proxyAuthenticationRestProcessingFilter"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.DefaultAuthenticationRestProcessingFilter">
    <property name="authenticationManager">
        <ref local="ldapAuthenticationManager" />
    </property>
    <property name="externalDataSynchronizer">
        <ref local="externalDataSynchronizer" />
    </property>

    <property name="filterProcessesUrl" value="/rest/login" />
    <property name="invalidateSessionOnSuccessfulAuthentication"
        value="true" />
    <property name="migrateInvalidatedSessionAttributes" value="true" />
</bean>



<bean id="ldapAuthenticationManager" class="org.springframework.security.providers.ProviderManager">
    <property name="providers">
        <list>
            <ref local="ldapAuthenticationProvider" />
            <ref bean="${bean.daoAuthenticationProvider}" />
            <!--anonymousAuthenticationProvider only needed if filterInvocationInterceptor.alwaysReauthenticate 
                is set to true <ref bean="anonymousAuthenticationProvider"/> -->
        </list>
    </property>
</bean>

<bean id="ldapAuthenticationProvider"
    class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
    <constructor-arg>
        <bean
            class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
            <constructor-arg>
                <ref local="ldapContextSource" />
            </constructor-arg>
            <property name="userSearch" ref="userSearch" />
        </bean>
    </constructor-arg>
    <constructor-arg>
        <bean
            class="org.springframework.security.ldap.populator.DefaultLdapAuthoritiesPopulator">
            <constructor-arg index="0">
                <ref local="ldapContextSource" />
            </constructor-arg>
            <constructor-arg index="1">
                <value></value>
            </constructor-arg>

            <property name="groupRoleAttribute" value="cn" />
            <property name="convertToUpperCase" value="true" />
            <property name="rolePrefix" value="ROLE_" />
            <property name="groupSearchFilter"
                value="(&amp;(member={0})(&amp;(objectCategory=Group)(objectclass=group)(cn=my-nested-group-name)))" />
            <property name="searchSubtree" value="true" />
            <!-- Can setup additional external default roles here <property name="defaultRole" 
                value="LDAP"/> -->
        </bean>
    </constructor-arg>
</bean>

<bean id="userSearch"
    class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
    <constructor-arg index="0">
        <value></value>
    </constructor-arg>
    <constructor-arg index="1">
        <value>(&amp;(sAMAccountName={0})(&amp;((objectCategory=person)(objectclass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberOf:1.2.840.113556.1.4.1941:=CN=my-nested-group-name,OU=ou3,OU=ou2,OU=ou1,DC=dc3,DC=dc2,DC=dc1))))
        </value>
    </constructor-arg>
    <constructor-arg index="2">
        <ref local="ldapContextSource" />
    </constructor-arg>
    <property name="searchSubtree">
        <value>true</value>
    </property>
</bean>

<bean id="ldapContextSource"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.ldap.JSLdapContextSource">
    <constructor-arg value="ldap://myhost:3268/DC=dc3,DC=dc2,DC=dc1?cn" />
    <!-- manager user name and password (may not be needed) -->
    <property name="userDn" value="CN=someuser,OU=ou4,OU=1,DC=dc3,DC=dc2,DC=dc1" />
    <property name="password" value="somepass" />
    <!--End Changes -->
</bean>
<!-- ############ LDAP authentication ############ -->

<!-- ############ JRS Synchronizer ############ -->
<bean id="externalDataSynchronizer"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.ExternalDataSynchronizerImpl">
    <property name="externalUserProcessors">
        <list>
            <ref local="externalUserSetupProcessor" />
            <!-- Example processor for creating user folder -->
            <!--<ref local="externalUserFolderProcessor"/> -->
        </list>
    </property>
</bean>

<bean id="abstractExternalProcessor"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.AbstractExternalUserProcessor"
    abstract="true">
    <property name="repositoryService" ref="${bean.repositoryService}" />
    <property name="userAuthorityService" ref="${bean.userAuthorityService}" />
    <property name="tenantService" ref="${bean.tenantService}" />
    <property name="profileAttributeService" ref="profileAttributeService" />
    <property name="objectPermissionService" ref="objectPermissionService" />
</bean>

<bean id="externalUserSetupProcessor"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.ExternalUserSetupProcessor"
    parent="abstractExternalProcessor">
    <property name="userAuthorityService">
        <ref bean="${bean.internalUserAuthorityService}" />
    </property>
    <property name="defaultInternalRoles">
        <list>
            <value>ROLE_USER</value>
        </list>
    </property>

    <property name="organizationRoleMap">
        <map>
            <!-- Example of mapping customer roles to JRS roles -->
            <entry>
                <key>
                    <value>ROLE_MY-NESTED-GROUP-NAME</value>
                </key>
                <!-- JRS role that the <key> external role is mapped to -->
                <value>ROLE_USER</value>
            </entry>
        </map>
    </property>
</bean>

<!--bean id="externalUserFolderProcessor" class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.ExternalUserFolderProcessor" 
    parent="abstractExternalProcessor"> <property name="repositoryService" ref="${bean.unsecureRepositoryService}"/> 
    </bean -->

<!-- ############ JRS Synchronizer ############ -->

How to find keys of a hash?

This is the best you can do, as far as I know...

var keys = [];
for (var k in h)keys.push(k);

MySQL my.cnf performance tuning recommendations

Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.

https://tools.percona.com/wizard

Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/

Everyone points to key_buffer_size first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).

How to get all of the IDs with jQuery?

It's a late answer but now there is an easy way. Current version of jquery lets you search if attribute exists. For example

$('[id]')

will give you all the elements if they have id. If you want all spans with id starting with span you can use

$('span[id^="span"]')

How do I install Maven with Yum?

For those of you that are looking for a way to install Maven in 2018:

$ sudo yum install maven

is supported these days.

GCM with PHP (Google Cloud Messaging)

It's easy to do. The cURL code that's on the page that Elad Nava has put here works. Elad has commented about the error he's receiving.

String describing an error that occurred while processing the message for that recipient. The possible values are the same as documented in the above table, plus "Unavailable" (meaning GCM servers were busy and could not process the message for that particular recipient, so it could be retried).

I've got a service set up already that seems to be working (ish), and so far all I've had back are unavailable returns from Google. More than likely this will change soon.

To answer the question, use PHP, make sure the Zend Framework is in your include path, and use this code:

<?php
    ini_set('display_errors',1);
    include"Zend/Loader/Autoloader.php";
    Zend_Loader_Autoloader::getInstance();

    $url = 'https://android.googleapis.com/gcm/send';
    $serverApiKey = "YOUR API KEY AS GENERATED IN API CONSOLE";
    $reg = "DEVICE REGISTRATION ID";

    $data = array(
            'registration_ids' => array($reg),
            'data' => array('yourname' => 'Joe Bloggs')
    );

    print(json_encode($data));

    $client = new Zend_Http_Client($url);
    $client->setMethod('POST');
    $client->setHeaders(array("Content-Type" => "application/json", "Authorization" => "key=" . $serverApiKey));
    $client->setRawData(json_encode($data));
    $request = $client->request('POST');
    $body = $request->getBody();
    $headers = $request->getHeaders();
    print("<xmp>");
    var_dump($body);
    var_dump($headers);

And there we have it. A working (it will work soon) example of using Googles new GCM in Zend Framework PHP.

CSS background image to fit width, height should auto-scale in proportion

Background image is not Set Perfect then his css is problem create so his css file change to below code

_x000D_
_x000D_
html {  _x000D_
  background-image: url("example.png");  _x000D_
  background-repeat: no-repeat;  _x000D_
  background-position: 0% 0%;_x000D_
  background-size: 100% 100%;_x000D_
}
_x000D_
_x000D_
_x000D_

%; background-size: 100% 100%;"

How to draw a rounded Rectangle on HTML Canvas?

    var canvas = document.createElement("canvas");
    document.body.appendChild(canvas);
    var ctx = canvas.getContext("2d");
    ctx.beginPath();
    ctx.moveTo(100,100);
    ctx.arcTo(0,100,0,0,30);
    ctx.arcTo(0,0,100,0,30);
    ctx.arcTo(100,0,100,100,30);
    ctx.arcTo(100,100,0,100,30);
    ctx.fill();

load jquery after the page is fully loaded

You can also use:

$(window).bind("load", function() { 
    // Your code here.
});

Remove from the beginning of std::vector

Two suggestions:

  1. Use std::deque instead of std::vector for better performance in your specific case and use the method std::deque::pop_front().
  2. Rethink (I mean: delete) the & in std::vector<ScanRule>& topPriorityRules;

How can I refresh a page with jQuery?

window.location.reload() will reload from the server and will load all your data, scripts, images, etc. again.

So if you just want to refresh the HTML, the window.location = document.URL will return much quicker and with less traffic. But it will not reload the page if there is a hash (#) in the URL.

Generate random string/characters in JavaScript

How about this compact little trick?

var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var stringLength = 5;

function pickRandom() {
    return possible[Math.floor(Math.random() * possible.length)];
}

var randomString = Array.apply(null, Array(stringLength)).map(pickRandom).join('');

You need the Array.apply there to trick the empty array into being an array of undefineds.

If you're coding for ES2015, then building the array is a little simpler:

var randomString = Array.from({ length: stringLength }, pickRandom).join('');

Multiprocessing a for loop?

Alternatively

with Pool() as pool: 
    pool.map(fits.open, [name + '.fits' for name in datainput])

How to convert a boolean array to an int array

The 1*y method works in Numpy too:

>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False,  True,  True], dtype=bool)
>>> 1*y                      # Method 1
array([0, 0, 1, 1])
>>> y.astype(int)            # Method 2
array([0, 0, 1, 1]) 

If you are asking for a way to convert Python lists from Boolean to int, you can use map to do it:

>>> testList = [False, False,  True,  True]
>>> map(lambda x: 1 if x else 0, testList)
[0, 0, 1, 1]
>>> map(int, testList)
[0, 0, 1, 1]

Or using list comprehensions:

>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]

How to append new data onto a new line

There is also one fact that you have to consider. You should first check if your file is empty before adding anything to it. Because if your file is empty then I don't think you would like to add a blank new line in the beginning of the file. This code

  1. first checks if the file is empty
  2. If the file is empty then it will simply add your input text to the file else it will add a new line and then it will add your text to the file. You should use a try catch for os.path.getsize() to catch any exceptions.

Code:

import os

def storescores():
hs = open("hst.txt","a")
if(os.path.getsize("hst.txt") > 0):
   hs.write("\n"+name)
else:
   hs.write(name)

hs.close()

SQLAlchemy insert or update example

assuming certain column names...

INSERT one

newToner = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

dbsession.add(newToner)   
dbsession.commit()

INSERT multiple

newToner1 = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

newToner2 = Toner(toner_id = 2,
                    toner_color = 'red',
                    toner_hex = '#F01731')

dbsession.add_all([newToner1, newToner2])   
dbsession.commit()

UPDATE

q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'

dbsession.commit()

or using a fancy one-liner using MERGE

record = dbsession.merge(Toner( **kwargs))

How to delete columns in numpy.array

>>> A = array([[ 1,  2,  3,  4],
               [ 5,  6,  7,  8],
               [ 9, 10, 11, 12]])

>>> A = A.transpose()

>>> A = A[1:].transpose()

Create table (structure) from existing table

SELECT * 
INTO NewTable
FROM OldTable
WHERE 1 = 2

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

In some cases, just install web page 2 to resolve this (resolved with my case - deploy to local web page using web api )

https://www.microsoft.com/en-us/download/details.aspx?id=34600

How to create string with multiple spaces in JavaScript

var a = 'something' + Array(10).fill('\xa0').join('') + 'something'

number inside Array(10) can be changed to needed number of spaces

How to format a java.sql Timestamp for displaying?

For this particular question, the standard suggestion of java.text.SimpleDateFormat works, but has the unfortunate side effect that SimpleDateFormat is not thread-safe and can be the source of particularly nasty problems since it'll corrupt your output in multi-threaded scenarios, and you won't get any exceptions!

I would strongly recommend looking at Joda for anything like this. Why ? It's a much richer and more intuitive time/date library for Java than the current library (and the basis of the up-and-coming new standard Java date/time library, so you'll be learning a soon-to-be-standard API).

Git/GitHub can't push to master

The fastest way yuo get over it is to replace origin with the suggestion it gives.

Instead of git push origin master, use:

git push [email protected]:my_user_name/my_repo.git master

Open PDF in new browser full window

To do it from a Base64 encoding you can use the following function:

function base64ToArrayBuffer(data) {
  const bString = window.atob(data);
  const bLength = bString.length;
  const bytes = new Uint8Array(bLength);
  for (let i = 0; i < bLength; i++) {
      bytes[i] = bString.charCodeAt(i);
  }
  return bytes;
}
function base64toPDF(base64EncodedData, fileName = 'file') {
  const bufferArray = base64ToArrayBuffer(base64EncodedData);
  const blobStore = new Blob([bufferArray], { type: 'application/pdf' });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blobStore);
      return;
  }
  const data = window.URL.createObjectURL(blobStore);
  const link = document.createElement('a');
  document.body.appendChild(link);
  link.href = data;
  link.download = `${fileName}.pdf`;
  link.click();
  window.URL.revokeObjectURL(data);
  link.remove();
}

Jquery Chosen plugin - dynamically populate list by Ajax

Ashirvad's answer no longer works. Note the class name changes and using the option element instead of the li element. I've updated my answer to not use the deprecated "success" event, instead opting for .done():

$('.chosen-search input').autocomplete({
    minLength: 3,
    source: function( request, response ) {
        $.ajax({
            url: "/some/autocomplete/url/"+request.term,
            dataType: "json",
            beforeSend: function(){ $('ul.chosen-results').empty(); $("#CHOSEN_INPUT_FIELDID").empty(); }
        }).done(function( data ) {
                response( $.map( data, function( item ) {
                    $('#CHOSEN_INPUT_FIELDID').append('<option value="blah">' + item.name + '</option>');
                }));

               $("#CHOSEN_INPUT_FIELDID").trigger("chosen:updated");
        });
    }
});

Remove warning messages in PHP

I think that better solution is configuration of .htaccess In that way you dont have to alter code of application. Here are directives for Apache2

php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0

How can apply multiple background color to one div

You can create something like c using CSS multiple-backgrounds.

div {
    background: linear-gradient(red, red),
                linear-gradient(blue, blue),
                linear-gradient(green, green);
    background-size: 30% 50%,
                     30% 60%,
                     40% 80%;
    background-position: 0% top,
                         calc(30% * 100 / (100 - 30)) top,
                         calc(60% * 100 / (100 - 40)) top;
    background-repeat: no-repeat;
}

Note, you still have to use linear-gradients for background types, because CSS will not allow you to control the background-size of a single color layer. So here we just make a single-color gradient. Then you can control the size/position of each of those blocks of color independently. You also have to make sure they don't repeat, or they'll just expand and cover the whole image.

The trickiest part here is background-position. A background-position of 0% puts your element's left edge at the left. 100% puts its right edge at the right. 50% centers is middle.

For a fun bit of math to solve that, you can guess the transform is probably linear, and just solve two little slope-intercept equations.

// (at 0%, the div's left edge is 0% from the left)
0 = m * 0 + b
// (at 100%, the div's right edge is 100% - width% from the left)
100 = m * (100 - width) + b
b = 0, m = 100 / (100 - width)

so to position our 40% wide div 60% from the left, we put it at 60% * 100 / (100 - 40) (or use css-calc).

How do I make a text go onto the next line if it overflows?

As long as you specify a width on the element, it should wrap itself without needing anything else.

Toggle Checkboxes on/off

simply you can use this

$("#chkAll").on("click",function(){
    $("input[name=checkBoxName]").prop("checked",$(this).prop("checked"));
});

Remove a git commit which has not been pushed

There are two branches to this question (Rolling back a commit does not mean I want to lose all my local changes):

1. To revert the latest commit and discard changes in the committed file do:

git reset --hard HEAD~1

2. To revert the latest commit but retain the local changes (on disk) do:

git reset --soft HEAD~1

This (the later command) will take you to the state you would have been if you did git add.

If you want to unstage the files after that, do

git reset

Now you can make more changes before adding and then committing again.

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

Unless there is some other requirement not specified, I would simply convert your color image to grayscale and work with that only (no need to work on the 3 channels, the contrast present is too high already). Also, unless there is some specific problem regarding resizing, I would work with a downscaled version of your images, since they are relatively large and the size adds nothing to the problem being solved. Then, finally, your problem is solved with a median filter, some basic morphological tools, and statistics (mostly for the Otsu thresholding, which is already done for you).

Here is what I obtain with your sample image and some other image with a sheet of paper I found around:

enter image description here enter image description here

The median filter is used to remove minor details from the, now grayscale, image. It will possibly remove thin lines inside the whitish paper, which is good because then you will end with tiny connected components which are easy to discard. After the median, apply a morphological gradient (simply dilation - erosion) and binarize the result by Otsu. The morphological gradient is a good method to keep strong edges, it should be used more. Then, since this gradient will increase the contour width, apply a morphological thinning. Now you can discard small components.

At this point, here is what we have with the right image above (before drawing the blue polygon), the left one is not shown because the only remaining component is the one describing the paper:

enter image description here

Given the examples, now the only issue left is distinguishing between components that look like rectangles and others that do not. This is a matter of determining a ratio between the area of the convex hull containing the shape and the area of its bounding box; the ratio 0.7 works fine for these examples. It might be the case that you also need to discard components that are inside the paper, but not in these examples by using this method (nevertheless, doing this step should be very easy especially because it can be done through OpenCV directly).

For reference, here is a sample code in Mathematica:

f = Import["http://thwartedglamour.files.wordpress.com/2010/06/my-coffee-table-1-sa.jpg"]
f = ImageResize[f, ImageDimensions[f][[1]]/4]
g = MedianFilter[ColorConvert[f, "Grayscale"], 2]
h = DeleteSmallComponents[Thinning[
     Binarize[ImageSubtract[Dilation[g, 1], Erosion[g, 1]]]]]
convexvert = ComponentMeasurements[SelectComponents[
     h, {"ConvexArea", "BoundingBoxArea"}, #1 / #2 > 0.7 &], 
     "ConvexVertices"][[All, 2]]
(* To visualize the blue polygons above: *)
Show[f, Graphics[{EdgeForm[{Blue, Thick}], RGBColor[0, 0, 1, 0.5], 
     Polygon @@ convexvert}]]

If there are more varied situations where the paper's rectangle is not so well defined, or the approach confuses it with other shapes -- these situations could happen due to various reasons, but a common cause is bad image acquisition -- then try combining the pre-processing steps with the work described in the paper "Rectangle Detection based on a Windowed Hough Transform".

What does "dereferencing" a pointer mean?

A pointer is a "reference" to a value.. much like a library call number is a reference to a book. "Dereferencing" the call number is physically going through and retrieving that book.

int a=4 ;
int *pA = &a ;
printf( "The REFERENCE/call number for the variable `a` is %p\n", pA ) ;

// The * causes pA to DEREFERENCE...  `a` via "callnumber" `pA`.
printf( "%d\n", *pA ) ; // prints 4.. 

If the book isn't there, the librarian starts shouting, shuts the library down, and a couple of people are set to investigate the cause of a person going to find a book that isn't there.

How to run a bash script from C++ program

Since this is a pretty old question, and this method hasn't been added (aside from the system() call function) I guess it would be useful to include creating the shell script with the C binary itself. The shell code will be housed inside the file.c source file. Here is an example of code:

#include <stdio.h>
#include <stdlib.h>

#define SHELLSCRIPT "\
#/bin/bash \n\
echo -e \"\" \n\
echo -e \"This is a test shell script inside C code!!\" \n\
read -p \"press <enter> to continue\" \n\
clear\
"

int main() {

system(SHELLSCRIPT);
return 0;
}

Basically, in a nutshell (pun intended), we are defining the script name, fleshing out the script, enclosing them in double quotes (while inserting proper escapes to ignore double quotes in the shell code), and then calling that script's name, which in this example is SHELLSCRIPT using the system() function in main().

php: how to get associative array key from numeric index?

$array = array( 'one' =>'value', 'two' => 'value2' );
$keys  = array_keys($array);
echo $keys[0]; // one
echo $keys[1]; // two

Simple Java Client/Server Program

this is client code

first run the server program then on another cmd run client program

import java.io.*;
import java.net.*;

public class frmclient 
{
 public static void main(String args[])throws Exception
 {

   try
        {
          DataInputStream d=new DataInputStream(System.in);
          System.out.print("\n1.fact\n2.Sum of digit\nEnter ur choice:");

           int ch=Integer.parseInt(d.readLine());
           System.out.print("\nEnter number:");
           int num=Integer.parseInt(d.readLine());

           Socket s=new Socket("localhost",1024);

           PrintStream ps=new PrintStream(s.getOutputStream());
           ps.println(ch+"");
           ps.println(num+"");

          DataInputStream dis=new DataInputStream(s.getInputStream());
           String response=dis.readLine();
                 System.out.print("Answer:"+response);


                s.close();
        }
        catch(Exception ex)
        {

        }
 }


}

this is sever side code

import java.io.*;
import java.net.*;
public class frmserver {

  public static void main(String args[])throws Exception
  {

try
    {

    ServerSocket ss=new ServerSocket(1024);
       System.out.print("\nWaiting for client.....");
       Socket s=ss.accept();
       System.out.print("\nConnected");

       DataInputStream d=new DataInputStream(s.getInputStream());

        int ch=Integer.parseInt(d.readLine());
       int num=Integer.parseInt(d.readLine());
         int result=0;

        PrintStream ps=new PrintStream(s.getOutputStream());
        switch(ch)
        {
          case 1:result=fact(num);
                 ps.println(result);
                  break;
          case 2:result=sum(num);
                 ps.println(result);
                  break;
        }

          ss.close();
          s.close();
    }
catch(Exception ex)
{

}
  }

  public static int fact(int n)
  {
  int ans=1;
    for(int i=n;i>0;i--)
    {
      ans=ans*i;
    }
    return ans;
  }
  public static int sum(int n)
  {
   String str=n+"";
   int ans=0;
    for(int i=0;i<str.length();i++)
    {
      int tmp=Integer.parseInt(str.charAt(i)+"");
      ans=ans+tmp;
    }
    return ans;
  }
}

How to extract a single value from JSON response?

Extract single value from JSON response Python

Try this

import json
import sys

#load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

#dumps the json object into an element
json_str = json.dumps(data)

#load the json to a string
resp = json.loads(json_str)

#print the resp
print (resp)

#extract an element in the response
print (resp['test1'])

SQL server query to get the list of columns in a table along with Data types, NOT NULL, and PRIMARY KEY constraints

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES 
     WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'Table')
      BEGIN
        SELECT COLS.COLUMN_NAME, COLS.DATA_TYPE, COLS.CHARACTER_MAXIMUM_LENGTH, 
              (SELECT 'Yes' FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
                              ON COLS.TABLE_NAME = TC.TABLE_NAME 
                             AND TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
                             AND KCU.TABLE_NAME = TC.TABLE_NAME
                             AND KCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
                             AND KCU.COLUMN_NAME = COLS.COLUMN_NAME) AS KeyX
        FROM INFORMATION_SCHEMA.COLUMNS COLS WHERE TABLE_NAME = 'Table' ORDER BY KeyX DESC, COLUMN_NAME
      END

Deleting folders in python recursively

The command (given by Tomek) can't delete a file, if it is read only. therefore, one can use -

import os, sys
import stat

def del_evenReadonly(action, name, exc):
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)

if  os.path.exists("test/qt_env"):
    shutil.rmtree('test/qt_env',onerror=del_evenReadonly)

tsql returning a table from a function or store procedure

Use this as a template

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE FUNCTION <Table_Function_Name, sysname, FunctionName> 
(
    -- Add the parameters for the function here
    <@param1, sysname, @p1> <data_type_for_param1, , int>, 
    <@param2, sysname, @p2> <data_type_for_param2, , char>
)
RETURNS 
<@Table_Variable_Name, sysname, @Table_Var> TABLE 
(
    -- Add the column definitions for the TABLE variable here
    <Column_1, sysname, c1> <Data_Type_For_Column1, , int>, 
    <Column_2, sysname, c2> <Data_Type_For_Column2, , int>
)
AS
BEGIN
    -- Fill the table variable with the rows for your result set

    RETURN 
END
GO

That will define your function. Then you would just use it as any other table:

Select * from MyFunction(Param1, Param2, etc.)

Save image from url with curl PHP

try this:

function grab_image($url,$saveto){
    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
    $raw=curl_exec($ch);
    curl_close ($ch);
    if(file_exists($saveto)){
        unlink($saveto);
    }
    $fp = fopen($saveto,'x');
    fwrite($fp, $raw);
    fclose($fp);
}

and ensure that in php.ini allow_url_fopen is enable

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

Here's a modification of the accepted answer to provide more functionality.

RangeCollection.cs:

public class RangeCollection<T> : ObservableCollection<T>
{
    #region Members

    /// <summary>
    /// Occurs when a single item is added.
    /// </summary>
    public event EventHandler<ItemAddedEventArgs<T>> ItemAdded;

    /// <summary>
    /// Occurs when a single item is inserted.
    /// </summary>
    public event EventHandler<ItemInsertedEventArgs<T>> ItemInserted;

    /// <summary>
    /// Occurs when a single item is removed.
    /// </summary>
    public event EventHandler<ItemRemovedEventArgs<T>> ItemRemoved;

    /// <summary>
    /// Occurs when a single item is replaced.
    /// </summary>
    public event EventHandler<ItemReplacedEventArgs<T>> ItemReplaced;

    /// <summary>
    /// Occurs when items are added to this.
    /// </summary>
    public event EventHandler<ItemsAddedEventArgs<T>> ItemsAdded;

    /// <summary>
    /// Occurs when items are removed from this.
    /// </summary>
    public event EventHandler<ItemsRemovedEventArgs<T>> ItemsRemoved;

    /// <summary>
    /// Occurs when items are replaced within this.
    /// </summary>
    public event EventHandler<ItemsReplacedEventArgs<T>> ItemsReplaced;

    /// <summary>
    /// Occurs when entire collection is cleared.
    /// </summary>
    public event EventHandler<ItemsClearedEventArgs<T>> ItemsCleared;

    /// <summary>
    /// Occurs when entire collection is replaced.
    /// </summary>
    public event EventHandler<CollectionReplacedEventArgs<T>> CollectionReplaced;

    #endregion

    #region Helper Methods

    /// <summary>
    /// Throws exception if any of the specified objects are null.
    /// </summary>
    private void Check(params T[] Items)
    {
        foreach (T Item in Items)
        {
            if (Item == null)
            {
                throw new ArgumentNullException("Item cannot be null.");
            }
        }
    }

    private void Check(IEnumerable<T> Items)
    {
        if (Items == null) throw new ArgumentNullException("Items cannot be null.");
    }

    private void Check(IEnumerable<IEnumerable<T>> Items)
    {
        if (Items == null) throw new ArgumentNullException("Items cannot be null.");
    }

    private void RaiseChanged(NotifyCollectionChangedAction Action)
    {
        this.OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        this.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
        this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }

    #endregion

    #region Bulk Methods

    /// <summary> 
    /// Adds the elements of the specified collection to the end of this.
    /// </summary> 
    public void AddRange(IEnumerable<T> NewItems)
    {
        this.Check(NewItems);
        foreach (var i in NewItems) this.Items.Add(i);
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        this.OnItemsAdded(new ItemsAddedEventArgs<T>(NewItems));
    }

    /// <summary>
    /// Adds variable IEnumerable<T> to this.
    /// </summary>
    /// <param name="List"></param>
    public void AddRange(params IEnumerable<T>[] NewItems)
    {
        this.Check(NewItems);
        foreach (IEnumerable<T> Items in NewItems) foreach (T Item in Items) this.Items.Add(Item);
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        //TO-DO: Raise OnItemsAdded with combined IEnumerable<T>.
    }

    /// <summary> 
    /// Removes the first occurence of each item in the specified collection. 
    /// </summary> 
    public void Remove(IEnumerable<T> OldItems)
    {
        this.Check(OldItems);
        foreach (var i in OldItems) Items.Remove(i);
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        OnItemsRemoved(new ItemsRemovedEventArgs<T>(OldItems));
    }

    /// <summary>
    /// Removes all occurences of each item in the specified collection.
    /// </summary>
    /// <param name="itemsToRemove"></param>
    public void RemoveAll(IEnumerable<T> OldItems)
    {
        this.Check(OldItems);
        var set = new HashSet<T>(OldItems);
        var list = this as List<T>;
        int i = 0;
        while (i < this.Count) if (set.Contains(this[i])) this.RemoveAt(i); else i++;
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        OnItemsRemoved(new ItemsRemovedEventArgs<T>(OldItems));
    }

    /// <summary> 
    /// Replaces all occurences of a single item with specified item.
    /// </summary> 
    public void ReplaceAll(T Old, T New)
    {
        this.Check(Old, New);
        this.Replace(Old, New, false);
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        this.OnItemReplaced(new ItemReplacedEventArgs<T>(Old, New));
    }

    /// <summary> 
    /// Clears this and adds specified collection. 
    /// </summary> 
    public void ReplaceCollection(IEnumerable<T> NewItems, bool SupressEvent = false)
    {
        this.Check(NewItems);
        IEnumerable<T> OldItems = new List<T>(this.Items);
        this.Items.Clear();
        foreach (T Item in NewItems) this.Items.Add(Item);
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        this.OnReplaced(new CollectionReplacedEventArgs<T>(OldItems, NewItems));
    }

    private void Replace(T Old, T New, bool BreakFirst)
    {
        List<T> Cloned = new List<T>(this.Items);
        int i = 0;
        foreach (T Item in Cloned)
        {
            if (Item.Equals(Old))
            {
                this.Items.Remove(Item);
                this.Items.Insert(i, New);
                if (BreakFirst) break;
            }
            i++;
        }
    }

    /// <summary> 
    /// Replaces the first occurence of a single item with specified item.
    /// </summary> 
    public void Replace(T Old, T New)
    {
        this.Check(Old, New);
        this.Replace(Old, New, true);
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        this.OnItemReplaced(new ItemReplacedEventArgs<T>(Old, New));
    }

    #endregion

    #region  New Methods

    /// <summary>
    /// Removes a single item.
    /// </summary>
    /// <param name="Item"></param>
    public new void Remove(T Item)
    {
        this.Check(Item);
        base.Remove(Item);
        OnItemRemoved(new ItemRemovedEventArgs<T>(Item));
    }

    /// <summary>
    /// Removes a single item at specified index.
    /// </summary>
    /// <param name="i"></param>
    public new void RemoveAt(int i)
    {
        T OldItem = this.Items[i]; //This will throw first if null
        base.RemoveAt(i);
        OnItemRemoved(new ItemRemovedEventArgs<T>(OldItem));
    }

    /// <summary>
    /// Clears this.
    /// </summary>
    public new void Clear()
    {
        IEnumerable<T> OldItems = new List<T>(this.Items);
        this.Items.Clear();
        this.RaiseChanged(NotifyCollectionChangedAction.Reset);
        this.OnCleared(new ItemsClearedEventArgs<T>(OldItems));
    }

    /// <summary>
    /// Adds a single item to end of this.
    /// </summary>
    /// <param name="t"></param>
    public new void Add(T Item)
    {
        this.Check(Item);
        base.Add(Item);
        this.OnItemAdded(new ItemAddedEventArgs<T>(Item));
    }

    /// <summary>
    /// Inserts a single item at specified index.
    /// </summary>
    /// <param name="i"></param>
    /// <param name="t"></param>
    public new void Insert(int i, T Item)
    {
        this.Check(Item);
        base.Insert(i, Item);
        this.OnItemInserted(new ItemInsertedEventArgs<T>(Item, i));
    }

    /// <summary>
    /// Returns list of T.ToString().
    /// </summary>
    /// <returns></returns>
    public new IEnumerable<string> ToString()
    {
        foreach (T Item in this) yield return Item.ToString();
    }

    #endregion

    #region Event Methods

    private void OnItemAdded(ItemAddedEventArgs<T> i)
    {
        if (this.ItemAdded != null) this.ItemAdded(this, new ItemAddedEventArgs<T>(i.NewItem));
    }

    private void OnItemInserted(ItemInsertedEventArgs<T> i)
    {
        if (this.ItemInserted != null) this.ItemInserted(this, new ItemInsertedEventArgs<T>(i.NewItem, i.Index));
    }

    private void OnItemRemoved(ItemRemovedEventArgs<T> i)
    {
        if (this.ItemRemoved != null) this.ItemRemoved(this, new ItemRemovedEventArgs<T>(i.OldItem));
    }

    private void OnItemReplaced(ItemReplacedEventArgs<T> i)
    {
        if (this.ItemReplaced != null) this.ItemReplaced(this, new ItemReplacedEventArgs<T>(i.OldItem, i.NewItem));
    }

    private void OnItemsAdded(ItemsAddedEventArgs<T> i)
    {
        if (this.ItemsAdded != null) this.ItemsAdded(this, new ItemsAddedEventArgs<T>(i.NewItems));
    }

    private void OnItemsRemoved(ItemsRemovedEventArgs<T> i)
    {
        if (this.ItemsRemoved != null) this.ItemsRemoved(this, new ItemsRemovedEventArgs<T>(i.OldItems));
    }

    private void OnItemsReplaced(ItemsReplacedEventArgs<T> i)
    {
        if (this.ItemsReplaced != null) this.ItemsReplaced(this, new ItemsReplacedEventArgs<T>(i.OldItems, i.NewItems));
    }

    private void OnCleared(ItemsClearedEventArgs<T> i)
    {
        if (this.ItemsCleared != null) this.ItemsCleared(this, new ItemsClearedEventArgs<T>(i.OldItems));
    }

    private void OnReplaced(CollectionReplacedEventArgs<T> i)
    {
        if (this.CollectionReplaced != null) this.CollectionReplaced(this, new CollectionReplacedEventArgs<T>(i.OldItems, i.NewItems));
    }

    #endregion

    #region RangeCollection

    /// <summary> 
    /// Initializes a new instance. 
    /// </summary> 
    public RangeCollection() : base() { }

    /// <summary> 
    /// Initializes a new instance from specified enumerable. 
    /// </summary> 
    public RangeCollection(IEnumerable<T> Collection) : base(Collection) { }

    /// <summary> 
    /// Initializes a new instance from specified list.
    /// </summary> 
    public RangeCollection(List<T> List) : base(List) { }

    /// <summary>
    /// Initializes a new instance with variable T.
    /// </summary>
    public RangeCollection(params T[] Items) : base()
    {
        this.AddRange(Items);
    }

    /// <summary>
    /// Initializes a new instance with variable enumerable.
    /// </summary>
    public RangeCollection(params IEnumerable<T>[] Items) : base()
    {
        this.AddRange(Items);
    }

    #endregion
}

Events Classes:

public class CollectionReplacedEventArgs<T> : ReplacedEventArgs<T>
{
    public CollectionReplacedEventArgs(IEnumerable<T> Old, IEnumerable<T> New) : base(Old, New) { }
}

public class ItemAddedEventArgs<T> : EventArgs
{
    public T NewItem;
    public ItemAddedEventArgs(T t)
    {
        this.NewItem = t;
    }
}

public class ItemInsertedEventArgs<T> : EventArgs
{
    public int Index;
    public T NewItem;
    public ItemInsertedEventArgs(T t, int i)
    {
        this.NewItem = t;
        this.Index = i;
    }
}

public class ItemRemovedEventArgs<T> : EventArgs
{
    public T OldItem;
    public ItemRemovedEventArgs(T t)
    {
        this.OldItem = t;
    }
}

public class ItemReplacedEventArgs<T> : EventArgs
{
    public T OldItem;
    public T NewItem;
    public ItemReplacedEventArgs(T Old, T New)
    {
        this.OldItem = Old;
        this.NewItem = New;
    }
}

public class ItemsAddedEventArgs<T> : EventArgs
{
    public IEnumerable<T> NewItems;
    public ItemsAddedEventArgs(IEnumerable<T> t)
    {
        this.NewItems = t;
    }
}

public class ItemsClearedEventArgs<T> : RemovedEventArgs<T>
{
    public ItemsClearedEventArgs(IEnumerable<T> Old) : base(Old) { }
}

public class ItemsRemovedEventArgs<T> : RemovedEventArgs<T>
{
    public ItemsRemovedEventArgs(IEnumerable<T> Old) : base(Old) { }
}

public class ItemsReplacedEventArgs<T> : ReplacedEventArgs<T>
{
    public ItemsReplacedEventArgs(IEnumerable<T> Old, IEnumerable<T> New) : base(Old, New) { }
}

public class RemovedEventArgs<T> : EventArgs
{
    public IEnumerable<T> OldItems;
    public RemovedEventArgs(IEnumerable<T> Old)
    {
        this.OldItems = Old;
    }
}

public class ReplacedEventArgs<T> : EventArgs
{
    public IEnumerable<T> OldItems;
    public IEnumerable<T> NewItems;
    public ReplacedEventArgs(IEnumerable<T> Old, IEnumerable<T> New)
    {
        this.OldItems = Old;
        this.NewItems = New;
    }
}

Note: I did not manually raise OnCollectionChanged in the base methods because it appears only to be possible to create a CollectionChangedEventArgs using the Reset action. If you try to raise OnCollectionChanged using Reset for a single item change, your items control will appear to flicker, which is something you want to avoid.

End-line characters from lines read from text file, using Python

You may also consider using line.rstrip() to remove the whitespaces at the end of your line.

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

I was facing a similar issue and below line fixed the issue for me.

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
    </dependency>

Edit: I realized that I was using spring boot and the version of the dependency was getting pulled from spring-boot-starter-parent.

Mailto links do nothing in Chrome but work in Firefox?

Fix that worked for me since my Protocol handlers was empty

https://productforums.google.com/forum/#!topic/gmail/CQMCGRvyhCM

See redfish43 reply , to sum up

For mailto: - Make sure you are logged in to Gmail and the active window is your main Gmail page (or nothing will happen). - Copy/paste this into the address bar:

javascript:navigator.registerProtocolHandler("mailto","https://mail.google.com/mail/?extsrc=mailto&url=%s","Gmail")

Add the javascript: to the front again if needed, because when you pasted it, Chrome probably trimmed everything before and including the colon. Then hit enter.

When popup window opens click on "Allow"

I want to exception handle 'list index out of range.'

For anyone interested in a shorter way:

gotdata = len(dlist)>1 and dlist[1] or 'null'

But for best performance, I suggest using False instead of 'null', then a one line test will suffice:

gotdata = len(dlist)>1 and dlist[1]

Angular 2 Dropdown Options Default Value

Add this Code at o position of the select list.

<option [ngValue]="undefined" selected>Select</option>

VirtualBox error "Failed to open a session for the virtual machine"

try this

sudo update-secureboot-policy --enroll-key

and restart your system, when restart it shows option and select Mok key and you will work fine.

Fatal error: Call to a member function prepare() on null

You can try/catch PDOExceptions (your configs could differ but the important part is the try/catch):

try {
        $dbh = new PDO(
            DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_PERSISTENT            => true,
                PDO::ATTR_ERRMODE               => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND    => 'SET NAMES ' . DB_CHARSET . ' COLLATE ' . DB_COLLATE

            ]
        );
    } catch ( PDOException $e ) {
        echo 'ERROR!';
        print_r( $e );
    }

The print_r( $e ); line will show you everything you need, for example I had a recent case where the error message was like unknown database 'my_db'.

What are the differences between virtual memory and physical memory?

See here: Physical Vs Virtual Memory

Virtual memory is stored on the hard drive and is used when the RAM is filled. Physical memory is limited to the size of the RAM chips installed in the computer. Virtual memory is limited by the size of the hard drive, so virtual memory has the capability for more storage.

git: fatal: I don't handle protocol '??http'

The solution is very simple:

1- Copy your git path. forexample : http://github.com/yourname/my-git-project.git

2- Open notepad and Paste it. Then copy the path from notepad.

3- paste the path to command line

thats it.

How to list all the files in a commit?

I'll just assume that gitk is not desired for this. In that case, try git show --name-only <sha>.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

try this code it might be useful -

<%# ((DataBinder.Eval(Container.DataItem,"ImageFilename").ToString()=="") ? "" :"<a
 href="+DataBinder.Eval(Container.DataItem, "link")+"><img
 src='/Images/Products/"+DataBinder.Eval(Container.DataItem,
 "ImageFilename")+"' border='0' /></a>")%>

close vs shutdown socket?

Close

When you have finished using a socket, you can simply close its file descriptor with close; If there is still data waiting to be transmitted over the connection, normally close tries to complete this transmission. You can control this behavior using the SO_LINGER socket option to specify a timeout period; see Socket Options.

ShutDown

You can also shut down only reception or transmission on a connection by calling shutdown.

The shutdown function shuts down the connection of socket. Its argument how specifies what action to perform: 0 Stop receiving data for this socket. If further data arrives, reject it. 1 Stop trying to transmit data from this socket. Discard any data waiting to be sent. Stop looking for acknowledgement of data already sent; don’t retransmit it if it is lost. 2 Stop both reception and transmission.

The return value is 0 on success and -1 on failure.

Get key and value of object in JavaScript?

$.each(top_brands, function() {
  var key = Object.keys(this)[0];
  var value = this[key];
  brand_options.append($("<option />").val(key).text(key + " "  + value));
});

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

If you use Linux or Mac, even you can also run in ssh terminal. You can use terminal for run this command,

 php artisan cache:clear 
 sudo chmod -R 777 storage
 composer dump-autoload

If you are using windows, you can run using git bash.

 php artisan cache:clear 
 chmod -R 777 storage
 composer dump-autoload

You can download git form https://git-scm.com/downloads.

Convert string to decimal number with 2 decimal places in Java

I just want to be sure that the float number will also have 2 decimal places after converting that string.

You can't, because floating point numbers don't have decimal places. They have binary places, which aren't commensurate with decimal places.

If you want decimal places, use a decimal radix.

Should functions return null or an empty object?

I typically return null. It provides a quick and easy mechanism to detect if something screwed up without throwing exceptions and using tons of try/catch all over the place.

Safest way to convert float to integer in python?

df['Column_Name']=df['Column_Name'].astype(int)

Visual Studio breakpoints not being hit

One of my projects in my solution was set to Release mode. I changed it back to Debug mode, and the breakpoints are hitting now.

Unmarshaling nested JSON objects

Yes. With gjson all you have to do now is:

bar := gjson.Get(json, "foo.bar")

bar could be a struct property if you like. Also, no maps.

How to get the focused element with jQuery?

Try this::

$(document).on("click",function(){
    alert(event.target);
    });

CSS display:table-row does not expand when width is set to 100%

Note that according to the CSS3 spec, you do NOT have to wrap your layout in a table-style element. The browser will infer the existence of containing elements if they do not exist.

How do I mount a host directory as a volume in docker compose

There are a few options

Short Syntax

Using the host : guest format you can do any of the following:

volumes:
  # Just specify a path and let the Engine create a volume
  - /var/lib/mysql

  # Specify an absolute path mapping
  - /opt/data:/var/lib/mysql

  # Path on the host, relative to the Compose file
  - ./cache:/tmp/cache

  # User-relative path
  - ~/configs:/etc/configs/:ro

  # Named volume
  - datavolume:/var/lib/mysql

Long Syntax

As of docker-compose v3.2 you can use long syntax which allows the configuration of additional fields that can be expressed in the short form such as mount type (volume, bind or tmpfs) and read_only.

version: "3.2"
services:
  web:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - type: volume
        source: mydata
        target: /data
        volume:
          nocopy: true
      - type: bind
        source: ./static
        target: /opt/app/static

networks:
  webnet:

volumes:
  mydata:

Check out https://docs.docker.com/compose/compose-file/#long-syntax-3 for more info.

How to Read and Write from the Serial Port

I spent a lot of time to use SerialPort class and has concluded to use SerialPort.BaseStream class instead. You can see source code: SerialPort-source and SerialPort.BaseStream-source for deep understanding. I created and use code that shown below.

  • The core function public int Recv(byte[] buffer, int maxLen) has name and works like "well known" socket's recv().

  • It means that

    • in one hand it has timeout for no any data and throws TimeoutException.
    • In other hand, when any data has received,
      • it receives data either until maxLen bytes
      • or short timeout (theoretical 6 ms) in UART data flow

.

public class Uart : SerialPort

    {
        private int _receiveTimeout;

        public int ReceiveTimeout { get => _receiveTimeout; set => _receiveTimeout = value; }

        static private string ComPortName = "";

        /// <summary>
        /// It builds PortName using ComPortNum parameter and opens SerialPort.
        /// </summary>
        /// <param name="ComPortNum"></param>
        public Uart(int ComPortNum) : base()
        {
            base.BaudRate = 115200; // default value           
            _receiveTimeout = 2000;
            ComPortName = "COM" + ComPortNum;

            try
            {
                base.PortName = ComPortName;
                base.Open();
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Error: Port {0} is in use", ComPortName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Uart exception: " + ex);
            }
        } //Uart()

        /// <summary>
        /// Private property returning positive only Environment.TickCount
        /// </summary>
        private int _tickCount { get => Environment.TickCount & Int32.MaxValue; }


        /// <summary>
        /// It uses SerialPort.BaseStream rather SerialPort functionality .
        /// It Receives up to maxLen number bytes of data, 
        /// Or throws TimeoutException if no any data arrived during ReceiveTimeout. 
        /// It works likes socket-recv routine (explanation in body).
        /// Returns:
        ///    totalReceived - bytes, 
        ///    TimeoutException,
        ///    -1 in non-ComPortNum Exception  
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="maxLen"></param>
        /// <returns></returns>
        public int Recv(byte[] buffer, int maxLen)
        {
            /// The routine works in "pseudo-blocking" mode. It cycles up to first 
            /// data received using BaseStream.ReadTimeout = TimeOutSpan (2 ms).
            /// If no any message received during ReceiveTimeout property, 
            /// the routine throws TimeoutException 
            /// In other hand, if any data has received, first no-data cycle
            /// causes to exit from routine.

            int TimeOutSpan = 2;
            // counts delay in TimeOutSpan-s after end of data to break receive
            int EndOfDataCnt;
            // pseudo-blocking timeout counter
            int TimeOutCnt = _tickCount + _receiveTimeout; 
            //number of currently received data bytes
            int justReceived = 0;
            //number of total received data bytes
            int totalReceived = 0;

            BaseStream.ReadTimeout = TimeOutSpan;
            //causes (2+1)*TimeOutSpan delay after end of data in UART stream
            EndOfDataCnt = 2;
            while (_tickCount < TimeOutCnt && EndOfDataCnt > 0)
            {
                try
                {
                    justReceived = 0; 
                    justReceived = base.BaseStream.Read(buffer, totalReceived, maxLen - totalReceived);
                    totalReceived += justReceived;

                    if (totalReceived >= maxLen)
                        break;
                }
                catch (TimeoutException)
                {
                    if (totalReceived > 0) 
                        EndOfDataCnt--;
                }
                catch (Exception ex)
                {                   
                    totalReceived = -1;
                    base.Close();
                    Console.WriteLine("Recv exception: " + ex);
                    break;
                }

            } //while
            if (totalReceived == 0)
            {              
                throw new TimeoutException();
            }
            else
            {               
                return totalReceived;
            }
        } // Recv()            
    } // Uart

How to import large sql file in phpmyadmin

Ok you use PHPMyAdmin but sometimes the best way is through terminal:

  • Connect to database: mysql -h localhost -u root -p (switch root and localhost for user and database location)
  • Start import from dump: \. /path/to/your/file.sql
  • Go take a coffe and brag about yourself because you use terminal.

And that's it. Just remember if you are in a remote server, you must upload the .sql file to some folder.

How can I create C header files

  1. Open your favorite text editor
  2. Create a new file named whatever.h
  3. Put your function prototypes in it

DONE.

Example whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once but it is not guaranteed to be supported on every compiler.

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.

Like this:

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it (if you use GCC):

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

You can test sample:

$ ./sample
3
$

Is it possible to set a custom font for entire of application?

As of Android O this is now possible to define directly from the XML and my bug is now closed!

See here for details

TL;DR:

First you must add your fonts to the project

Second you add a font family, like so:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>

Finally, you can use the font in a layout or style:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/lobster"/>

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/lobster</item>
</style>

Enjoy!

How do I use reflection to invoke a private method?

Microsoft recently modified the reflection API rendering most of these answers obsolete. The following should work on modern platforms (including Xamarin.Forms and UWP):

obj.GetType().GetTypeInfo().GetDeclaredMethod("MethodName").Invoke(obj, yourArgsHere);

Or as an extension method:

public static object InvokeMethod<T>(this T obj, string methodName, params object[] args)
{
    var type = typeof(T);
    var method = type.GetTypeInfo().GetDeclaredMethod(methodName);
    return method.Invoke(obj, args);
}

Note:

  • If the desired method is in a superclass of obj the T generic must be explicitly set to the type of the superclass.

  • If the method is asynchronous you can use await (Task) obj.InvokeMethod(…).

How to call Stored Procedure in a View?

I was able to call stored procedure in a view (SQL Server 2005).

CREATE FUNCTION [dbo].[dimMeasure] 
   RETURNS  TABLE  AS

    (
     SELECT * FROM OPENROWSET('SQLNCLI', 'Server=localhost; Trusted_Connection=yes;', 'exec ceaw.dbo.sp_dimMeasure2')
    )
RETURN
GO

Inside stored procedure we need to set:

set nocount on
SET FMTONLY OFF
CREATE VIEW [dbo].[dimMeasure]
AS

SELECT * FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;', 'exec ceaw.dbo.sp_dimMeasure2')

GO

What steps are needed to stream RTSP from FFmpeg?

FWIW, I was able to setup a local RTSP server for testing purposes using simple-rtsp-server and ffmpeg following these steps:

  1. Create a configuration file for the RTSP server called rtsp-simple-server.yml with this single line:
    protocols: [tcp]
    
  2. Start the RTSP server as a Docker container:
    $ docker run --rm -it -v $PWD/rtsp-simple-server.yml:/rtsp-simple-server.yml -p 8554:8554 aler9/rtsp-simple-server
    
  3. Use ffmpeg to stream a video file (looping forever) to the server:
    $ ffmpeg -re -stream_loop -1 -i test.mp4 -f rtsp -rtsp_transport tcp rtsp://localhost:8554/live.stream
    

Once you have that running you can use ffplay to view the stream:

$ ffplay -rtsp_transport tcp rtsp://localhost:8554/live.stream

Note that simple-rtsp-server can also handle UDP streams (i.s.o. TCP) but that's tricky running the server as a Docker container.

Test credit card numbers for use with PayPal sandbox

A bit late in the game but just in case it helps anyone.

If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).

The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.

I got the url above from PayPal's tech support.

Tested using a simple Hosted button and IPN. Good luck.

How To limit the number of characters in JTextField?

Just put this code in KeyTyped event:

    if ((jtextField.getText() + evt.getKeyChar()).length() > 20) {
        evt.consume();
    }

Where "20" is the maximum number of characters that you want.

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

You have to create a variable of the type of the class, and set it equal to a new instance of the object first.

GradeBook myGradeBook = new GradeBook();

Then call the method on the obect you just created.

myGradeBook.[method you want called]

How to validate phone numbers using regex

For anyone interested in doing something similar with Irish mobile phone numbers, here's a straightforward way of accomplishing it:

http://ilovenicii.com/?p=87

PHP


<?php
$pattern = "/^(083|086|085|086|087)\d{7}$/";
$phone = "087343266";

if (preg_match($pattern,$phone)) echo "Match";
else echo "Not match";

There is also a JQuery solution on that link.

EDIT:

jQuery solution:

    $(function(){
    //original field values
    var field_values = {
            //id        :  value
            'url'       : 'url',
            'yourname'  : 'yourname',
            'email'     : 'email',
            'phone'     : 'phone'
    };

        var url =$("input#url").val();
        var yourname =$("input#yourname").val();
        var email =$("input#email").val();
        var phone =$("input#phone").val();


    //inputfocus
    $('input#url').inputfocus({ value: field_values['url'] });
    $('input#yourname').inputfocus({ value: field_values['yourname'] });
    $('input#email').inputfocus({ value: field_values['email'] }); 
    $('input#phone').inputfocus({ value: field_values['phone'] });



    //reset progress bar
    $('#progress').css('width','0');
    $('#progress_text').html('0% Complete');

    //first_step
    $('form').submit(function(){ return false; });
    $('#submit_first').click(function(){
        //remove classes
        $('#first_step input').removeClass('error').removeClass('valid');

        //ckeck if inputs aren't empty
        var fields = $('#first_step input[type=text]');
        var error = 0;
        fields.each(function(){
            var value = $(this).val();
            if( value.length<12 || value==field_values[$(this).attr('id')] ) {
                $(this).addClass('error');
                $(this).effect("shake", { times:3 }, 50);

                error++;
            } else {
                $(this).addClass('valid');
            }
        });        

        if(!error) {
            if( $('#password').val() != $('#cpassword').val() ) {
                    $('#first_step input[type=password]').each(function(){
                        $(this).removeClass('valid').addClass('error');
                        $(this).effect("shake", { times:3 }, 50);
                    });

                    return false;
            } else {   
                //update progress bar
                $('#progress_text').html('33% Complete');
                $('#progress').css('width','113px');

                //slide steps
                $('#first_step').slideUp();
                $('#second_step').slideDown();     
            }               
        } else return false;
    });

    //second section
    $('#submit_second').click(function(){
        //remove classes
        $('#second_step input').removeClass('error').removeClass('valid');

        var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
        var fields = $('#second_step input[type=text]');
        var error = 0;
        fields.each(function(){
            var value = $(this).val();
            if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) {
                $(this).addClass('error');
                $(this).effect("shake", { times:3 }, 50);

                error++;
            } else {
                $(this).addClass('valid');
            }


        function validatePhone(phone) {
        var a = document.getElementById(phone).value;
        var filter = /^[0-9-+]+$/;
            if (filter.test(a)) {
                return true;
            }
            else {
                return false;
            }
        }

        $('#phone').blur(function(e) {
            if (validatePhone('txtPhone')) {
                $('#spnPhoneStatus').html('Valid');
                $('#spnPhoneStatus').css('color', 'green');
            }
            else {
                $('#spnPhoneStatus').html('Invalid');
            $('#spnPhoneStatus').css('color', 'red');
            }
        });

     });

        if(!error) {
                //update progress bar
                $('#progress_text').html('66% Complete');
                $('#progress').css('width','226px');

                //slide steps
                $('#second_step').slideUp();
                $('#fourth_step').slideDown();     
        } else return false;

    });


    $('#submit_second').click(function(){
        //update progress bar
        $('#progress_text').html('100% Complete');
        $('#progress').css('width','339px');

        //prepare the fourth step
        var fields = new Array(
            $('#url').val(),
            $('#yourname').val(),
            $('#email').val(),
            $('#phone').val()

        );
        var tr = $('#fourth_step tr');
        tr.each(function(){
            //alert( fields[$(this).index()] )
            $(this).children('td:nth-child(2)').html(fields[$(this).index()]);
        });

        //slide steps
        $('#third_step').slideUp();
        $('#fourth_step').slideDown();            
    });


    $('#submit_fourth').click(function(){

        url =$("input#url").val();
        yourname =$("input#yourname").val();
        email =$("input#email").val();
        phone =$("input#phone").val();

        //send information to server
        var dataString = 'url='+ url + '&yourname=' + yourname + '&email=' + email + '&phone=' + phone;  



        alert (dataString);//return false;  
            $.ajax({  
                type: "POST",  
                url: "http://clients.socialnetworkingsolutions.com/infobox/contact/",  
                data: "url="+url+"&yourname="+yourname+"&email="+email+'&phone=' + phone,
                cache: false,
                success: function(data) {  
                    console.log("form submitted");
                    alert("success");
                }
                });  
        return false;

   });


    //back button
    $('.back').click(function(){
        var container = $(this).parent('div'),
        previous  = container.prev();

        switch(previous.attr('id')) {
            case 'first_step' : $('#progress_text').html('0% Complete');
                  $('#progress').css('width','0px');
                       break;
            case 'second_step': $('#progress_text').html('33% Complete');
                  $('#progress').css('width','113px');
                       break;

            case 'third_step' : $('#progress_text').html('66% Complete');
                  $('#progress').css('width','226px');
                       break;

        default: break;
    }

    $(container).slideUp();
    $(previous).slideDown();
});


});

Source.

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

Turn On "Access for less secure apps" in Security setting for the gmail account.(from mail), see the below link for references

http://www.ghacks.net/2014/07/21/gmail-starts-block-less-secure-apps-enable-access/

MySQL trigger if condition exists

Try to do...

 DELIMITER $$
        CREATE TRIGGER aumentarsalario 
        BEFORE INSERT 
        ON empregados
        FOR EACH ROW
        BEGIN
          if (NEW.SALARIO < 900) THEN 
             set NEW.SALARIO = NEW.SALARIO + (NEW.SALARIO * 0.1);
          END IF;
        END $$
  DELIMITER ;

How to append binary data to a buffer in node.js

Buffers are always of fixed size, there is no built in way to resize them dynamically, so your approach of copying it to a larger Buffer is the only way.

However, to be more efficient, you could make the Buffer larger than the original contents, so it contains some "free" space where you can add data without reallocating the Buffer. That way you don't need to create a new Buffer and copy the contents on each append operation.

How to access parameters in a Parameterized Build?

I tried a few of the solutions from this thread. It seemed to work, but my values were always true and I also encountered the following issue: JENKINS-40235

I managed to use parameters in groovy jenkinsfile using the following syntax: params.myVariable

Here's a working example:

Solution

print 'DEBUG: parameter isFoo = ' + params.isFoo
print "DEBUG: parameter isFoo = ${params.isFoo}"

A more detailed (and working) example:

node() {
   // adds job parameters within jenkinsfile
   properties([
     parameters([
       booleanParam(
         defaultValue: false,
         description: 'isFoo should be false',
         name: 'isFoo'
       ),
       booleanParam(
         defaultValue: true,
         description: 'isBar should be true',
         name: 'isBar'
       ),
     ])
   ])

   // test the false value
   print 'DEBUG: parameter isFoo = ' + params.isFoo
   print "DEBUG: parameter isFoo = ${params.isFoo}"
   sh "echo sh isFoo is ${params.isFoo}"
   if (params.isFoo) { print "THIS SHOULD NOT DISPLAY" }

   // test the true value
   print 'DEBUG: parameter isBar = ' + params.isBar
   print "DEBUG: parameter isBar = ${params.isBar}"
   sh "echo sh isBar is ${params.isBar}"
   if (params.isBar) { print "this should display" }
}

Output

[Pipeline] {
[Pipeline] properties
WARNING: The properties step will remove all JobPropertys currently configured in this job, either from the UI or from an earlier properties step.
This includes configuration for discarding old builds, parameters, concurrent builds and build triggers.
WARNING: Removing existing job property 'This project is parameterized'
WARNING: Removing existing job property 'Build triggers'
[Pipeline] echo
DEBUG: parameter isFoo = false
[Pipeline] echo
DEBUG: parameter isFoo = false
[Pipeline] sh
[wegotrade-test-job] Running shell script
+ echo sh isFoo is false
sh isFoo is false
[Pipeline] echo
DEBUG: parameter isBar = true
[Pipeline] echo
DEBUG: parameter isBar = true
[Pipeline] sh
[wegotrade-test-job] Running shell script
+ echo sh isBar is true
sh isBar is true
[Pipeline] echo
this should display
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

I sent a Pull Request to update the misleading pipeline tutorial#build-parameters quote that says "they are accessible as Groovy variables of the same name.". ;)

Edit: As Jesse Glick pointed out: Release notes go into more details

You should also update the Pipeline Job Plugin to 2.7 or later, so that build parameters are defined as environment variables and thus accessible as if they were global Groovy variables.

How to force JS to do math instead of putting two strings together

the simplest:

dots = dots*1+5;

the dots will be converted to number.

Conditional Formatting (IF not empty)

You can use Conditional formatting with the option "Formula Is". One possible formula is

=NOT(ISBLANK($B1))

enter image description here

Another possible formula is

=$B1<>""

enter image description here

If hasClass then addClass to parent

Alternatively you could use:

if ($('#navigation a').is(".active")) {
    $(this).parent().addClass("active");
}

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

How to modify a text file?

Rewriting a file in place is often done by saving the old copy with a modified name. Unix folks add a ~ to mark the old one. Windows folks do all kinds of things -- add .bak or .old -- or rename the file entirely or put the ~ on the front of the name.

import shutil
shutil.move( afile, afile+"~" )

destination= open( aFile, "w" )
source= open( aFile+"~", "r" )
for line in source:
    destination.write( line )
    if <some condition>:
        destination.write( >some additional line> + "\n" )
source.close()
destination.close()

Instead of shutil, you can use the following.

import os
os.rename( aFile, aFile+"~" )

Searching for Text within Oracle Stored Procedures

I allways use UPPER(text) like UPPER('%blah%')

How do I force detach Screen from another SSH session?

As Jose answered, screen -d -r should do the trick. This is a combination of two commands, as taken from the man page.

screen -d detaches the already-running screen session, and screen -r reattaches the existing session. By running screen -d -r, you force screen to detach it and then resume the session.

If you use the capital -D -RR, I quote the man page because it's too good to pass up.

Attach here and now. Whatever that means, just do it.

Note: It is always a good idea to check the status of your sessions by means of "screen -list".

What is special about /dev/tty?

The 'c' means it's a character device. tty is a special file representing the 'controlling terminal' for the current process.

Character Devices

Unix supports 'device files', which aren't really files at all, but file-like access points to hardware devices. A 'character' device is one which is interfaced byte-by-byte (as opposed to buffered IO).

TTY

/dev/tty is a special file, representing the terminal for the current process. So, when you echo 1 > /dev/tty, your message ('1') will appear on your screen. Likewise, when you cat /dev/tty, your subsequent input gets duplicated (until you press Ctrl-C).

/dev/tty doesn't 'contain' anything as such, but you can read from it and write to it (for what it's worth). I can't think of a good use for it, but there are similar files which are very useful for simple IO operations (e.g. /dev/ttyS0 is normally your serial port)

This quote is from http://tldp.org/HOWTO/Text-Terminal-HOWTO-7.html#ss7.3 :

/dev/tty stands for the controlling terminal (if any) for the current process. To find out which tty's are attached to which processes use the "ps -a" command at the shell prompt (command line). Look at the "tty" column. For the shell process you're in, /dev/tty is the terminal you are now using. Type "tty" at the shell prompt to see what it is (see manual pg. tty(1)). /dev/tty is something like a link to the actually terminal device name with some additional features for C-programmers: see the manual page tty(4).

Here is the man page: http://linux.die.net/man/4/tty

Constructor in an Interface?

This is because interfaces do not allow to define the method body in it.but we should have to define the constructor in the same class as interfaces have by default abstract modifier for all the methods to define. That's why we can not define constructor in the interfaces.

How do you open an SDF file (SQL Server Compact Edition)?

Try the sql server management studio (version 2008 or earlier) from Microsoft. Download it from here. Not sure about the license, but it seems to be free if you download the EXPRESS EDITION.

You might also be able to use later editions of SSMS. For 2016, you will need to install an extension.

If you have the option you can copy the sdf file to a different machine which you are allowed to pollute with additional software.

Update: comment from Nick Westgate in nice formatting

The steps are not all that intuitive:

  1. Open SQL Server Management Studio, or if it's running select File -> Connect Object Explorer...
  2. In the Connect to Server dialog change Server type to SQL Server Compact Edition
  3. From the Database file dropdown select < Browse for more...>
  4. Open your SDF file.

Convert hex to binary

a = raw_input('hex number\n')
length = len(a)
ab = bin(int(a, 16))[2:]
while len(ab)<(length * 4):
    ab = '0' + ab
print ab

Converting Pandas dataframe into Spark dataframe error

I have tried this with your data and it is working :

%pyspark
import pandas as pd
from pyspark.sql import SQLContext
print sc
df = pd.read_csv("test.csv")
print type(df)
print df
sqlCtx = SQLContext(sc)
sqlCtx.createDataFrame(df).show()

How to select rows from a DataFrame based on column values

To append to this famous question (though a bit too late): You can also do df.groupby('column_name').get_group('column_desired_value').reset_index() to make a new data frame with specified column having a particular value. E.g.

import pandas as pd
df = pd.DataFrame({'A': 'foo bar foo bar foo bar foo foo'.split(),
                   'B': 'one one two three two two one three'.split()})
print("Original dataframe:")
print(df)

b_is_two_dataframe = pd.DataFrame(df.groupby('B').get_group('two').reset_index()).drop('index', axis = 1) 
#NOTE: the final drop is to remove the extra index column returned by groupby object
print('Sub dataframe where B is two:')
print(b_is_two_dataframe)

Run this gives:

Original dataframe:
     A      B
0  foo    one
1  bar    one
2  foo    two
3  bar  three
4  foo    two
5  bar    two
6  foo    one
7  foo  three
Sub dataframe where B is two:
     A    B
0  foo  two
1  foo  two
2  bar  two

How do I add a new class to an element dynamically?

Since everyone has given you jQuery/JS answers to this, I will provide an additional solution. The answer to your question is still no, but using LESS (a CSS Pre-processor) you can do this easily.

.first-class {
  background-color: yellow;
}
.second-class:hover {
  .first-class;
}

Quite simply, any time you hover over .second-class it will give it all the properties of .first-class. Note that it won't add the class permanently, just on hover. You can learn more about LESS here: Getting Started with LESS

Here is a SASS way to do it as well:

.first-class {
  background-color: yellow;
}
.second-class {
  &:hover {
    @extend .first-class;
  }
}

StringStream in C#

I see a lot of good answers here, but none that directly address the lack of a StringStream class in C#. So I have written one of my own...

public class StringStream : Stream
{
    private readonly MemoryStream _memory;
    public StringStream(string text)
    {
        _memory = new MemoryStream(Encoding.UTF8.GetBytes(text));
    }
    public StringStream()
    {
        _memory = new MemoryStream();
    }
    public StringStream(int capacity)
    {
        _memory = new MemoryStream(capacity);
    }
    public override void Flush()
    {
        _memory.Flush();
    }
    public override int Read(byte[] buffer, int offset, int count)
    {
        return  _memory.Read(buffer, offset, count);
    }
    public override long Seek(long offset, SeekOrigin origin)
    {
        return _memory.Seek(offset, origin);
    }
    public override void SetLength(long value)
    {
        _memory.SetLength(value);
    }
    public override void Write(byte[] buffer, int offset, int count)
    {
        _memory.Write(buffer, offset, count);
        return;
    }
    public override bool CanRead => _memory.CanRead;
    public override bool CanSeek => _memory.CanSeek;
    public override bool CanWrite => _memory.CanWrite;
    public override long Length =>  _memory.Length;
    public override long Position
    {
        get => _memory.Position;
        set => _memory.Position = value;
    }
    public override string ToString()
    {
        return System.Text.Encoding.UTF8.GetString(_memory.GetBuffer(), 0, (int) _memory.Length);
    }
    public override int ReadByte()
    {
        return _memory.ReadByte();
    }
    public override void WriteByte(byte value)
    {
        _memory.WriteByte(value);
    }
}

An example of its use...

        string s0 =
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor\r\n" +
            "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud\r\n" +
            "exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\r\n" +
            "in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint\r\n" +
            "occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\r\n";
        StringStream ss0 = new StringStream(s0);
        StringStream ss1 = new StringStream();
        int line = 1;
        Console.WriteLine("Contents of input stream: ");
        Console.WriteLine();
        using (StreamReader reader = new StreamReader(ss0))
        {
            using (StreamWriter writer = new StreamWriter(ss1))
            {
                while (!reader.EndOfStream)
                {
                    string s = reader.ReadLine();
                    Console.WriteLine("Line " + line++ + ": " + s);
                    writer.WriteLine(s);
                }
            }
        }

        Console.WriteLine();
        Console.WriteLine("Contents of output stream: ");
        Console.WriteLine();
        Console.Write(ss1.ToString());

What does an exclamation mark before a cell reference mean?

When entered as the reference of a Named range, it refers to range on the sheet the named range is used on.

For example, create a named range MyName refering to =SUM(!B1:!K1)

Place a formula on Sheet1 =MyName. This will sum Sheet1!B1:K1

Now place the same formula (=MyName) on Sheet2. That formula will sum Sheet2!B1:K1

Note: (as pnuts commented) this and the regular SheetName!B1:K1 format are relative, so reference different cells as the =MyName formula is entered into different cells.

How to get a index value from foreach loop in jstl

I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.

It can use for use to read for Zeor base index or 1 one base index.

${loop.count}` it will give 1 starting base index.

${loop.index} it will give 0 base index as normal Index of array start from 0.

For Example :

<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
   <source srcset="${currentImage}" media="(min-width: 1000px)"></source>
   <source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
   <img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>

For more Info please refer this link

Aborting a stash pop in Git

I solved this in a somewhat different way. Here's what happened.

First, I popped on the wrong branch and got conflicts. The stash remained intact but the index was in conflict resolution, blocking many commands.

A simple git reset HEAD aborted the conflict resolution and left the uncommitted (and UNWANTED) changes.

Several git co <filename> reverted the index to the initial state. Finally, I switched branch with git co <branch-name> and run a new git stash pop, which resolved without conflicts.

Using HTML5/JavaScript to generate and save a file

As previously mentioned the File API, along with the FileWriter and FileSystem APIs can be used to store files on a client's machine from the context of a browser tab/window.

However, there are several things pertaining to latter two APIs which you should be aware of:

  • Implementations of the APIs currently exist only in Chromium-based browsers (Chrome & Opera)
  • Both of the APIs were taken off of the W3C standards track on April 24, 2014, and as of now are proprietary
  • Removal of the (now proprietary) APIs from implementing browsers in the future is a possibility
  • A sandbox (a location on disk outside of which files can produce no effect) is used to store the files created with the APIs
  • A virtual file system (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser) is used represent the files created with the APIs

Here are simple examples of how the APIs are used, directly and indirectly, in tandem to do this:

BakedGoods*

bakedGoods.get({
        data: ["testFile"],
        storageTypes: ["fileSystem"],
        options: {fileSystem:{storageType: Window.PERSISTENT}},
        complete: function(resultDataObj, byStorageTypeErrorObj){}
});

Using the raw File, FileWriter, and FileSystem APIs

function onQuotaRequestSuccess(grantedQuota)
{

    function saveFile(directoryEntry)
    {

        function createFileWriter(fileEntry)
        {

            function write(fileWriter)
            {
                var dataBlob = new Blob(["Hello world!"], {type: "text/plain"});
                fileWriter.write(dataBlob);              
            }

            fileEntry.createWriter(write);
        }

        directoryEntry.getFile(
            "testFile", 
            {create: true, exclusive: true},
            createFileWriter
        );
    }

    requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}

var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);

Though the FileSystem and FileWriter APIs are no longer on the standards track, their use can be justified in some cases, in my opinion, because:

  • Renewed interest from the un-implementing browser vendors may place them right back on it
  • Market penetration of implementing (Chromium-based) browsers is high
  • Google (the main contributer to Chromium) has not given and end-of-life date to the APIs

Whether "some cases" encompasses your own, however, is for you to decide.

*BakedGoods is maintained by none other than this guy right here :)

Vue Js - Loop via v-for X times (in a range)

You can use the native JS slice method:

<div v-for="item in shoppingItems.slice(0,10)">

The slice() method returns the selected elements in an array, as a new array object.

Based on tip in the migration guide: https://vuejs.org/v2/guide/migration.html#Replacing-the-limitBy-Filter

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

How to convert a .eps file to a high quality 1024x1024 .jpg?

Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.

JavaScript override methods

_x000D_
_x000D_
function A() {_x000D_
    var c = new C();_x000D_
 c.modify = function(){_x000D_
  c.x = 123;_x000D_
  c.y = 333;_x000D_
 }_x000D_
 c.sum();_x000D_
}_x000D_
_x000D_
function B() {_x000D_
    var c = new C();_x000D_
 c.modify = function(){_x000D_
  c.x = 999;_x000D_
  c.y = 333;_x000D_
 }_x000D_
 c.sum();_x000D_
}_x000D_
_x000D_
_x000D_
C = function () {_x000D_
   this.x = 10;_x000D_
   this.y = 20;_x000D_
_x000D_
   this.modify = function() {_x000D_
      this.x = 30;_x000D_
      this.y = 40;_x000D_
   };_x000D_
   _x000D_
   this.sum = function(){_x000D_
 this.modify();_x000D_
 console.log("The sum is: " + (this.x+this.y));_x000D_
   }_x000D_
}_x000D_
_x000D_
A();_x000D_
B();
_x000D_
_x000D_
_x000D_

ADB Driver and Windows 8.1

There is lots of stuff on this topic, each slightly different. Like many users I spent hours trying them and got nowhere. In the end, this is what worked for me - I.e. installed the driver on windows 8.1

In my extras/google/usb_driver is a file android_winusb.inf

I double clicked on this and it "ran" and installed the driver.

I can't explain why this worked.

preventDefault() on an <a> tag

After several operations, when the page should finally go to <a href"..."> link you can do the following:

jQuery("a").click(function(e){
    var self = jQuery(this);
    var href = self.attr('href');
    e.preventDefault();
    // needed operations

    window.location = href;
});

Django model "doesn't declare an explicit app_label"

I received this error after I moved the SECRET_KEY to pull from an environment variable and forgot to set it when running the application. If you have something like this in your settings.py

SECRET_KEY = os.getenv('SECRET_KEY')

then make sure you are actually setting the environment variable.

How to cast Object to its actual type?

Casting to actual type is easy:

void MyMethod(Object obj) {
    ActualType actualyType = (ActualType)obj;
}

Error when trying vagrant up

This work for me on Windows 10: https://stackoverflow.com/a/31594225/2400373

But it is necessary to delete the file: Vagranfile after use the command:

vagrant init precise64 http://files.vagrantup.com/precise64.box

And after

vagrant up

Read a file line by line assigning the value to a variable

Use IFS (internal field separator) tool in bash, defines the character using to separate lines into tokens, by default includes <tab> /<space> /<newLine>

step 1: Load the file data and insert into list:

# declaring array list and index iterator
declare -a array=()
i=0

# reading file in row mode, insert each line into array
while IFS= read -r line; do
    array[i]=$line
    let "i++"
    # reading from file path
done < "<yourFullFilePath>"

step 2: now iterate and print the output:

for line in "${array[@]}"
  do
    echo "$line"
  done

echo specific index in array: Accessing to a variable in array:

echo "${array[0]}"

How to post pictures to instagram using API

Instagram now allows businesses to schedule their posts, using the new Content Publishing Beta endpoints.

https://developers.facebook.com/blog/post/2018/01/30/instagram-graph-api-updates/

However, this blog post - https://business.instagram.com/blog/instagram-api-features-updates - makes it clear that they are only opening that API to their Facebook Marketing Partners or Instagram Partners.

To get started with scheduling posts, please work with one of our Facebook Marketing Partners or Instagram Partners.

This link from Facebook - https://developers.facebook.com/docs/instagram-api/content-publishing - lists it as a closed beta.

The Content Publishing API is in closed beta with Facebook Marketing Partners and Instagram Partners only. We are not accepting new applicants at this time.

But this is how you would do it:

You have a photo at...

https://www.example.com/images/bronz-fonz.jpg

You want to publish it with the hashtag "#BronzFonz".

You could use the /user/media edge to create the container like this:

POST graph.facebook.com 
  /17841400008460056/media?
    image_url=https%3A%2F%2Fwww.example.com%2Fimages%2Fbronz-fonz.jpg&
    caption=%23BronzFonz

This would return a container ID (let's say 17889455560051444), which you would then publish using the /user/media_publish edge, like this:

POST graph.facebook.com
  /17841405822304914/media_publish
    ?creation_id=17889455560051444

This example from the docs.

Get the last day of the month in SQL

Based on the statements:

SELECT DATEADD(MONTH, 1, @x)           -- Add a month to the supplied date @x

and

SELECT DATEADD(DAY,  0 - DAY(@x), @x)  -- Get last day of month previous to the supplied date @x

how about adding a month to date @x and then retrieving the last day of the month previous to that (i.e. The last day of the month of the supplied date)

DECLARE @x  DATE = '20-Feb-2012' 
SELECT DAY(DATEADD(DAY,  0 - DAY(DATEADD(MONTH, 1, @x)), DATEADD(MONTH, 1, @x)))

Note: This was test using SQL Server 2008 R2

The best way to remove duplicate values from NSMutableArray in Objective-C?

Here i removed duplicate name values from mainArray and store result in NSMutableArray(listOfUsers)

for (int i=0; i<mainArray.count; i++) {
    if (listOfUsers.count==0) {
        [listOfUsers addObject:[mainArray objectAtIndex:i]];

    }
   else if ([[listOfUsers valueForKey:@"name" ] containsObject:[[mainArray objectAtIndex:i] valueForKey:@"name"]])
    {  
       NSLog(@"Same object");
    }
    else
    {
        [listOfUsers addObject:[mainArray objectAtIndex:i]];
    }
}

How to print a stack trace in Node.js?

To print stacktrace of Error in console in more readable way:

console.log(ex, ex.stack.split("\n"));

Example result:

[Error] [ 'Error',
  '    at repl:1:7',
  '    at REPLServer.self.eval (repl.js:110:21)',
  '    at Interface.<anonymous> (repl.js:239:12)',
  '    at Interface.EventEmitter.emit (events.js:95:17)',
  '    at Interface._onLine (readline.js:202:10)',
  '    at Interface._line (readline.js:531:8)',
  '    at Interface._ttyWrite (readline.js:760:14)',
  '    at ReadStream.onkeypress (readline.js:99:10)',
  '    at ReadStream.EventEmitter.emit (events.js:98:17)',
  '    at emitKey (readline.js:1095:12)' ]

correct way of comparing string jquery operator =

No. = sets somevar to have that value. use === to compare value and type which returns a boolean that you need.

Never use or suggest == instead of ===. its a recipe for disaster. e.g 0 == "" is true but "" == '0' is false and many more.

More information also in this great answer

Calling Objective-C method from C++ member function?

Sometimes renaming .cpp to .mm is not good idea, especially when project is crossplatform. In this case for xcode project I open xcode project file throught TextEdit, found string which contents interest file, it should be like:

/* OnlineManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = OnlineManager.cpp; sourceTree = "<group>"; };

and then change file type from sourcecode.cpp.cpp to sourcecode.cpp.objcpp

/* OnlineManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = **sourcecode.cpp.objcpp**; path = OnlineManager.cpp; sourceTree = "<group>"; };

It is equivalent to rename .cpp to .mm

Each for object?

A javascript Object does not have a standard .each function. jQuery provides a function. See http://api.jquery.com/jQuery.each/ The below should work

$.each(object, function(index, value) {
    console.log(value);
}); 

Another option would be to use vanilla Javascript using the Object.keys() and the Array .map() functions like this

Object.keys(object).map(function(objectKey, index) {
    var value = object[objectKey];
    console.log(value);
});

See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Object/keys and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

These are usually better than using a vanilla Javascript for-loop, unless you really understand the implications of using a normal for-loop and see use for it's specific characteristics like looping over the property chain.

But usually, a for-loop doesn't work better than jQuery or Object.keys().map(). I'll go into two potential issues with using a plain for-loop below.


Right, so also pointed out in other answers, a plain Javascript alternative would be

for(var index in object) { 
    var attr = object[index]; 
}

There are two potential issues with this:

1 . You want to check whether the attribute that you are finding is from the object itself and not from up the prototype chain. This can be checked with the hasOwnProperty function like so

for(var index in object) { 
   if (object.hasOwnProperty(index)) {
       var attr = object[index];
   }
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty for more information.

The jQuery.each and Object.keys functions take care of this automatically.

2 . Another potential issue with a plain for-loop is that of scope and non-closures. This is a bit complicated, but take for example the following code. We have a bunch of buttons with ids button0, button1, button2 etc, and we want to set an onclick on them and do a console.log like this:

<button id='button0'>click</button>
<button id='button1'>click</button>
<button id='button2'>click</button>

var messagesByButtonId = {"button0" : "clicked first!", "button1" : "clicked middle!", "button2" : "clicked last!"];
for(var buttonId in messagesByButtonId ) { 
   if (messagesByButtonId.hasOwnProperty(buttonId)) {
       $('#'+buttonId).click(function() {
           var message = messagesByButtonId[buttonId];
           console.log(message);
       });
   }
}

If, after some time, we click any of the buttons we will always get "clicked last!" in the console, and never "clicked first!" or "clicked middle!". Why? Because at the time that the onclick function is executed, it will display messagesByButtonId[buttonId] using the buttonId variable at that moment. And since the loop has finished at that moment, the buttonId variable will still be "button2" (the value it had during the last loop iteration), and so messagesByButtonId[buttonId] will be messagesByButtonId["button2"], i.e. "clicked last!".

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures for more information on closures. Especially the last part of that page that covers our example.

Again, jQuery.each and Object.keys().map() solve this problem automatically for us, because it provides us with a function(index, value) (that has closure) so we are safe to use both index and value and rest assured that they have the value that we expect.

How do I print out the contents of an object in Rails for easy debugging?

inspect is great but sometimes not good enough. E.g. BigDecimal prints like this: #<BigDecimal:7ff49f5478b0,'0.1E2',9(18)>.

To have full control over what's printed you could redefine to_s or inspect methods. Or create your own one to not confuse future devs too much.

  class Something < ApplicationRecord

    def to_s
      attributes.map{ |k, v| { k => v.to_s } }.inject(:merge)
    end

  end

This will apply a method (i.e. to_s) to all attributes. This example will get rid of the ugly BigDecimals.

You can also redefine a handful of attributes only:

  def to_s
    attributes.merge({ my_attribute: my_attribute.to_s })
  end

You can also create a mix of the two or somehow add associations.

Why does python use 'else' after for and while loops?

Great answers are:

  • this which explain the history, and
  • this gives the right citation to ease yours translation/understanding.

My note here comes from what Donald Knuth once said (sorry can't find reference) that there is a construct where while-else is indistinguishable from if-else, namely (in Python):

x = 2
while x > 3:
    print("foo")
    break
else:
    print("boo")

has the same flow (excluding low level differences) as:

x = 2
if x > 3:
    print("foo")
else:
    print("boo")

The point is that if-else can be considered as syntactic sugar for while-else which has implicit break at the end of its if block. The opposite implication, that while loop is extension to if, is more common (it's just repeated/looped conditional check), because if is often taught before while. However that isn't true because that would mean else block in while-else would be executed each time when condition is false.

To ease your understanding think of it that way:

Without break, return, etc., loop ends only when condition is no longer true and in such case else block will also execute once. In case of Python for you must consider C-style for loops (with conditions) or translate them to while.

Another note:

Premature break, return, etc. inside loop makes impossible for condition to become false because execution jumped out of the loop while condition was true and it would never come back to check it again.

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

If using Bootstrap, add:

class="text-capitalize"

For example:

<input type="text" class="form-control text-capitalize" placeholder="Full Name" value="">

How to open adb and use it to send commands

You should find it in :

C:\Users\User Name\AppData\Local\Android\sdk\platform-tools

Add that to path, or change directory to there. The command sqlite3 is also there.

In the terminal you can type commands like

adb logcat //for logs
adb shell // for android shell

Remove leading zeros from a number in Javascript

It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

value = +value;

If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

input.value = +input.value;

is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

Angular 4.3 - HttpClient set params

Since HTTP Params class is immutable therefore you need to chain the set method:

const params = new HttpParams()
.set('aaa', '111')
.set('bbb', "222");

Difference between binary semaphore and mutex

Mutex and binary semaphore are both of the same usage, but in reality, they are different.

In case of mutex, only the thread which have locked it can unlock it. If any other thread comes to lock it, it will wait.

In case of semaphone, that's not the case. Semaphore is not tied up with a particular thread ID.

Python: Converting from ISO-8859-1/latin1 to UTF-8

For Python 3:

bytes(apple,'iso-8859-1').decode('utf-8')

I used this for a text incorrectly encoded as iso-8859-1 (showing words like VeÅ\x99ejné) instead of utf-8. This code produces correct version Verejné.

Cast to generic type in C#

I had a similar problem. I have a class;

Action<T>

which has a property of type T.

How do I get the property when I don't know T? I can't cast to Action<> unless I know T.

SOLUTION:

Implement a non-generic interface;

public interface IGetGenericTypeInstance
{
    object GenericTypeInstance();
}

Now I can cast the object to IGetGenericTypeInstance and GenericTypeInstance will return the property as type object.

TypeError: string indices must be integers, not str // working with dict

I see that you are looking for an implementation of the problem more than solving that error. Here you have a possible solution:

from itertools import chain

def involved(courses, person):
    courses_info = chain.from_iterable(x.values() for x in courses.values())
    return filter(lambda x: x['teacher'] == person, courses_info)

print involved(courses, 'Dave')

The first thing I do is getting the list of the courses and then filter by teacher's name.

How to use patterns in a case statement?

if and grep -Eq

arg='abc'
if echo "$arg" | grep -Eq 'a.c|d.*'; then
  echo 'first'
elif echo "$arg" | grep -Eq 'a{2,3}'; then
  echo 'second'
fi

where:

  • -q prevents grep from producing output, it just produces the exit status
  • -E enables extended regular expressions

I like this because:

One downside is that this is likely slower than case since it calls an external grep program, but I tend to consider performance last when using Bash.

case is POSIX 7

Bash appears to follow POSIX by default without shopt as mentioned by https://stackoverflow.com/a/4555979/895245

Here is the quote: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_01 section "Case Conditional Construct":

The conditional construct case shall execute the compound-list corresponding to the first one of several patterns (see Pattern Matching Notation) [...] Multiple patterns with the same compound-list shall be delimited by the '|' symbol. [...]

The format for the case construct is as follows:

case word in
     [(] pattern1 ) compound-list ;;
     [[(] pattern[ | pattern] ... ) compound-list ;;] ...
     [[(] pattern[ | pattern] ... ) compound-list]
  esac

and then http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13 section "2.13. Pattern Matching Notation" only mentions ?, * and [].

ModalPopupExtender OK Button click event not firing?

It could also be that the button needs to have CausesValidation="false". That worked for me.

List all liquibase sql types

For checking type conversions in version 3, you can go to their github and check into the different liquibase types and check the method toDatabaseDataType. For example, for Boolean, you can check here:

https://github.com/liquibase/liquibase/blob/master/liquibase-core/src/main/java/liquibase/datatype/core/BooleanType.java

For version 2.0.x, the conversion seems to be into database specific classes. For example, for Mysql:

https://github.com/liquibase/liquibase/blob/2_0_x/liquibase-core/src/main/java/liquibase/database/typeconversion/core/MySQLTypeConverter.java

How to set the image from drawable dynamically in android?

ImageView imageView=findViewById(R.id.imageView)

if you have image in drawable folder then use

imageView.setImageResource(R.drawable.imageView)

if you have uri and want to display it in imageView then use

imageView.setImageUri("uri")

if you have bitmap and want to display it in imageView then use

imageView.setImageBitmap(bitmap)

note:- 1. imageView.setImageDrawable() is now deprecated in java 2. If image uri is from firebase or from any other online link then use

    Picasso.get()
    .load("uri")
    .into(imageView)

(https://github.com/square/picasso)

or use

Glide.with(context)
            .load("uri")
            .into(imageView)

(https://github.com/bumptech/glide)

Getting ssh to execute a command in the background on target machine

You can do this without nohup:

ssh user@host 'myprogram >out.log 2>err.log &'

Can't start Eclipse - Java was started but returned exit code=13

If nothing works, then the last solution you can try is to completely uninstall Java from your computer and then install it again, and make sure the path variables are set correctly.

Passing $_POST values with cURL

Check out the cUrl PHP documentation page. It will help much more than just with example scripts.

Merge two array of objects based on a key

I was able to achieve this with a nested mapping of the two arrays and updating the initial array:

member.map(mem => {
return memberInfo.map(info => {
    if (info.id === mem.userId) {
        mem.date = info.date;
        return mem;
        }
    }
}

Creating pdf files at runtime in c#

For this i looked into running LaTeX apps to generate a pdf. Although this option is likely to be far more complicated and heavy duty than the ones listed here.

Default property value in React component using TypeScript

For those having optional props that need default values. Credit here :)

interface Props {
  firstName: string;
  lastName?: string;
}

interface DefaultProps {
  lastName: string;
}

type PropsWithDefaults = Props & DefaultProps;

export class User extends React.Component<Props> {
  public static defaultProps: DefaultProps = {
    lastName: 'None',
  }

  public render () {
    const { firstName, lastName } = this.props as PropsWithDefaults;

    return (
      <div>{firstName} {lastName}</div>
    )
  }
}

How to use sed to extract substring

Explaining how you can use cut:

cat yourxmlfile | cut -d'"' -f2

It will 'cut' all the lines in the file based on " delimiter, and will take the 2nd field , which is what you wanted.

Get Base64 encode file-data from Input Form

I've started to think that using the 'iframe' for Ajax style upload might be a much better choice for my situation until HTML5 comes full circle and I don't have to support legacy browsers in my app!

Volley JsonObjectRequest Post request not working

Easy one for me ! I got it few weeks ago :

This goes in getBody() method, not in getParams() for a post request.

Here is mine :

    @Override
/**
 * Returns the raw POST or PUT body to be sent.
 *
 * @throws AuthFailureError in the event of auth failure
 */
public byte[] getBody() throws AuthFailureError {
    //        Map<String, String> params = getParams();
    Map<String, String> params = new HashMap<String, String>();
    params.put("id","1");
    params.put("name", "myname");
    if (params != null && params.size() > 0) {
        return encodeParameters(params, getParamsEncoding());
    }
    return null;

}

(I assumed you want to POST the params you wrote in your getParams)

I gave the params to the request inside the constructor, but since you are creating the request on the fly, you can hard coded them inside your override of the getBody() method.

This is what my code looks like :

    Bundle param = new Bundle();
    param.putString(HttpUtils.HTTP_CALL_TAG_KEY, tag);
    param.putString(HttpUtils.HTTP_CALL_PATH_KEY, url);
    param.putString(HttpUtils.HTTP_CALL_PARAM_KEY, params);

    switch (type) {
    case RequestType.POST:
        param.putInt(HttpUtils.HTTP_CALL_TYPE_KEY, RequestType.POST);
        SCMainActivity.mRequestQueue.add(new SCRequestPOST(Method.POST, url, this, tag, receiver, params));

and if you want even more this last string params comes from :

param = JsonUtils.XWWWUrlEncoder.encode(new JSONObject(paramasJObj)).toString();

and the paramasJObj is something like this : {"id"="1","name"="myname"} the usual JSON string.

How do I start a program with arguments when debugging?

Go to Project-><Projectname> Properties. Then click on the Debug tab, and fill in your arguments in the textbox called Command line arguments.

How to stop a JavaScript for loop?

The logic is incorrect. It would always return the result of last element in the array.

remIndex = -1;

for (i = 0; i < remSize.length; i++) {      
    if (remSize[i].size == remData.size) {
        remIndex = i
        break;
    }
}

How can I remove Nan from list Python/NumPy

Another way to do it would include using filter like this:

countries = list(filter(lambda x: str(x) != 'nan', countries))

How to select the nth row in a SQL database table?

For SQL Server, a generic way to go by row number is as such:

SET ROWCOUNT @row --@row = the row number you wish to work on.

For Example:

set rowcount 20   --sets row to 20th row

select meat, cheese from dbo.sandwich --select columns from table at 20th row

set rowcount 0   --sets rowcount back to all rows

This will return the 20th row's information. Be sure to put in the rowcount 0 afterward.

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

How to delete row in gridview using rowdeleting event?

Try This Make sure You mention Datakeyname which is nothing but the column name (id) in your designer file

//your aspx code

<asp:GridView ID="dgUsers" runat="server" AutoGenerateSelectButton="True" OnDataBound="dgUsers_DataBound" OnRowDataBound="dgUsers_RowDataBound" OnSelectedIndexChanged="dgUsers_SelectedIndexChanged" AutoGenerateDeleteButton="True" OnRowDeleting="dgUsers_RowDeleting" DataKeyNames="id" OnRowCommand="dgUsers_RowCommand"></asp:GridView>

//Your aspx.cs Code

protected void dgUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

            int id = Convert.ToInt32(dgUsers.DataKeys[e.RowIndex].Value);
            string query = "delete from users where id= '" + id + "'";
            //your remaining delete code
        }

How to find encoding of a file via script on Linux?

This is not something you can do in a foolproof way. One possibility would be to examine every character in the file to ensure that it doesn't contain any characters in the ranges 0x00 - 0x1f or 0x7f -0x9f but, as I said, this may be true for any number of files, including at least one other variant of ISO8859.

Another possibility is to look for specific words in the file in all of the languages supported and see if you can find them.

So, for example, find the equivalent of the English "and", "but", "to", "of" and so on in all the supported languages of 8859-1 and see if they have a large number of occurrences within the file.

I'm not talking about literal translation such as:

English   French
-------   ------
of        de, du
and       et
the       le, la, les

although that's possible. I'm talking about common words in the target language (for all I know, Icelandic has no word for "and" - you'd probably have to use their word for "fish" [sorry that's a little stereotypical, I didn't mean any offense, just illustrating a point]).

How to sort an array of ints using a custom comparator?

How about using streams (Java 8)?

int[] ia = {99, 11, 7, 21, 4, 2};
ia = Arrays.stream(ia).
    boxed().
    sorted((a, b) -> b.compareTo(a)). // sort descending
    mapToInt(i -> i).
    toArray();

Or in-place:

int[] ia = {99, 11, 7, 21, 4, 2};
System.arraycopy(
        Arrays.stream(ia).
            boxed().
            sorted((a, b) -> b.compareTo(a)). // sort descending
            mapToInt(i -> i).
            toArray(),
        0,
        ia,
        0,
        ia.length
    );

What are ODEX files in Android?

The blog article is mostly right, but not complete. To have a full understanding of what an odex file does, you have to understand a little about how application files (APK) work.

Applications are basically glorified ZIP archives. The java code is stored in a file called classes.dex and this file is parsed by the Dalvik JVM and a cache of the processed classes.dex file is stored in the phone's Dalvik cache.

An odex is basically a pre-processed version of an application's classes.dex that is execution-ready for Dalvik. When an application is odexed, the classes.dex is removed from the APK archive and it does not write anything to the Dalvik cache. An application that is not odexed ends up with 2 copies of the classes.dex file--the packaged one in the APK, and the processed one in the Dalvik cache. It also takes a little longer to launch the first time since Dalvik has to extract and process the classes.dex file.

If you are building a custom ROM, it's a really good idea to odex both your framework JAR files and the stock apps in order to maximize the internal storage space for user-installed apps. If you want to theme, then simply deodex -> apply your theme -> reodex -> release.

To actually deodex, use small and baksmali:

https://github.com/JesusFreke/smali/wiki/DeodexInstructions

Drawing rotated text on a HTML5 canvas

Posting this in an effort to help others with similar problems. I solved this issue with a five step approach -- save the context, translate the context, rotate the context, draw the text, then restore the context to its saved state.

I think of translations and transforms to the context as manipulating the coordinate grid overlaid on the canvas. By default the origin (0,0) starts in the upper left hand corner of the canvas. X increases from left to right, Y increases from top to bottom. If you make an "L" w/ your index finger and thumb on your left hand and hold it out in front of you with your thumb down, your thumb would point in the direction of increasing Y and your index finger would point in the direction of increasing X. I know it's elementary, but I find it helpful when thinking about translations and rotations. Here's why:

When you translate the context, you move the origin of the coordinate grid to a new location on the canvas. When you rotate the context, think of rotating the "L" you made with your left hand in a clockwise direction the amount indicated by the angle you specify in radians about the origin. When you strokeText or fillText, specify your coordinates in relation to the newly aligned axes. To orient your text so it's readable from bottom to top, you would translate to a position below where you want to start your labels, rotate by -90 degrees and fill or strokeText, offsetting each label along the rotated x axis. Something like this should work:

 context.save();
 context.translate(newx, newy);
 context.rotate(-Math.PI/2);
 context.textAlign = "center";
 context.fillText("Your Label Here", labelXposition, 0);
 context.restore();

.restore() resets the context back to the state it had when you called .save() -- handy for returning things back to "normal".


How to check a channel is closed or not without reading it?

Well, you can use default branch to detect it, for a closed channel will be selected, for example: the following code will select default, channel, channel, the first select is not blocked.

func main() {
    ch := make(chan int)

    go func() {
        select {
        case <-ch:
            log.Printf("1.channel")
        default:
            log.Printf("1.default")
        }
        select {
        case <-ch:
            log.Printf("2.channel")
        }
        close(ch)
        select {
        case <-ch:
            log.Printf("3.channel")
        default:
            log.Printf("3.default")
        }
    }()
    time.Sleep(time.Second)
    ch <- 1
    time.Sleep(time.Second)
}

Prints

2018/05/24 08:00:00 1.default
2018/05/24 08:00:01 2.channel
2018/05/24 08:00:01 3.channel

Implode an array with JavaScript?

array.join was not recognizing ";" how a separator, but replacing it with comma. Using jQuery, you can use $.each to implode an array (Note that output_saved_json is the array and tmp is the string that will store the imploded array):

var tmp = "";
$.each(output_saved_json, function(index,value) {
    tmp = tmp + output_saved_json[index] + ";";
});

output_saved_json = tmp.substring(0,tmp.length - 1); // remove last ";" added

I have used substring to remove last ";" added at the final without necessity. But if you prefer, you can use instead substring something like:

var tmp = "";
$.each(output_saved_json, function(index,value) {
    tmp = tmp + output_saved_json[index];

    if((index + 1) != output_saved_json.length) {
         tmp = tmp + ";";
    }
});

output_saved_json = tmp;

I think this last solution is more slower than the 1st one because it needs to check if index is different than the lenght of array every time while $.each do not end.

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

The above mentioned solutions didn't work for me.

I just restarted my IDE by closing it and reopening it.

And then error disappeared and its working fine now.

How to format numbers by prepending 0 to single-digit numbers?

("0" + (date.getMonth() + 1)).slice(-2);
("0" + (date.getDay())).slice(-2);

What is the difference between static func and class func in Swift?

From Swift2.0, Apple says:

"Always prefix type property requirements with the static keyword when you define them in a protocol. This rule pertains even though type property requirements can be prefixed with the class or static keyword when implemented by a class:"

Display current time in 12 hour format with AM/PM

You can use SimpleDateFormat for this.

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm a");

Hope this helps you.

Java Strings: "String s = new String("silly");"

- How do i make CaseInsensitiveString behave like String so the above statement is ok (with and w/out extending String)? What is it about String that makes it ok to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java right?

Enough has been said from the first point. "Polish" is an string literal and cannot be assigned to the CaseInsentiviveString class.

Now about the second point

Although you can't create new literals, you can follow the first item of that book for a "similar" approach so the following statements are true:

    // Lets test the insensitiveness
    CaseInsensitiveString cis5 = CaseInsensitiveString.valueOf("sOmEtHiNg");
    CaseInsensitiveString cis6 = CaseInsensitiveString.valueOf("SoMeThInG");

    assert cis5 == cis6;
    assert cis5.equals(cis6);

Here's the code.

C:\oreyes\samples\java\insensitive>type CaseInsensitiveString.java
import java.util.Map;
import java.util.HashMap;

public final class CaseInsensitiveString  {


    private static final Map<String,CaseInsensitiveString> innerPool 
                                = new HashMap<String,CaseInsensitiveString>();

    private final String s;


    // Effective Java Item 1: Consider providing static factory methods instead of constructors
    public static CaseInsensitiveString valueOf( String s ) {

        if ( s == null ) {
            return null;
        }
        String value = s.toLowerCase();

        if ( !CaseInsensitiveString.innerPool.containsKey( value ) ) {
             CaseInsensitiveString.innerPool.put( value , new CaseInsensitiveString( value ) );
         }

         return CaseInsensitiveString.innerPool.get( value );   
    }

    // Class constructor: This creates a new instance each time it is invoked.
    public CaseInsensitiveString(String s){
        if (s == null) {
            throw new NullPointerException();
         }         
         this.s = s.toLowerCase();
    }

    public boolean equals( Object other ) {
         if ( other instanceof CaseInsensitiveString ) {
              CaseInsensitiveString otherInstance = ( CaseInsensitiveString ) other;
             return this.s.equals( otherInstance.s );
         }

         return false;
    }


    public int hashCode(){
         return this.s.hashCode();
    }

// Test the class using the "assert" keyword

    public static void main( String [] args ) {

        // Creating two different objects as in new String("Polish") == new String("Polish") is false
        CaseInsensitiveString cis1 = new CaseInsensitiveString("Polish");
        CaseInsensitiveString cis2 = new CaseInsensitiveString("Polish");

        // references cis1 and cis2 points to differents objects.
        // so the following is true
        assert cis1 !=  cis2;      // Yes they're different
        assert cis1.equals(cis2);  // Yes they're equals thanks to the equals method

        // Now let's try the valueOf idiom
        CaseInsensitiveString cis3 = CaseInsensitiveString.valueOf("Polish");
        CaseInsensitiveString cis4 = CaseInsensitiveString.valueOf("Polish");

        // References cis3 and cis4 points to same  object.
        // so the following is true
        assert cis3 == cis4;      // Yes they point to the same object
        assert cis3.equals(cis4); // and still equals.

        // Lets test the insensitiveness
        CaseInsensitiveString cis5 = CaseInsensitiveString.valueOf("sOmEtHiNg");
        CaseInsensitiveString cis6 = CaseInsensitiveString.valueOf("SoMeThInG");

        assert cis5 == cis6;
        assert cis5.equals(cis6);

        // Futhermore
        CaseInsensitiveString cis7 = CaseInsensitiveString.valueOf("SomethinG");
        CaseInsensitiveString cis8 = CaseInsensitiveString.valueOf("someThing");

        assert cis8 == cis5 && cis7 == cis6;
        assert cis7.equals(cis5) && cis6.equals(cis8);
    }

}

C:\oreyes\samples\java\insensitive>javac CaseInsensitiveString.java


C:\oreyes\samples\java\insensitive>java -ea CaseInsensitiveString

C:\oreyes\samples\java\insensitive>

That is, create an internal pool of CaseInsensitiveString objects, and return the corrensponding instance from there.

This way the "==" operator returns true for two objects references representing the same value.

This is useful when similar objects are used very frequently and creating cost is expensive.

The string class documentation states that the class uses an internal pool

The class is not complete, some interesting issues arises when we try to walk the contents of the object at implementing the CharSequence interface, but this code is good enough to show how that item in the Book could be applied.

It is important to notice that by using the internalPool object, the references are not released and thus not garbage collectible, and that may become an issue if a lot of objects are created.

It works for the String class because it is used intensively and the pool is constituted of "interned" object only.

It works well for the Boolean class too, because there are only two possible values.

And finally that's also the reason why valueOf(int) in class Integer is limited to -128 to 127 int values.

git commit error: pathspec 'commit' did not match any file(s) known to git

In my case the problem was I had forgotten to add the switch -m before the quoted comment. It may be a common error too, and the error message received is exactly the same