Programs & Examples On #Mercurial bigfiles

React.js inline style best practices

I use inline styles extensively within my React components. I find it so much clearer to colocate styles within components because it's always clear what styles the component does and doesn't have. Plus having the full power of Javascript at hand really simplifies more complex styling needs.

I wasn't convinced at first but after dabbling in it for several months, I'm fully converted and am in process of converting all my CSS to inline or other JS-driven css methods.

This presentation by Facebook employee and React contributor "vjeux" is really helpful as well — https://speakerdeck.com/vjeux/react-css-in-js

"elseif" syntax in JavaScript

x = 10;
if(x > 100 ) console.log('over 100')
else if (x > 90 ) console.log('over 90')
else if (x > 50 ) console.log('over 50')
else if (x > 9 ) console.log('over 9')
else console.log('lower 9') 

What are the differences between Mustache.js and Handlebars.js?

One subtle but significant difference is in the way the two libraries approach scope. Mustache will fall back to parent scope if it can't find a variable within the current context; Handlebars will return a blank string.

This is barely mentioned in the GitHub README, where there's one line for it:

Handlebars deviates from Mustache slightly in that it does not perform recursive lookup by default.

However, as noted there, there is a flag to make Handlebars behave in the same way as Mustache -- but it affects performance.

This has an effect on the way you can use # variables as conditionals.

For example in Mustache you can do this:

{{#variable}}<span class="text">{{variable}}</span>{{/variable}}

It basically means "if variable exists and is truthy, print a span with the variable in it". But in Handlebars, you would either have to:

  • use {{this}} instead
  • use a parent path, i.e., {{../variable}} to get back out to relevant scope
  • define a child variable value within the parent variable object

More details on this, if you want them, here.

What is “assert” in JavaScript?

check this:http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-quick-and-easy-javascript-testing-with-assert/

it is for testing JavaScript. Amazingly, at barely five or six lines, this code provides a great level of power and control over your code, when testing.

The assert function accepts two parameters:

outcome: A boolean, which references whether your test passed or failed

description: A short description of your test.

The assert function then simply creates a list item, applies a class of either “pass” or “fail,” dependent upon whether your test returned true or false, and then appends the description to the list item. Finally, that block of coded is added to the page. It’s crazy simple, but works perfectly.

Reverse a string in Java

Here is the code that can be used to reverse a String.

public static void main(String[] args) {

        String aString = "noun";

        int size = aString.length();
        String reversed = "";

        for (int i=size-1;i>=0;i--){
            reversed = reversed+ aString.charAt(i);
            if (i == 0)
                System.out.println(reversed);
        }
}

you can also watch the video to better understand the concepts that are needed https://www.youtube.com/watch?v=KaoA0o2Tfi4

ADB - Android - Getting the name of the current activity

You can use this command,

adb shell dumpsys activity

You can find current activity name in activity stack.

Output :-

 Sticky broadcasts:
 * Sticky action android.intent.action.BATTERY_CHANGED:
   Intent: act=android.intent.action.BATTERY_CHANGED flg=0x60000000
     Bundle[{icon-small=17302169, present=true, scale=100, level=50, technology=Li-ion, status=2, voltage=0, plugged=1, health=2, temperature=0}]
 * Sticky action android.net.thrott.THROTTLE_ACTION:
   Intent: act=android.net.thrott.THROTTLE_ACTION
     Bundle[{level=-1}]
 * Sticky action android.intent.action.NETWORK_SET_TIMEZONE:
   Intent: act=android.intent.action.NETWORK_SET_TIMEZONE flg=0x20000000
     Bundle[mParcelledData.dataSize=68]
 * Sticky action android.provider.Telephony.SPN_STRINGS_UPDATED:
   Intent: act=android.provider.Telephony.SPN_STRINGS_UPDATED flg=0x20000000
     Bundle[mParcelledData.dataSize=156]
 * Sticky action android.net.thrott.POLL_ACTION:
   Intent: act=android.net.thrott.POLL_ACTION
     Bundle[{cycleRead=0, cycleStart=1349893800000, cycleEnd=1352572200000, cycleWrite=0}]
 * Sticky action android.intent.action.SIM_STATE_CHANGED:
   Intent: act=android.intent.action.SIM_STATE_CHANGED flg=0x20000000
     Bundle[mParcelledData.dataSize=116]
 * Sticky action android.intent.action.SIG_STR:
   Intent: act=android.intent.action.SIG_STR flg=0x20000000
     Bundle[{EvdoSnr=-1, CdmaDbm=-1, GsmBitErrorRate=-1, CdmaEcio=-1, EvdoDbm=-1, GsmSignalStrength=7, EvdoEcio=-1, isGsm=true}]
 * Sticky action android.intent.action.SERVICE_STATE:
   Intent: act=android.intent.action.SERVICE_STATE flg=0x20000000
     Bundle[{cdmaRoamingIndicator=0, operator-numeric=310260, networkId=0, state=0, emergencyOnly=false, operator-alpha-short=Android, radioTechnology=3, manual=false, cssIndicator=false, operator-alpha-long=Android, systemId=0, roaming=false, cdmaDefaultRoamingIndicator=0}]
 * Sticky action android.net.conn.CONNECTIVITY_CHANGE:
   Intent: act=android.net.conn.CONNECTIVITY_CHANGE flg=0x30000000
     Bundle[{networkInfo=NetworkInfo: type: mobile[UMTS], state: CONNECTED/CONNECTED, reason: simLoaded, extra: internet, roaming: false, failover: false, isAvailable: true, reason=simLoaded, extraInfo=internet}]
 * Sticky action android.intent.action.NETWORK_SET_TIME:
   Intent: act=android.intent.action.NETWORK_SET_TIME flg=0x20000000
     Bundle[mParcelledData.dataSize=36]
 * Sticky action android.media.RINGER_MODE_CHANGED:
   Intent: act=android.media.RINGER_MODE_CHANGED flg=0x70000000
     Bundle[{android.media.EXTRA_RINGER_MODE=2}]
 * Sticky action android.intent.action.ANY_DATA_STATE:
   Intent: act=android.intent.action.ANY_DATA_STATE flg=0x20000000
     Bundle[{state=CONNECTED, apnType=*, iface=/dev/omap_csmi_tty1, apn=internet, reason=simLoaded}]

 Activity stack:
 * TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
   clearOnBackground=false numActivities=2 rootWasReset=false
   affinity=org.chanakyastocktipps.com
   intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=org.chanakyastocktipps.com/.ui.SplashScreen}
   realActivity=org.chanakyastocktipps.com/.ui.SplashScreen
   lastActiveTime=15107753 (inactive for 4879s)
   * Hist #2: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
       packageName=org.chanakyastocktipps.com processName=org.chanakyastocktipps.com
       launchedFromUid=10046 app=ProcessRecord{44fa3450 1065:org.chanakyastocktipps.com/10046}
       Intent { cmp=org.chanakyastocktipps.com/.ui.Profile }
       frontOfTask=false task=TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
       taskAffinity=org.chanakyastocktipps.com
       realActivity=org.chanakyastocktipps.com/.ui.Profile
       base=/data/app/org.chanakyastocktipps.com-1.apk/data/app/org.chanakyastocktipps.com-1.apk data=/data/data/org.chanakyastocktipps.com
       labelRes=0x7f09000b icon=0x7f020065 theme=0x1030007
       stateNotNeeded=false componentSpecified=true isHomeActivity=false
       configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
       resultTo=HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen} resultWho=null resultCode=4
       launchFailed=false haveState=false icicle=null
       state=RESUMED stopped=false delayedResume=false finishing=false
       keysPaused=false inHistory=true persistent=false launchMode=0
       fullscreen=true visible=true frozenBeforeDestroy=false thumbnailNeeded=false idle=true
       waitingVisible=false nowVisible=true
   * Hist #1: HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen}
       packageName=org.chanakyastocktipps.com processName=org.chanakyastocktipps.com
       launchedFromUid=10046 app=ProcessRecord{44fa3450 1065:org.chanakyastocktipps.com/10046}
       Intent { cmp=org.chanakyastocktipps.com/.ui.MainScreen }
       frontOfTask=true task=TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
       taskAffinity=org.chanakyastocktipps.com
       realActivity=org.chanakyastocktipps.com/.ui.MainScreen
       base=/data/app/org.chanakyastocktipps.com-1.apk/data/app/org.chanakyastocktipps.com-1.apk data=/data/data/org.chanakyastocktipps.com
       labelRes=0x7f09000b icon=0x7f020065 theme=0x1030007
       stateNotNeeded=false componentSpecified=true isHomeActivity=false
       configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
       launchFailed=false haveState=true icicle=Bundle[mParcelledData.dataSize=1344]
       state=STOPPED stopped=true delayedResume=false finishing=false
       keysPaused=false inHistory=true persistent=false launchMode=0
       fullscreen=true visible=false frozenBeforeDestroy=false thumbnailNeeded=false idle=true
 * TaskRecord{450615a0 #2 A com.android.launcher}
   clearOnBackground=true numActivities=1 rootWasReset=false
   affinity=com.android.launcher
   intent={act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000000 cmp=com.android.launcher/com.android.launcher2.Launcher}
   realActivity=com.android.launcher/com.android.launcher2.Launcher
   lastActiveTime=12263090 (inactive for 7724s)
   * Hist #0: HistoryRecord{4505d838 com.android.launcher/com.android.launcher2.Launcher}
       packageName=com.android.launcher processName=com.android.launcher
       launchedFromUid=0 app=ProcessRecord{45062558 129:com.android.launcher/10025}
       Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000000 cmp=com.android.launcher/com.android.launcher2.Launcher }
       frontOfTask=true task=TaskRecord{450615a0 #2 A com.android.launcher}
       taskAffinity=com.android.launcher
       realActivity=com.android.launcher/com.android.launcher2.Launcher
       base=/system/app/Launcher2.apk/system/app/Launcher2.apk data=/data/data/com.android.launcher
       labelRes=0x7f0c0002 icon=0x7f020044 theme=0x7f0d0000
       stateNotNeeded=true componentSpecified=false isHomeActivity=true
       configuration={ scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
       launchFailed=false haveState=true icicle=Bundle[mParcelledData.dataSize=3608]
       state=STOPPED stopped=true delayedResume=false finishing=false
       keysPaused=false inHistory=true persistent=false launchMode=2
       fullscreen=true visible=false frozenBeforeDestroy=false thumbnailNeeded=false idle=true

 Running activities (most recent first):
   TaskRecord{450adb90 #22 A org.chanakyastocktipps.com}
     Run #2: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
     Run #1: HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen}
   TaskRecord{450615a0 #2 A com.android.launcher}
     Run #0: HistoryRecord{4505d838 com.android.launcher/com.android.launcher2.Launcher}

 mPausingActivity: null
 mResumedActivity: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
 mFocusedActivity: HistoryRecord{450d7ab0 org.chanakyastocktipps.com/.ui.Profile}
 mLastPausedActivity: HistoryRecord{44f523c0 org.chanakyastocktipps.com/.ui.MainScreen}

 mCurTask: 22

 Running processes (most recent first):
   App  #13: adj=vis  /F 45052120 119:com.android.inputmethod.latin/10003 (service)
             com.android.inputmethod.latin.LatinIME<=ProcessRecord{44ec2698 59:system/1000}
   PERS #12: adj=sys  /F 44ec2698 59:system/1000 (fixed)
   App  #11: adj=fore /F 44fa3450 1065:org.chanakyastocktipps.com/10046 (top-activity)
   App  #10: adj=bak  /B 44e7c4c0 299:com.svox.pico/10028 (bg-empty)
   App  # 9: adj=bak+1/B 450f7ef0 288:com.dreamreminder.org:feather_system_receiver/10057 (bg-empty)
   App  # 8: adj=bak+2/B 4503cc38 201:com.android.defcontainer/10010 (bg-empty)
   App  # 7: adj=home /B 45062558 129:com.android.launcher/10025 (home)
   App  # 6: adj=bak+3/B 450244d8 276:android.process.media/10002 (bg-empty)
   App  # 5: adj=bak+4/B 44f2b9b8 263:com.android.quicksearchbox/10012 (bg-empty)
   App  # 4: adj=bak+5/B 450beec0 257:com.android.protips/10007 (bg-empty)
   App  # 3: adj=bak+6/B 44ff37b8 270:com.android.music/10022 (bg-empty)
   PERS # 2: adj=core /F 45056818 124:com.android.phone/1001 (fixed)
   App  # 1: adj=bak+7/B 45080c38 238:com.dreamreminder.org/10057 (bg-empty)
   App  # 0: adj=empty/B 4507d030 229:com.android.email/10030 (bg-empty)

 PID mappings:
   PID #59: ProcessRecord{44ec2698 59:system/1000}
   PID #119: ProcessRecord{45052120 119:com.android.inputmethod.latin/10003}
   PID #124: ProcessRecord{45056818 124:com.android.phone/1001}
   PID #129: ProcessRecord{45062558 129:com.android.launcher/10025}
   PID #201: ProcessRecord{4503cc38 201:com.android.defcontainer/10010}
   PID #229: ProcessRecord{4507d030 229:com.android.email/10030}
   PID #238: ProcessRecord{45080c38 238:com.dreamreminder.org/10057}
   PID #257: ProcessRecord{450beec0 257:com.android.protips/10007}
   PID #263: ProcessRecord{44f2b9b8 263:com.android.quicksearchbox/10012}
   PID #270: ProcessRecord{44ff37b8 270:com.android.music/10022}
   PID #276: ProcessRecord{450244d8 276:android.process.media/10002}
   PID #288: ProcessRecord{450f7ef0 288:com.dreamreminder.org:feather_system_receiver/10057}
   PID #299: ProcessRecord{44e7c4c0 299:com.svox.pico/10028}
   PID #1065: ProcessRecord{44fa3450 1065:org.chanakyastocktipps.com/10046}

 mHomeProcess: ProcessRecord{45062558 129:com.android.launcher/10025}
 mConfiguration: { scale=1.0 imsi=310/260 loc=en_US touch=3 keys=2/1/2 nav=3/1 orien=1 layout=18 uiMode=17 seq=3}
 mConfigWillChange: false
 mSleeping=false mShuttingDown=false

Bootstrap 3 Align Text To Bottom of Div

I think your best bet would be to use a combination of absolute and relative positioning.

Here's a fiddle: http://jsfiddle.net/PKVza/2/

given your html:

<div class="row">
    <div class="col-sm-6">
        <img src="~/Images/MyLogo.png" alt="Logo" />
    </div>
    <div class="bottom-align-text col-sm-6">
        <h3>Some Text</h3>
    </div>
</div>

use the following CSS:

@media (min-width: 768px ) {
  .row {
      position: relative;
  }

  .bottom-align-text {
    position: absolute;
    bottom: 0;
    right: 0;
  }
}

EDIT - Fixed CSS and JSFiddle for mobile responsiveness and changed the ID to a class.

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

I got the same error because of a simple typo in vhost.conf. Remember to make sure you don't have any errors in the config files.

apachectl configtest

Convert seconds to HH-MM-SS with JavaScript?

--update 2

Please use @Frank's a one line solution:

new Date(SECONDS * 1000).toISOString().substr(11, 8)

It is by far the best solution.

How to set TLS version on apache HttpClient

HttpClient-4.5,Use TLSv1.2 ,You must code like this:

 //Set the https use TLSv1.2
private static Registry<ConnectionSocketFactory> getRegistry() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext sslContext = SSLContexts.custom().build();
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[]{"TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory)
            .build();
}

public static void main(String... args) {
    try {
        //Set the https use TLSv1.2
        PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(getRegistry());
        clientConnectionManager.setMaxTotal(100);
        clientConnectionManager.setDefaultMaxPerRoute(20);
        HttpClient client = HttpClients.custom().setConnectionManager(clientConnectionManager).build();
        //Then you can do : client.execute(HttpGet or HttpPost);
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

Catching errors in Angular HttpClient

With the arrival of the HTTPClient API, not only was the Http API replaced, but a new one was added, the HttpInterceptor API.

AFAIK one of its goals is to add default behavior to all the HTTP outgoing requests and incoming responses.

So assumming that you want to add a default error handling behavior, adding .catch() to all of your possible http.get/post/etc methods is ridiculously hard to maintain.

This could be done in the following way as example using a HttpInterceptor:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { _throw } from 'rxjs/observable/throw';
import 'rxjs/add/operator/catch';

/**
 * Intercepts the HTTP responses, and in case that an error/exception is thrown, handles it
 * and extract the relevant information of it.
 */
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    /**
     * Intercepts an outgoing HTTP request, executes it and handles any error that could be triggered in execution.
     * @see HttpInterceptor
     * @param req the outgoing HTTP request
     * @param next a HTTP request handler
     */
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req)
            .catch(errorResponse => {
                let errMsg: string;
                if (errorResponse instanceof HttpErrorResponse) {
                    const err = errorResponse.message || JSON.stringify(errorResponse.error);
                    errMsg = `${errorResponse.status} - ${errorResponse.statusText || ''} Details: ${err}`;
                } else {
                    errMsg = errorResponse.message ? errorResponse.message : errorResponse.toString();
                }
                return _throw(errMsg);
            });
    }
}

/**
 * Provider POJO for the interceptor
 */
export const ErrorInterceptorProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    multi: true,
};

// app.module.ts

import { ErrorInterceptorProvider } from 'somewhere/in/your/src/folder';

@NgModule({
   ...
   providers: [
    ...
    ErrorInterceptorProvider,
    ....
   ],
   ...
})
export class AppModule {}

Some extra info for OP: Calling http.get/post/etc without a strong type isn't an optimal use of the API. Your service should look like this:

// These interfaces could be somewhere else in your src folder, not necessarily in your service file
export interface FooPost {
 // Define the form of the object in JSON format that your 
 // expect from the backend on post
}

export interface FooPatch {
 // Define the form of the object in JSON format that your 
 // expect from the backend on patch
}

export interface FooGet {
 // Define the form of the object in JSON format that your 
 // expect from the backend on get
}

@Injectable()
export class DataService {
    baseUrl = 'http://localhost'
    constructor(
        private http: HttpClient) {
    }

    get(url, params): Observable<FooGet> {

        return this.http.get<FooGet>(this.baseUrl + url, params);
    }

    post(url, body): Observable<FooPost> {
        return this.http.post<FooPost>(this.baseUrl + url, body);
    }

    patch(url, body): Observable<FooPatch> {
        return this.http.patch<FooPatch>(this.baseUrl + url, body);
    }
}

Returning Promises from your service methods instead of Observables is another bad decision.

And an extra piece of advice: if you are using TYPEscript, then start using the type part of it. You lose one of the biggest advantages of the language: to know the type of the value that you are dealing with.

If you want a, in my opinion, good example of an angular service, take a look at the following gist.

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

What is the C++ function to raise a number to a power?

You should be able to use normal C methods in math.

#include <cmath>

pow(2,3)

if you're on a unix-like system, man cmath

Is that what you're asking?

Sujal

What does <![CDATA[]]> in XML mean?

I once had to use CDATA when my xml element needed to store HTML code. Something like

<codearea>
  <![CDATA[ 
  <div> <p> my para </p> </div> 
  ]]>
</codearea>

So CDATA means it will ignore any character which could otherwise be interpreted as XML tag like < and > etc.

phpMyAdmin - Error > Incorrect format parameter?

If you use docker-compose just set UPLOAD_LIMIT

phpmyadmin:
    image: phpmyadmin/phpmyadmin
    environment:
        UPLOAD_LIMIT: 1G

Why do I get "a label can only be part of a statement and a declaration is not a statement" if I have a variable that is initialized after a label?

This is a quirk of the C grammar. A label (Cleanup:) is not allowed to appear immediately before a declaration (such as char *str ...;), only before a statement (printf(...);). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.

You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:

int main (void) 
{
    char *str;
    printf("Hello ");
    goto Cleanup;
Cleanup:
    str = "World\n";
    printf("%s\n", str);
    return 0;
}

IF function with 3 conditions

Using INDEX and MATCH for binning. Easier to maintain if we have more bins.

=INDEX({"Text 1","Text 2","Text 3"},MATCH(A2,{0,5,21,100}))

enter image description here

Func vs. Action vs. Predicate

Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.

Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).

Predicate is a special kind of Func often used for comparisons.

Though widely used with Linq, Action and Func are concepts logically independent of Linq. C++ already contained the basic concept in form of typed function pointers.

Here is a small example for Action and Func without using Linq:

class Program
{
    static void Main(string[] args)
    {
        Action<int> myAction = new Action<int>(DoSomething);
        myAction(123);           // Prints out "123"
                                 // can be also called as myAction.Invoke(123);

        Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
        Console.WriteLine(myFunc(5));   // Prints out "2.5"
    }

    static void DoSomething(int i)
    {
        Console.WriteLine(i);
    }

    static double CalculateSomething(int i)
    {
        return (double)i/2;
    }
}

Regex to check if valid URL that ends in .jpg, .png, or .gif

Actually.

Why are you checking the URL? That's no guarantee what you're going to get is an image, and no guarantee that the things you're rejecting aren't images. Try performing a HEAD request on it, and see what content-type it actually is.

How to load data from a text file in a PostgreSQL database?

Let consider that your data are in the file values.txt and that you want to import them in the database table myTable then the following query does the job

COPY myTable FROM 'value.txt' (DELIMITER('|'));

https://www.postgresql.org/docs/current/static/sql-copy.html

Click a button programmatically - JS

Though this question is rather old, here's a answer :)

What you are asking for can be achieved by using jQuery's .click() event method and .on() event method

So this could be the code:

// Set the global variables
var userImage = $("#img-giLkojRpuK");
var hangoutButton = $("#hangout-giLkojRpuK");

$(document).ready(function() {
    // When the document is ready/loaded, execute function

    // Hide hangoutButton
    hangoutButton.hide();

    // Assign "click"-event-method to userImage
    userImage.on("click", function() {
        console.log("in onclick");
        hangoutButton.click();
    });
});

Close pre-existing figures in matplotlib when running from eclipse

You can close a figure by calling matplotlib.pyplot.close, for example:

from numpy import *
import matplotlib.pyplot as plt
from scipy import *

t = linspace(0, 0.1,1000)
w = 60*2*pi


fig = plt.figure()
plt.plot(t,cos(w*t))
plt.plot(t,cos(w*t-2*pi/3))
plt.plot(t,cos(w*t-4*pi/3))
plt.show()
plt.close(fig)

You can also close all open figures by calling matplotlib.pyplot.close("all")

Max length for client ip address

For IPv4, you could get away with storing the 4 raw bytes of the IP address (each of the numbers between the periods in an IP address are 0-255, i.e., one byte). But then you would have to translate going in and out of the DB and that's messy.

IPv6 addresses are 128 bits (as opposed to 32 bits of IPv4 addresses). They are usually written as 8 groups of 4 hex digits separated by colons: 2001:0db8:85a3:0000:0000:8a2e:0370:7334. 39 characters is appropriate to store IPv6 addresses in this format.

Edit: However, there is a caveat, see @Deepak's answer for details about IPv4-mapped IPv6 addresses. (The correct maximum IPv6 string length is 45 characters.)

Find (and kill) process locking port 3000 on Mac

Easiest solution:

kill $(lsof -ti:3000,3001,8080)

For single port:

kill $(lsof -ti:3000)

#3000 is the port to be freed

Kill multiple ports with single line command:

kill $(lsof -ti:3000,3001)

#here multiple ports 3000 and 3001 are the ports to be freed

lsof -ti:3000

82500 (Process ID)

lsof -ti:3001

82499

lsof -ti:3001,3000

82499 82500

kill $(lsof -ti:3001,3000)

Terminates both 82499 and 82500 processes in a single command.

For using this in package.json scripts:

"scripts": { "start": "kill $(lsof -ti:3000,3001) && npm start" }

How to convert current date into string in java?

String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());

Extension exists but uuid_generate_v4 fails

The extension is available but not installed in this database.

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

How do I share a global variable between c files?

using extern <variable type> <variable name> in a header or another C file.

How to increment a letter N times per iteration and store in an array?

ord() will not work because your end string is two characters long.

Returns the ASCII value of the first character of string.

Watch it break.

From my testing, you need to check that the end string doesn't get "stepped over". The perl-style character incrementation is a cool method, but it is a single-stepping method. For this reason, an inner loop helps it along when necessary. This is actually not a bother, in fact, it is useful because we need to check if the loop(s) should be broken on each single step.

Code: (Demo)

function excelCols($letter,$end,$step=1){  // function doesn't check that $end is "later" than $letter
    if($step==0)return [];  // prevent infinite loop
    do{
        $letters[]=$letter;  // store letter
        for($x=0; $x<$step; ++$x){  // increment in accordance with $step declaration
            if($letter===$end)break(2);  // break if end is "stepped on"
            ++$letter;
        }
    }while(true);
    return $letters;    
}
echo implode(' ',excelCols('A','JJ',4));
echo "\n --- \n";
echo implode(' ',excelCols('A','BB',3));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',1));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',3));

Output:

A E I M Q U Y AC AG AK AO AS AW BA BE BI BM BQ BU BY CC CG CK CO CS CW DA DE DI DM DQ DU DY EC EG EK EO ES EW FA FE FI FM FQ FU FY GC GG GK GO GS GW HA HE HI HM HQ HU HY IC IG IK IO IS IW JA JE JI
 --- 
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ
 --- 
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z AA AB AC AD AE AF AG AH AI AJ AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ BA BB BC BD BE BF BG BH BI BJ BK BL BM BN BO BP BQ BR BS BT BU BV BW BX BY BZ CA CB CC CD CE CF CG CH CI CJ CK CL CM CN CO CP CQ CR CS CT CU CV CW CX CY CZ DA DB DC DD DE DF DG DH DI DJ DK DL DM DN DO DP DQ DR DS DT DU DV DW DX DY DZ EA EB EC ED EE EF EG EH EI EJ EK EL EM EN EO EP EQ ER ES ET EU EV EW EX EY EZ FA FB FC FD FE FF FG FH FI FJ FK FL FM FN FO FP FQ FR FS FT FU FV FW FX FY FZ GA GB GC GD GE GF GG GH GI GJ GK GL GM GN GO GP GQ GR GS GT GU GV GW GX GY GZ HA HB HC HD HE HF HG HH HI HJ HK HL HM HN HO HP HQ HR HS HT HU HV HW HX HY HZ IA IB IC ID IE IF IG IH II IJ IK IL IM IN IO IP IQ IR IS IT IU IV IW IX IY IZ JA JB JC JD JE JF JG JH JI JJ JK JL JM JN JO JP JQ JR JS JT JU JV JW JX JY JZ KA KB KC KD KE KF KG KH KI KJ KK KL KM KN KO KP KQ KR KS KT KU KV KW KX KY KZ LA LB LC LD LE LF LG LH LI LJ LK LL LM LN LO LP LQ LR LS LT LU LV LW LX LY LZ MA MB MC MD ME MF MG MH MI MJ MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NB NC ND NE NF NG NH NI NJ NK NL NM NN NO NP NQ NR NS NT NU NV NW NX NY NZ OA OB OC OD OE OF OG OH OI OJ OK OL OM ON OO OP OQ OR OS OT OU OV OW OX OY OZ PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ QA QB QC QD QE QF QG QH QI QJ QK QL QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ RA RB RC RD RE RF RG RH RI RJ RK RL RM RN RO RP RQ RR RS RT RU RV RW RX RY RZ SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO SP SQ SR SS ST SU SV SW SX SY SZ TA TB TC TD TE TF TG TH TI TJ TK TL TM TN TO TP TQ TR TS TT TU TV TW TX TY TZ UA UB UC UD UE UF UG UH UI UJ UK UL UM UN UO UP UQ UR US UT UU UV UW UX UY UZ VA VB VC VD VE VF VG VH VI VJ VK VL VM VN VO VP VQ VR VS VT VU VV VW VX VY VZ WA WB WC WD WE WF WG WH WI WJ WK WL WM WN WO WP WQ WR WS WT WU WV WW WX WY WZ XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ YA YB YC YD YE YF YG YH YI YJ YK YL YM YN YO YP YQ YR YS YT YU YV YW YX YY YZ ZA ZB ZC ZD ZE ZF ZG ZH ZI ZJ ZK ZL ZM ZN ZO ZP ZQ ZR ZS ZT ZU ZV ZW ZX ZY ZZ
 --- 
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ BC BF BI BL BO BR BU BX CA CD CG CJ CM CP CS CV CY DB DE DH DK DN DQ DT DW DZ EC EF EI EL EO ER EU EX FA FD FG FJ FM FP FS FV FY GB GE GH GK GN GQ GT GW GZ HC HF HI HL HO HR HU HX IA ID IG IJ IM IP IS IV IY JB JE JH JK JN JQ JT JW JZ KC KF KI KL KO KR KU KX LA LD LG LJ LM LP LS LV LY MB ME MH MK MN MQ MT MW MZ NC NF NI NL NO NR NU NX OA OD OG OJ OM OP OS OV OY PB PE PH PK PN PQ PT PW PZ QC QF QI QL QO QR QU QX RA RD RG RJ RM RP RS RV RY SB SE SH SK SN SQ ST SW SZ TC TF TI TL TO TR TU TX UA UD UG UJ UM UP US UV UY VB VE VH VK VN VQ VT VW VZ WC WF WI WL WO WR WU WX XA XD XG XJ XM XP XS XV XY YB YE YH YK YN YQ YT YW YZ ZC ZF ZI ZL ZO ZR ZU ZX

Here is an array-functions approach:

Code: (Demo)

$start='C';
$end='DD';
$step=4;

// generate and store more than we need (this is an obvious method disadvantage)
$result=$array=range('A','Z',1);  // store A - Z as $array and $result
foreach($array as $a){
    foreach($array as $b){
        $result[]="$a$b";  // store double letter combinations
        if(in_array($end,$result)){break(2);}  // stop asap
    }
}
//echo implode(' ',$result),"\n\n";

// slice away from the front of the array
$result=array_slice($result,array_search($start,$result));  // reindex keys
//echo implode(' ',$result),"\n\n";

 // punch out elements that are not "stepped on"
$result=array_filter($result,function($k)use($step){return $k%$step==0;},ARRAY_FILTER_USE_KEY); // use modulo

// result is ready
echo implode(' ',$result);

Output:

C G K O S W AA AE AI AM AQ AU AY BC BG BK BO BS BW CA CE CI CM CQ CU CY DC

inner join in linq to entities

You can find a whole bunch of Linq examples in visual studio. Just select Help -> Samples, and then unzip the Linq samples.

Open the linq samples solution and open the LinqSamples.cs of the SampleQueries project.

The answer you are looking for is in method Linq14:

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

var pairs =
   from a in numbersA
   from b in numbersB
   where a < b
   select new {a, b};

Can a foreign key be NULL and/or duplicate?

1 - Yes, since at least SQL Server 2000.

2 - Yes, as long as it's not a UNIQUE constraint or linked to a unique index.

How to fix libeay32.dll was not found error

I believe you need to put the libeay32.dll and ssleay32.dll files in the systems folder

SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN'

An expression of non-boolean type specified in a context where a condition is expected

I also got this error when I forgot to add ON condition when specifying my join clause.

Switch in Laravel 5 - Blade

In Laravel 5.1, this works in a Blade:

<?php
    switch( $machine->disposal ) {
        case 'DISPO': echo 'Send to Property Disposition'; break;
        case 'UNIT':  echo 'Send to Unit'; break;
        case 'CASCADE': echo 'Cascade the machine'; break;
        case 'TBD':   echo 'To Be Determined (TBD)'; break;
    }
?>

jQuery's .click - pass parameters to user function

      $imgReload.data('self', $self);
            $imgReload.click(function (e) {
                var $p = $(this).data('self');
                $p._reloadTable();
            });

Set javaScript object to onclick element:

 $imgReload.data('self', $self);

get Object from "this" element:

 var $p = $(this).data('self');

Color a table row with style="color:#fff" for displaying in an email

Rather than using direct tags, you can edit the css attribute for the color so that any tables you make will have the same color header text.

thead {
    color: #FFFFFF;
}

Is there a way to automatically build the package.json file for Node.js projects

First off, run

npm init

...will ask you a few questions (read this first) about your project/package and then generate a package.json file for you.

Then, once you have a package.json file, use

npm install <pkg> --save

or

npm install <pkg> --save-dev

...to install a dependency and automatically append it to your package.json's dependencies list.

(Note: You may need to manually tweak the version ranges for your dependencies.)

Set proxy through windows command line including login parameters

cmd

Tunnel all your internet traffic through a socks proxy:

netsh winhttp set proxy proxy-server="socks=localhost:9090" bypass-list="localhost"

View the current proxy settings:

netsh winhttp show proxy

Clear all proxy settings:

netsh winhttp reset proxy

How do you make a HTTP request with C++?

C and C++ don't have a standard library for HTTP or even for socket connections. Over the years some portable libraries have been developed. The most widely used, as others have said, is libcurl.

Here is a list of alternatives to libcurl (coming from the libcurl's web site).

Also, for Linux, this is a simple HTTP client. You could implement your own simple HTTP GET client, but this won't work if there are authentication or redirects involved or if you need to work behind a proxy. For these cases you need a full-blown library like libcurl.

For source code with libcurl, this is the closest to what you want (Libcurl has many examples). Look at the main function. The html content will be copied to the buffer, after a successfully connection. Just replace parseHtml with your own function.

SQLite table constraint - unique on multiple columns

If you already have a table and can't/don't want to recreate it for whatever reason, use indexes:

CREATE UNIQUE INDEX my_index ON my_table(col_1, col_2);

How to add a line break within echo in PHP?

The new line character is \n, like so:

echo __("Thanks for your email.\n<br />\n<br />Your order's details are below:", 'jigoshop');

How to start up spring-boot application via command line?

To run the spring-boot application, need to follow some step.

  1. Maven setup (ignore if already setup):

    a. Install maven from https://maven.apache.org/download.cgi

    b. Unzip maven and keep in C drive (you can keep any location. Path location will be changed accordingly).

    c. Set MAVEN_HOME in system variable. enter image description here

    d. Set path for maven

enter image description here

  1. Add Maven Plugin to POM.XML

    <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>

  2. Build Spring Boot Project with Maven

       maven package
    

    or

         mvn install / mvn clean install
    
  3. Run Spring Boot app using Maven:

        mvn spring-boot:run
    
  4. [optional] Run Spring Boot app with java -jar command

         java -jar target/mywebserviceapp-0.0.1-SNAPSHOT.jar
    

How to automatically update an application without ClickOnce?

A Lay men's way is

on Main() rename the executing assembly file .exe to some thing else check date and time of created. and the updated file date time and copy to the application folder.

//Rename he executing file
System.IO.FileInfo file = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);

System.IO.File.Move(file.FullName, file.DirectoryName + "\\" + file.Name.Replace(file.Extension,"") + "-1" + file.Extension);

then do the logic check and copy the new file to executing folder

How to center an iframe horizontally?

The simplest code to align the iframe element:

<div align="center"><iframe width="560" height="315" src="www.youtube.com" frameborder="1px"></iframe></div>

How to use Java property files?

In order:

  1. You can store the file pretty much anywhere.
  2. no extension is necessary.
  3. Montecristo has illustrated how to load this. That should work fine.
  4. propertyNames() gives you an enumeration to iterate through.

Passing parameters to addTarget:action:forControlEvents

You can replace target-action with a closure (block in Objective-C) by adding a helper closure wrapper (ClosureSleeve) and adding it as an associated object to the control so it gets retained. That way you can pass any parameters.

Swift 3

class ClosureSleeve {
    let closure: () -> ()

    init(attachTo: AnyObject, closure: @escaping () -> ()) {
        self.closure = closure
        objc_setAssociatedObject(attachTo, "[\(arc4random())]", self, .OBJC_ASSOCIATION_RETAIN)
    }

    @objc func invoke() {
        closure()
    }
}

extension UIControl {
    func addAction(for controlEvents: UIControlEvents, action: @escaping () -> ()) {
        let sleeve = ClosureSleeve(attachTo: self, closure: action)
        addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
    }
}

Usage:

button.addAction(for: .touchUpInside) {
    self.switchToNewsDetails(parameter: i)
}

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

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

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

   Adobe Reader Preferences dialog

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

   Adobe Reader Read Mode toolbar button

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

#toolbar=0&navpanes=0

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

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

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

Iterating Over Dictionary Key Values Corresponding to List in Python

You have several options for iterating over a dictionary.

If you iterate over the dictionary itself (for team in league), you will be iterating over the keys of the dictionary. When looping with a for loop, the behavior will be the same whether you loop over the dict (league) itself, or league.keys():

for team in league.keys():
    runs_scored, runs_allowed = map(float, league[team])

You can also iterate over both the keys and the values at once by iterating over league.items():

for team, runs in league.items():
    runs_scored, runs_allowed = map(float, runs)

You can even perform your tuple unpacking while iterating:

for team, (runs_scored, runs_allowed) in league.items():
    runs_scored = float(runs_scored)
    runs_allowed = float(runs_allowed)

How to return more than one value from a function in Python?

Return as a tuple, e.g.

def foo (a):
    x=a
    y=a*2
    return (x,y)

Convert InputStream to JSONObject

This worked for me:

JSONArray jsonarr = (JSONArray) new JSONParser().parse(new InputStreamReader(Nameofclass.class.getResourceAsStream(pathToJSONFile)));
JSONObject jsonobj = (JSONObject) new JSONParser().parse(new InputStreamReader(Nameofclass.class.getResourceAsStream(pathToJSONFile)));

git error: failed to push some refs to remote

In my case I misspelled the name of the branch. Locally I did something like:

git push --set-upstream origin feture/my-feature

where my branch name was missing the a in feature. I corrected it to:

git push --set-upstream origin feature/my-feature

And everything worked fine.

How to convert a set to a list in python?

Simply type:

list(my_set)

This will turn a set in the form {'1','2'} into a list in the form ['1','2'].

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

Really it's interesting. You need just use javax-mail.jar of "com.sun" not "javax.mail".
dwonload com.sun mail jar

How to scroll to the bottom of a UITableView on the iPhone before the view appears

No need for any scrolling you can just do it by using this code:

[YOURTABLEVIEWNAME setContentOffset:CGPointMake(0, CGFLOAT_MAX)];

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?

  • Check the other server's network configuration in SQL Server.
  • Check the other machines FIREWALL. SQL Server does not open ports automatically, so the windows firewall normally blocks access..

php convert datetime to UTC

As strtotime requires specific input format, DateTime::createFromFormat could be used (php 5.3+ is required)

// set timezone to user timezone
date_default_timezone_set($str_user_timezone);

// create date object using any given format
$date = DateTime::createFromFormat($str_user_dateformat, $str_user_datetime);

// convert given datetime to safe format for strtotime
$str_user_datetime = $date->format('Y-m-d H:i:s');

// convert to UTC
$str_UTC_datetime = gmdate($str_server_dateformat, strtotime($str_user_datetime));

// return timezone to server default
date_default_timezone_set($str_server_timezone);

How different is Objective-C from C++?

Short list of some of the major differences:

  • C++ allows multiple inheritance, Objective-C doesn't.
  • Unlike C++, Objective-C allows method parameters to be named and the method signature includes only the names and types of the parameters and return type (see bbum's and Chuck's comments below). In comparison, a C++ member function signature contains the function name as well as just the types of the parameters/return (without their names).
  • C++ uses bool, true and false, Objective-C uses BOOL, YES and NO.
  • C++ uses void* and nullptr, Objective-C prefers id and nil.
  • Objective-C uses "selectors" (which have type SEL) as an approximate equivalent to function pointers.
  • Objective-C uses a messaging paradigm (a la Smalltalk) where you can send "messages" to objects through methods/selectors.
  • Objective-C will happily let you send a message to nil, unlike C++ which will crash if you try to call a member function of nullptr
  • Objective-C allows for dynamic dispatch, allowing the class responding to a message to be determined at runtime, unlike C++ where the object a method is invoked upon must be known at compile time (see wilhelmtell's comment below). This is related to the previous point.
  • Objective-C allows autogeneration of accessors for member variables using "properties".
  • Objective-C allows assigning to self, and allows class initialisers (similar to constructors) to return a completely different class if desired. Contrast to C++, where if you create a new instance of a class (either implicitly on the stack, or explicitly through new) it is guaranteed to be of the type you originally specified.
  • Similarly, in Objective-C other classes may also dynamically alter a target class at runtime to intercept method calls.
  • Objective-C lacks the namespace feature of C++.
  • Objective-C lacks an equivalent to C++ references.
  • Objective-C lacks templates, preferring (for example) to instead allow weak typing in containers.
  • Objective-C doesn't allow implicit method overloading, but C++ does. That is, in C++ int foo (void) and int foo (int) define an implicit overload of the method foo, but to achieve the same in Objective-C requires the explicit overloads - (int) foo and - (int) foo:(int) intParam. This is due to Objective-C's named parameters being functionally equivalent to C++'s name mangling.
  • Objective-C will happily allow a method and a variable to share the same name, unlike C++ which will typically have fits. I imagine this is something to do with Objective-C using selectors instead of function pointers, and thus method names not actually having a "value".
  • Objective-C doesn't allow objects to be created on the stack - all objects must be allocated from the heap (either explicitly with an alloc message, or implicitly in an appropriate factory method).
  • Like C++, Objective-C has both structs and classes. However, where in C++ they are treated as almost exactly the same, in Objective-C they are treated wildly differently - you can create structs on the stack, for instance.

In my opinion, probably the biggest difference is the syntax. You can achieve essentially the same things in either language, but in my opinion the C++ syntax is simpler while some of Objective-C's features make certain tasks (such as GUI design) easier thanks to dynamic dispatch.

Probably plenty of other things too that I've missed, I'll update with any other things I think of. Other than that, can highly recommend the guide LiraNuna pointed you to. Incidentally, another site of interest might be this.

I should also point out that I'm just starting learning Objective-C myself, and as such a lot of the above may not quite be correct or complete - I apologise if that's the case, and welcome suggestions for improvement.

EDIT: updated to address the points raised in the following comments, added a few more items to the list.

How do you convert a JavaScript date to UTC?

The getTimezoneOffset() method returns the time zone difference, in minutes, from current locale (host system settings) to UTC.

Source: MDN web docs

This means that the offset is positive if the local timezone is behind UTC, and negative if it is ahead. For example, for time zone UTC+02:00, -120 will be returned.

_x000D_
_x000D_
let d = new Date();
console.log(d);
d.setTime(d.getTime() + (d.getTimezoneOffset() * 60000));
console.log(d);
_x000D_
_x000D_
_x000D_

NOTE: This will shift the date object time to UTC±00:00 and not convert its timezone so the date object timezone will still the same but the value will be in UTC±00:00.

Using a bitmask in C#

The traditional way to do this is to use the Flags attribute on an enum:

[Flags]
public enum Names
{
    None = 0,
    Susan = 1,
    Bob = 2,
    Karen = 4
}

Then you'd check for a particular name as follows:

Names names = Names.Susan | Names.Bob;

// evaluates to true
bool susanIsIncluded = (names & Names.Susan) != Names.None;

// evaluates to false
bool karenIsIncluded = (names & Names.Karen) != Names.None;

Logical bitwise combinations can be tough to remember, so I make life easier on myself with a FlagsHelper class*:

// The casts to object in the below code are an unfortunate necessity due to
// C#'s restriction against a where T : Enum constraint. (There are ways around
// this, but they're outside the scope of this simple illustration.)
public static class FlagsHelper
{
    public static bool IsSet<T>(T flags, T flag) where T : struct
    {
        int flagsValue = (int)(object)flags;
        int flagValue = (int)(object)flag;

        return (flagsValue & flagValue) != 0;
    }

    public static void Set<T>(ref T flags, T flag) where T : struct
    {
        int flagsValue = (int)(object)flags;
        int flagValue = (int)(object)flag;

        flags = (T)(object)(flagsValue | flagValue);
    }

    public static void Unset<T>(ref T flags, T flag) where T : struct
    {
        int flagsValue = (int)(object)flags;
        int flagValue = (int)(object)flag;

        flags = (T)(object)(flagsValue & (~flagValue));
    }
}

This would allow me to rewrite the above code as:

Names names = Names.Susan | Names.Bob;

bool susanIsIncluded = FlagsHelper.IsSet(names, Names.Susan);

bool karenIsIncluded = FlagsHelper.IsSet(names, Names.Karen);

Note I could also add Karen to the set by doing this:

FlagsHelper.Set(ref names, Names.Karen);

And I could remove Susan in a similar way:

FlagsHelper.Unset(ref names, Names.Susan);

*As Porges pointed out, an equivalent of the IsSet method above already exists in .NET 4.0: Enum.HasFlag. The Set and Unset methods don't appear to have equivalents, though; so I'd still say this class has some merit.


Note: Using enums is just the conventional way of tackling this problem. You can totally translate all of the above code to use ints instead and it'll work just as well.

LEFT OUTER JOIN in LINQ

Here is a fairly easy to understand version using method syntax:

IEnumerable<JoinPair> outerLeft =
    lefts.SelectMany(l => 
        rights.Where(r => l.Key == r.Key)
              .DefaultIfEmpty(new Item())
              .Select(r => new JoinPair { LeftId = l.Id, RightId = r.Id }));

Conversion from Long to Double in Java

Long i = 1000000;
String s = i + "";
Double d = Double.parseDouble(s);
Float f = Float.parseFloat(s);

This way we can convert Long type to Double or Float or Int without any problem because it's easy to convert string value to Double or Float or Int.

How to write subquery inside the OUTER JOIN Statement

I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .

While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output

Setting CSS pseudo-class rules from JavaScript

here is a solution including two functions: addCSSclass adds a new css class to the document, and toggleClass turns it on

The example shows adding a custom scrollbar to a div

_x000D_
_x000D_
// If newState is provided add/remove theClass accordingly, otherwise toggle theClass_x000D_
function toggleClass(elem, theClass, newState) {_x000D_
  var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');_x000D_
  var add = (arguments.length > 2 ? newState : (elem.className.match(matchRegExp) === null));_x000D_
_x000D_
  elem.className = elem.className.replace(matchRegExp, ''); // clear all_x000D_
  if (add) elem.className += ' ' + theClass;_x000D_
}_x000D_
_x000D_
function addCSSclass(rules) {_x000D_
  var style = document.createElement("style");_x000D_
  style.appendChild(document.createTextNode("")); // WebKit hack :(_x000D_
  document.head.appendChild(style);_x000D_
  var sheet = style.sheet;_x000D_
_x000D_
  rules.forEach((rule, index) => {_x000D_
    try {_x000D_
      if ("insertRule" in sheet) {_x000D_
        sheet.insertRule(rule.selector + "{" + rule.rule + "}", index);_x000D_
      } else if ("addRule" in sheet) {_x000D_
        sheet.addRule(rule.selector, rule.rule, index);_x000D_
      }_x000D_
    } catch (e) {_x000D_
      // firefox can break here          _x000D_
    }_x000D_
    _x000D_
  })_x000D_
}_x000D_
_x000D_
let div = document.getElementById('mydiv');_x000D_
addCSSclass([{_x000D_
    selector: '.narrowScrollbar::-webkit-scrollbar',_x000D_
    rule: 'width: 5px'_x000D_
  },_x000D_
  {_x000D_
    selector: '.narrowScrollbar::-webkit-scrollbar-thumb',_x000D_
    rule: 'background-color:#808080;border-radius:100px'_x000D_
  }_x000D_
]);_x000D_
toggleClass(div, 'narrowScrollbar', true);
_x000D_
<div id="mydiv" style="height:300px;width:300px;border:solid;overflow-y:scroll">_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed a eros metus. Nunc dui felis, accumsan nec aliquam quis, fringilla quis tellus. Nulla cursus mauris nibh, at faucibus justo tincidunt eget. Sed sodales eget erat consectetur consectetur. Vivamus_x000D_
  a diam volutpat, ullamcorper justo eu, dignissim ante. Aenean turpis tortor, fringilla quis efficitur eleifend, iaculis id quam. Quisque non turpis in lacus finibus auctor. Morbi ullamcorper felis ut nulla venenatis fringilla. Praesent imperdiet velit_x000D_
  nec sodales sodales. Etiam eget dui sollicitudin, tempus tortor non, porta nibh. Quisque eu efficitur velit. Nulla facilisi. Sed varius a erat ac volutpat. Sed accumsan maximus feugiat. Mauris id malesuada dui. Lorem ipsum dolor sit amet, consectetur_x000D_
  adipiscing elit. Sed a eros metus. Nunc dui felis, accumsan nec aliquam quis, fringilla quis tellus. Nulla cursus mauris nibh, at faucibus justo tincidunt eget. Sed sodales eget erat consectetur consectetur. Vivamus a diam volutpat, ullamcorper justo_x000D_
  eu, dignissim ante. Aenean turpis tortor, fringilla quis efficitur eleifend, iaculis id quam. Quisque non turpis in lacus finibus auctor. Morbi ullamcorper felis ut nulla venenatis fringilla. Praesent imperdiet velit nec sodales sodales. Etiam eget_x000D_
  dui sollicitudin, tempus tortor non, porta nibh. Quisque eu efficitur velit. Nulla facilisi. Sed varius a erat ac volutpat. Sed accumsan maximus feugiat. Mauris id malesuada dui._x000D_
</div>
_x000D_
_x000D_
_x000D_

Xcode Product -> Archive disabled

Change the active scheme Device from Simulator to Generic iOS Device

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

How do I create a nice-looking DMG for Mac OS X using command-line tools?

.DS_Store files stores windows settings in Mac. Windows settings include the icons layout, the window background, the size of the window, etc. The .DS_Store file is needed in creating the window for mounted images to preserve the arrangement of files and the windows background.

Once you have .DS_Store file created, you can just copy it to your created installer (DMG).

Finding the last index of an array

LINQ provides Last():

csharp> int[] nums = {1,2,3,4,5};
csharp> nums.Last();              
5

This is handy when you don't want to make a variable unnecessarily.

string lastName = "Abraham Lincoln".Split().Last();

Set min-width in HTML table's <td>

One way should be to add a <div style="min-width:XXXpx"> within the td, and let the <td style="width:100%">

Open two instances of a file in a single Visual Studio session

Here's how to do it...

  1. Select the tab you want two copies of
  2. Select menu Window ? New Window from the menu.
  3. Right click the new tab and select New Vertical Tab Group

If New Window is not listed in the *Window menu note that the command does exist, even as of Visual Studio 2017. Add it to the Window menu using menu Tools ? Customize ? Commands. At that point decide where to put the New Window command and select Add Command.

UPDATED on "30 July 2018"

In Visual Studio Code version 1.25.1 and later

Way 1

You can simple left click on your file in the side-panel (explorer) and press Ctrl + Enter.

Way 2

Simply right click on your file in the Visual Studio Code side-panel (explorer) and select the first option open to the side.

Remove non-ASCII characters from CSV

A perl oneliner would do: perl -i.bak -pe 's/[^[:ascii:]]//g' <your file>

-i says that the file is going to be edited inplace, and the backup is going to be saved with extension .bak.

Redirecting exec output to a buffer or file

You need to decide exactly what you want to do - and preferably explain it a bit more clearly.

Option 1: File

If you know which file you want the output of the executed command to go to, then:

  1. Ensure that the parent and child agree on the name (parent decides name before forking).
  2. Parent forks - you have two processes.
  3. Child reorganizes things so that file descriptor 1 (standard output) goes to the file.
  4. Usually, you can leave standard error alone; you might redirect standard input from /dev/null.
  5. Child then execs relevant command; said command runs and any standard output goes to the file (this is the basic shell I/O redirection).
  6. Executed process then terminates.
  7. Meanwhile, the parent process can adopt one of two main strategies:
    • Open the file for reading, and keep reading until it reaches an EOF. It then needs to double check whether the child died (so there won't be any more data to read), or hang around waiting for more input from the child.
    • Wait for the child to die and then open the file for reading.
    • The advantage of the first is that the parent can do some of its work while the child is also running; the advantage of the second is that you don't have to diddle with the I/O system (repeatedly reading past EOF).

Option 2: Pipe

If you want the parent to read the output from the child, arrange for the child to pipe its output back to the parent.

  1. Use popen() to do this the easy way. It will run the process and send the output to your parent process. Note that the parent must be active while the child is generating the output since pipes have a small buffer size (often 4-5 KB) and if the child generates more data than that while the parent is not reading, the child will block until the parent reads. If the parent is waiting for the child to die, you have a deadlock.
  2. Use pipe() etc to do this the hard way. Parent calls pipe(), then forks. The child sorts out the plumbing so that the write end of the pipe is its standard output, and ensures that all other file descriptors relating to the pipe are closed. This might well use the dup2() system call. It then executes the required process, which sends its standard output down the pipe.
  3. Meanwhile, the parent also closes the unwanted ends of the pipe, and then starts reading. When it gets EOF on the pipe, it knows the child has finished and closed the pipe; it can close its end of the pipe too.

Remove all stylings (border, glow) from textarea

if no luck with above try to it a class or even id something like textarea.foo and then your style. or try to !important

how to add script inside a php code?

You can just echo all the HTML as normal:

<?php
   echo '<input type="button" onclick="alert(\'Clicky!\')"/>';
?>

Automatically open default email client and pre-populate content

JQuery:

$(function () {
      $('.SendEmail').click(function (event) {
        var email = '[email protected]';
        var subject = 'Test';
        var emailBody = 'Hi Sample,';
        var attach = 'path';
        document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody+
            "?attach="+attach;
      });
    });

HTML:

 <button class="SendEmail">Send Email</button>

Failing to run jar file from command line: “no main manifest attribute”

Export you Java Project as an Runnable Jar file rather than Jar.

I exported my project as Jar and even though the Manifest was present it gave me the error no main manifest attribute in jar even though the Manifest file was present in the Jar. However there is only one entry in the Manifest file and it didn't specify the Main class or Function to execute or any dependent JAR's

After exporting it as Runnable Jar file it works as expected.

Adding :default => true to boolean in existing Rails column

I'm not sure when this was written, but currently to add or remove a default from a column in a migration, you can use the following:

change_column_null :products, :name, false

Rails 5:

change_column_default :products, :approved, from: true, to: false

http://edgeguides.rubyonrails.org/active_record_migrations.html#changing-columns

Rails 4.2:

change_column_default :products, :approved, false

http://guides.rubyonrails.org/v4.2/active_record_migrations.html#changing-columns

Which is a neat way of avoiding looking through your migrations or schema for the column specifications.

how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?

You can flush hosts local MySQL using following command:

mysqladmin -u [username] -p flush-hosts
**** [MySQL password]

or

mysqladmin flush-hosts -u [username] -p
**** [MySQL password]

Though Amazon RDS database server is on network then use the following command as like as flush network MySQL server:

mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts 

In additional suggestion you can permanently solve blocked of many connections error problem by editing my.ini file[Mysql configuration file]

change variables max_connections = 10000;

or

login into MySQL using command line -

mysql -u [username] -p
**** [MySQL password]

put the below command into MySQL window

SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;

check veritable using command-

show variables like "max_connections";
show variables like "max_connect_errors";

How do I use the Tensorboard callback of Keras?

This is how you use the TensorBoard callback:

from keras.callbacks import TensorBoard

tensorboard = TensorBoard(log_dir='./logs', histogram_freq=0,
                          write_graph=True, write_images=False)
# define model
model.fit(X_train, Y_train,
          batch_size=batch_size,
          epochs=nb_epoch,
          validation_data=(X_test, Y_test),
          shuffle=True,
          callbacks=[tensorboard])

swift How to remove optional String Character

Hello i have got the same issue i was getting Optional(3) So, i have tried this below code

cell.lbl_Quantity.text = "(data?.quantity!)" //"Optional(3)"

let quantity = data?.quantity

cell.lbl_Quantity.text = "(quantity!)" //"3"

500 Internal Server Error for php file not for html

It was changing the line endings (from Windows CRLF to Unix LF) in the .htaccess file that fixed it for me.

how to call scalar function in sql server 2008

You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.

select dbo.fun_functional_score('01091400003')

How to open some ports on Ubuntu?

Ubuntu these days comes with ufw - Uncomplicated Firewall. ufw is an easy-to-use method of handling iptables rules.

Try using this command to allow a port

sudo ufw allow 1701

To test connectivity, you could try shutting down the VPN software (freeing up the ports) and using netcat to listen, like this:

nc -l 1701

Then use telnet from your Windows host and see what shows up on your Ubuntu terminal. This can be repeated for each port you'd like to test.

How do I get first name and last name as whole name in a MYSQL query?

rtrim(lastname)+','+rtrim(firstname) as [Person Name]
from Table

the result will show lastname,firstname as one column header !

Twitter Bootstrap Multilevel Dropdown Menu

Updated Answer

* Updated answer which support the v2.1.1** bootstrap version stylesheet.

**But be careful because this solution has been removed from v3

Just wanted to point out that this solution is not needed anymore as the latest bootstrap now supports multi-level dropdowns by default. You can still use it if you're on older versions but for those who updated to the latest (v2.1.1 at the time of writing) it is not needed anymore. Here is a fiddle with the updated default multi-level dropdown straight from the documentation:

http://jsfiddle.net/2Smgv/2858/


Original Answer

There have been some issues raised on submenu support over at github and they are usually closed by the bootstrap developers, such as this one, so i think it is left to the developers using the bootstrap to work something out. Here is a demo i put together showing you how you can hack together a working sub-menu.

Relevant code

CSS

.dropdown-menu .sub-menu {
    left: 100%;
    position: absolute;
    top: 0;
    visibility: hidden;
    margin-top: -1px;
}

.dropdown-menu li:hover .sub-menu {
    visibility: visible;
    display: block;
}

.navbar .sub-menu:before {
    border-bottom: 7px solid transparent;
    border-left: none;
    border-right: 7px solid rgba(0, 0, 0, 0.2);
    border-top: 7px solid transparent;
    left: -7px;
    top: 10px;
}
.navbar .sub-menu:after {
    border-top: 6px solid transparent;
    border-left: none;
    border-right: 6px solid #fff;
    border-bottom: 6px solid transparent;
    left: 10px;
    top: 11px;
    left: -6px;
}

Created my own .sub-menu class to apply to the 2-level drop down menus, this way we can position them next to our menu items. Also modified the arrow to display it on the left of the submenu group.

Demo

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

If you are looking for a very simple lastIndex lookup with RegExp and don't care if it mimics lastIndexOf to the last detail, this may catch your attention.

I simply reverse the string, and subtract the first occurence index from length - 1. It happens to pass my test, but I think there could arise a performance issue with long strings.

interface String {
  reverse(): string;
  lastIndex(regex: RegExp): number;
}

String.prototype.reverse = function(this: string) {
  return this.split("")
    .reverse()
    .join("");
};

String.prototype.lastIndex = function(this: string, regex: RegExp) {
  const exec = regex.exec(this.reverse());
  return exec === null ? -1 : this.length - 1 - exec.index;
};

How to create a private class method?

Just for the completeness, we can also avoid declaring private_class_method in a separate line. I personally don't like this usage but good to know that it exists.

private_class_method  def self.method_name
 ....
end

"Could not find acceptable representation" using spring-boot-starter-web

In my case I was sending in correct object in ResponseEntity<>().

Correct :

@PostMapping(value = "/get-customer-details", produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> getCustomerDetails(@RequestBody String requestMessage) throws JSONException {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("customerId", "123");
    jsonObject.put("mobileNumber", "XXX-XXX-XXXX");
    return new ResponseEntity<>(jsonObject.toString(), HttpStatus.OK);
}

Incorrect :

return new ResponseEntity<>(jsonObject, HttpStatus.OK);

Because, jsonObject's toString() method "Encodes the jsonObject as a compact JSON string". Therefore, Spring returns json string directly without any further serialization.

When we send jsonObject instead, Spring tries to serialize it based on produces method used in RequestMapping and fails due to it "Could not find acceptable representation".

Get characters after last / in url

You can use substr and strrchr:

$url = 'http://www.vimeo.com/1234567';
$str = substr(strrchr($url, '/'), 1);
echo $str;      // Output: 1234567

Get string after character

This should work:

your_str='GenFiltEff=7.092200e-01'
echo $your_str | cut -d "=" -f2

How do I copy an entire directory of files into an existing directory using Python?

Here's a solution that's part of the standard library:

from distutils.dir_util import copy_tree
copy_tree("/a/b/c", "/x/y/z")

See this similar question.

Copy directory contents into a directory with python

How to correctly save instance state of Fragments in back stack?

Thanks to DroidT, I made this:

I realize that if the Fragment does not execute onCreateView(), its view is not instantiated. So, if the fragment on back stack did not create its views, I save the last stored state, otherwise I build my own bundle with the data I want to save/restore.

1) Extend this class:

import android.os.Bundle;
import android.support.v4.app.Fragment;

public abstract class StatefulFragment extends Fragment {

    private Bundle savedState;
    private boolean saved;
    private static final String _FRAGMENT_STATE = "FRAGMENT_STATE";

    @Override
    public void onSaveInstanceState(Bundle state) {
        if (getView() == null) {
            state.putBundle(_FRAGMENT_STATE, savedState);
        } else {
            Bundle bundle = saved ? savedState : getStateToSave();

            state.putBundle(_FRAGMENT_STATE, bundle);
        }

        saved = false;

        super.onSaveInstanceState(state);
    }

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);

        if (state != null) {
            savedState = state.getBundle(_FRAGMENT_STATE);
        }
    }

    @Override
    public void onDestroyView() {
        savedState = getStateToSave();
        saved = true;

        super.onDestroyView();
    }

    protected Bundle getSavedState() {
        return savedState;
    }

    protected abstract boolean hasSavedState();

    protected abstract Bundle getStateToSave();

}

2) In your Fragment, you must have this:

@Override
protected boolean hasSavedState() {
    Bundle state = getSavedState();

    if (state == null) {
        return false;
    }

    //restore your data here

    return true;
}

3) For example, you can call hasSavedState in onActivityCreated:

@Override
public void onActivityCreated(Bundle state) {
    super.onActivityCreated(state);

    if (hasSavedState()) {
        return;
    }

    //your code here
}

jQuery equivalent of JavaScript's addEventListener method

As of jQuery 1.7, .on() is now the preferred method of binding events, rather than .bind():

From http://api.jquery.com/bind/:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

The documentation page is located at http://api.jquery.com/on/

How to get main window handle from process id?

Here, I would like to add that if you are reading window handle that is HWND of a process then that process should not be running in a debugging otherwise it will not find the window handle by using FindWindowEx.

failed to find target with hash string android-23

Ensure the IDE recognizes that you have the package. It didn't on mine even after downloading 28, so I uninstalled then reinstalled it after realizing it wasn't showing up under File-Project Structure-Modules-App as a choice for SDK.

On top of that, you may want to change your build path to match.

Slightly related, the latest updates seem able to compile when I forced an update all the way to 28 for CompileSDK, and not just up to the new API 26 min requirement from Google Play. This is related to dependencies though, and might not affect yours

"commence before first target. Stop." error

This means that there is a line which starts with a space, tab, or some other whitespace without having a target in front of it.

How to provide user name and password when connecting to a network share

You can either change the thread identity, or P/Invoke WNetAddConnection2. I prefer the latter, as I sometimes need to maintain multiple credentials for different locations. I wrap it into an IDisposable and call WNetCancelConnection2 to remove the creds afterwards (avoiding the multiple usernames error):

using (new NetworkConnection(@"\\server\read", readCredentials))
using (new NetworkConnection(@"\\server2\write", writeCredentials)) {
   File.Copy(@"\\server\read\file", @"\\server2\write\file");
}

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

For Loop on Lua

By reading online (tables tutorial) it seems tables behave like arrays so you're looking for:

Way1

names = {'John', 'Joe', 'Steve'}
for i = 1,3 do print( names[i] ) end

Way2

names = {'John', 'Joe', 'Steve'}
for k,v in pairs(names) do print(v) end

Way1 uses the table index/key , on your table names each element has a key starting from 1, for example:

names = {'John', 'Joe', 'Steve'}
print( names[1] ) -- prints John

So you just make i go from 1 to 3.

On Way2 instead you specify what table you want to run and assign a variable for its key and value for example:

names = {'John', 'Joe', myKey="myValue" }
for k,v in pairs(names) do print(k,v) end

prints the following:

1   John
2   Joe
myKey   myValue

Fatal error: Call to undefined function mb_strlen()

For me, this worked in Ubuntu 14.04 and for php5.6:

$ sudo apt-get install php5.6-mbstring

java - iterating a linked list

Each java.util.List implementation is required to preserve the order so either you are using ArrayList, LinkedList, Vector, etc. each of them are ordered collections and each of them preserve the order of insertion (see http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html)

How can I count all the lines of code in a directory recursively?

You can use a utility called codel (link). It's a simple Python module to count lines with colorful formatting.

Installation

pip install codel

Usage

To count lines of C++ files (with .cpp and .h extensions), use:

codel count -e .cpp .h

You can also ignore some files/folder with the .gitignore format:

codel count -e .py -i tests/**

It will ignore all the files in the tests/ folder.

The output looks like:

Long output

You also can shorten the output with the -s flag. It will hide the information of each file and show only information about each extension. The example is below:

Short output

How to replace a string in an existing file in Perl?

$_='~s/blue/red/g';

Uh, what??

Just

s/blue/red/g;

or, if you insist on using a variable (which is not necessary when using $_, but I just want to show the right syntax):

$_ =~ s/blue/red/g;

Get value of a string after last slash in JavaScript

String path ="AnyDirectory/subFolder/last.htm";
int pos = path.lastIndexOf("/") + 1;

path.substring(pos, path.length()-pos) ;

Now you have the last.htm in the path string.

How do I style (css) radio buttons and labels?

This will get your buttons and labels next to each other, at least. I believe the second part can't be done in css alone, and will need javascript. I found a page that might help you with that part as well, but I don't have time right now to try it out: http://www.webmasterworld.com/forum83/6942.htm

<style type="text/css">
.input input {
  float: left;
}
.input label {
  margin: 5px;
}
</style>
<div class="input radio">
    <fieldset>
        <legend>What color is the sky?</legend>
        <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1"  />
        <label for="SubmitQuestion1">A strange radient green.</label>

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2"  />
        <label for="SubmitQuestion2">A dark gloomy orange</label>
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3"  />
        <label for="SubmitQuestion3">A perfect glittering blue</label>
    </fieldset>
</div>

How to set image button backgroundimage for different state?

you can create selector file in res/drawable

example: res/drawable/selector_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/btn_disabled" android:state_enabled="false" />
    <item android:drawable="@drawable/btn_enabled" />
</selector>

and in layout activity, fragment or etc

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/selector_bg_rectangle_black"/>

Transpose a matrix in Python

Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)

import numpy as np

a = np.array([(1,2,3), (4,5,6)])

b = a.transpose()

Returning from a void function

The first way is "more correct", what intention could there be to express? If the code ends, it ends. That's pretty clear, in my opinion.

I don't understand what could possibly be confusing and need clarification. If there's no looping construct being used, then what could possibly happen other than that the function stops executing?

I would be severly annoyed by such a pointless extra return statement at the end of a void function, since it clearly serves no purpose and just makes me feel the original programmer said "I was confused about this, and now you can be too!" which is not very nice.

How to remove docker completely from ubuntu 14.04

sudo apt-get remove docker docker-engine docker.io containerd runc
sudo rm -rf /var/lib/docker
sudo apt-get autoclean
sudo apt-get update

Remove Duplicate objects from JSON Array

Reviving an old question, but I wanted to post an iteration on @adeneo's answer. That answer is completely general, but for this use case it could be more efficient (it's slow on my machine with an array of a few thousand objects). If you know the specific properties of the objects you need to compare, just compare them directly:

var sl = standardsList;
var out = [];

for (var i = 0, l = sl.length; i < l; i++) {
    var unique = true;
    for (var j = 0, k = out.length; j < k; j++) {
        if ((sl[i].Grade === out[j].Grade) && (sl[i].Domain === out[j].Domain)) {
            unique = false;
        }
    }
    if (unique) {
        out.push(sl[i]);
    }
}

console.log(sl.length); // 10
console.log(out.length); // 5

Remove all newlines from inside a string

strip only removes characters from the beginning and end of a string. You want to use replace:

str2 = str.replace("\n", "")
re.sub('\s{2,}', ' ', str) # To remove more than one space 

Using port number in Windows host file

The hosts file is for host name resolution only (on Windows as well as on Unix-like systems). You cannot put port numbers in there, and there is no way to do what you want with generic OS-level configuration - the browser is what selects the port to choose.

So use bookmarks or something like that.
(Some firewall/routing software might allow outbound port redirection, but that doesn't really sound like an appealing option for this.)

How to initialize an array of custom objects

Maybe you mean like this? I like to make an object and use Format-Table:

> $array = @()
> $object = New-Object -TypeName PSObject
> $object | Add-Member -Name 'Name' -MemberType Noteproperty -Value 'Joe'
> $object | Add-Member -Name 'Age' -MemberType Noteproperty -Value 32
> $object | Add-Member -Name 'Info' -MemberType Noteproperty -Value 'something about him'
> $array += $object
> $array | Format-Table

Name                                                                        Age Info
----                                                                        --- ----
Joe                                                                          32  something about him

This will put all objects you have in the array in columns according to their properties.

Tip: Using -auto sizes the table better

> $array | Format-Table -Auto

Name Age Info
---- --- ----
Joe   32 something about him

You can also specify which properties you want in the table. Just separate each property name with a comma:

> $array | Format-Table Name, Age -Auto

Name Age
---- ---
Joe   32

Javascript: best Singleton pattern

Extending the above post by Tom, if you need a class type declaration and access the singleton instance using a variable, the code below might be of help. I like this notation as the code is little self guiding.

function SingletonClass(){
    if ( arguments.callee.instance )
        return arguments.callee.instance;
    arguments.callee.instance = this;
}


SingletonClass.getInstance = function() {
    var singletonClass = new SingletonClass();
    return singletonClass;
};

To access the singleton, you would

var singleTon = SingletonClass.getInstance();

Remove end of line characters from Java string

Did you try

string.trim(); 

This is meant to trim all leading and leaning while spaces in the string. Hope this helps.

Edit: (I was not explicit enough)

So, when you string.split(), you will have a string[] - for each of the strings in the array, do a string.trim() and then append it.

String[] tokens = yourString.split(" ");
StringBuffer buff = new StringBuffer();
for (String token : tokens)
{
  buff.append(token.trim());
}

Use stringBuffer/Builder instead of appending in the same string.

What is the difference between persist() and merge() in JPA and Hibernate?

The most important difference is this:

  • In case of persist method, if the entity that is to be managed in the persistence context, already exists in persistence context, the new one is ignored. (NOTHING happened)

  • But in case of merge method, the entity that is already managed in persistence context will be replaced by the new entity (updated) and a copy of this updated entity will return back. (from now on any changes should be made on this returned entity if you want to reflect your changes in persistence context)

Databound drop down list - initial value

I know this already has a chosen answer - but I wanted to toss in my two cents. I have a databound dropdown list:

<asp:DropDownList 
  id="country" 
  runat="server" 
  CssClass="selectOne" 
  DataSourceID="country_code" 
  DataTextField="Name" 
  DataValueField="CountryCode_PK"
></asp:DropDownList>
<asp:SqlDataSource 
  id="country_code" 
  runat="server" 
  ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
  SelectCommand="SELECT CountryCode_PK, CountryCode_PK + ' - ' + Name AS N'Name' FROM TBL_Country ORDER BY CountryCode_PK"
></asp:SqlDataSource>

In the codebehind, I have this - (which selects United States by default):

if (this.IsPostBack)
{
  //handle posted data
}
else 
{
  country.SelectedValue = "US";
}

The page initially loads based on the 'US' value rather than trying to worry about a selectedIndex (what if another item is added into the data table - I don't want to have to re-code)

Connecting to Oracle Database through C#?

The next approach work to me with Visual Studio 2013 Update 4 1- From Solution Explorer right click on References then select add references 2- Assemblies > Framework > System.Data.OracleClient > OK and after that you free to add using System.Data.OracleClient in your application and deal with database like you do with Sql Server database except changing the prefix from Sql to Oracle as in SqlCommand become OracleCommand for example to link to Oracle XE

OracleConnection oraConnection = new OracleConnection(@"Data Source=XE; User ID=system; Password=*myPass*");
public void Open()
{
if (oraConnection.State != ConnectionState.Open)
{
oraConnection.Open();
}
}
public void Close()
{
if (oraConnection.State == ConnectionState.Open)
{
oraConnection.Close();
}}

and to execute some command like INSERT, UPDATE, or DELETE using stored procedure we can use the following method

public void ExecuteCMD(string storedProcedure, OracleParameter[] param)
{
OracleCommand oraCmd = new OracleCommand();
oraCmd,CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = storedProcedure;
oraCmd.Connection = oraConnection;

if(param!=null)
{
oraCmd.Parameters.AddRange(param);
}
try
{
oraCmd.ExecuteNoneQuery();
}
catch (Exception)
{
MessageBox.Show("Sorry We've got Unknown Error","Connection Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}

Exact difference between CharSequence and String in java

Consider UTF-8. In UTF-8 Unicode code points are built from one or more bytes. A class encapsulating a UTF-8 byte array can implement the CharSequence interface but is most decidedly not a String. Certainly you can't pass a UTF-8 byte array where a String is expected but you certainly can pass a UTF-8 wrapper class that implements CharSequence when the contract is relaxed to allow a CharSequence. On my project, I am developing a class called CBTF8Field (Compressed Binary Transfer Format - Eight Bit) to provide data compression for xml and am looking to use the CharSequence interface to implement conversions from CBTF8 byte arrays to/from character arrays (UTF-16) and byte arrays (UTF-8).

The reason I came here was to get a complete understanding of the subsequence contract.

How to securely save username/password (local)?

I wanted to encrypt and decrypt the string as a readable string.

Here is a very simple quick example in C# Visual Studio 2019 WinForms based on the answer from @Pradip.

Right click project > properties > settings > Create a username and password setting.

enter image description here

Now you can leverage those settings you just created. Here I save the username and password but only encrypt the password in it's respectable value field in the user.config file.

Example of the encrypted string in the user.config file.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <secure_password_store.Properties.Settings>
            <setting name="username" serializeAs="String">
                <value>admin</value>
            </setting>
            <setting name="password" serializeAs="String">
                <value>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAQpgaPYIUq064U3o6xXkQOQAAAAACAAAAAAAQZgAAAAEAACAAAABlQQ8OcONYBr9qUhH7NeKF8bZB6uCJa5uKhk97NdH93AAAAAAOgAAAAAIAACAAAAC7yQicDYV5DiNp0fHXVEDZ7IhOXOrsRUbcY0ziYYTlKSAAAACVDQ+ICHWooDDaUywJeUOV9sRg5c8q6/vizdq8WtPVbkAAAADciZskoSw3g6N9EpX/8FOv+FeExZFxsm03i8vYdDHUVmJvX33K03rqiYF2qzpYCaldQnRxFH9wH2ZEHeSRPeiG</value>
            </setting>
        </secure_password_store.Properties.Settings>
    </userSettings>
</configuration>

enter image description here

Full Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace secure_password_store
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Login_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                Properties.Settings.Default.username = textBox1.Text;
                Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
                Properties.Settings.Default.Save();
            }
            else if (checkBox1.Checked == false)
            {
                Properties.Settings.Default.username = "";
                Properties.Settings.Default.password = "";
                Properties.Settings.Default.Save();
            }
            MessageBox.Show("{\"data\": \"some data\"}","Login Message Alert",MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void DecryptString_Click(object sender, EventArgs e)
        {
            SecureString password = DecryptString(Properties.Settings.Default.password);
            string readable = ToInsecureString(password);
            textBox4.AppendText(readable + Environment.NewLine);
        }
        private void Form_Load(object sender, EventArgs e)
        {
            //textBox1.Text = "UserName";
            //textBox2.Text = "Password";
            if (Properties.Settings.Default.username != string.Empty)
            {
                textBox1.Text = Properties.Settings.Default.username;
                checkBox1.Checked = true;
                SecureString password = DecryptString(Properties.Settings.Default.password);
                string readable = ToInsecureString(password);
                textBox2.Text = readable;
            }
            groupBox1.Select();
        }


        static byte[] entropy = Encoding.Unicode.GetBytes("SaLtY bOy 6970 ePiC");

        public static string EncryptString(SecureString input)
        {
            byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(ToInsecureString(input)),entropy,DataProtectionScope.CurrentUser);
            return Convert.ToBase64String(encryptedData);
        }

        public static SecureString DecryptString(string encryptedData)
        {
            try
            {
                byte[] decryptedData = ProtectedData.Unprotect(Convert.FromBase64String(encryptedData),entropy,DataProtectionScope.CurrentUser);
                return ToSecureString(Encoding.Unicode.GetString(decryptedData));
            }
            catch
            {
                return new SecureString();
            }
        }

        public static SecureString ToSecureString(string input)
        {
            SecureString secure = new SecureString();
            foreach (char c in input)
            {
                secure.AppendChar(c);
            }
            secure.MakeReadOnly();
            return secure;
        }

        public static string ToInsecureString(SecureString input)
        {
            string returnValue = string.Empty;
            IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
            try
            {
                returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
            }
            finally
            {
                System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
            }
            return returnValue;
        }

        private void EncryptString_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.password = EncryptString(ToSecureString(textBox2.Text));
            textBox3.AppendText(Properties.Settings.Default.password.ToString() + Environment.NewLine);
        }
    }
}

Update query using Subquery in Sql Server

because you are just learning I suggest you practice converting a SELECT joins to UPDATE or DELETE joins. First I suggest you generate a SELECT statement joining these two tables:

SELECT *
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

Then note that we have two table aliases a and b. Using these aliases you can easily generate UPDATE statement to update either table a or b. For table a you have an answer provided by JW. If you want to update b, the statement will be:

UPDATE  b
SET     b.marks = a.marks
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

Now, to convert the statement to a DELETE statement use the same approach. The statement below will delete from a only (leaving b intact) for those records that match by name:

DELETE a
FROM    tempDataView a
        INNER JOIN tempData b
            ON a.Name = b.Name

You can use the SQL Fiddle created by JW as a playground

python requests file upload

In Ubuntu you can apply this way,

to save file at some location (temporary) and then open and send it to API

      path = default_storage.save('static/tmp/' + f1.name, ContentFile(f1.read()))
      path12 = os.path.join(os.getcwd(), "static/tmp/" + f1.name)
      data={} #can be anything u want to pass along with File
      file1 = open(path12, 'rb')
      header = {"Content-Disposition": "attachment; filename=" + f1.name, "Authorization": "JWT " + token}
       res= requests.post(url,data,header)

Android: show soft keyboard automatically when focus is on an EditText

I created nice kotlin-esqe extension functions incase anyone is interested

fun Activity.hideKeyBoard() {
    val view = this.currentFocus
    val methodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

fun Activity.showKeyboard() {
    val view = this.currentFocus
    val methodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

PHP Foreach Arrays and objects

Recursive traverse object or array with array or objects elements:

function traverse(&$objOrArray)
{
    foreach ($objOrArray as $key => &$value)
    {
        if (is_array($value) || is_object($value))
        {
            traverse($value);
        }
        else
        {
            // DO SOMETHING
        }
    }
}

How to float 3 divs side by side using CSS?

try to add "display: block" to the style

<style>
   .left{
          display: block;
          float:left; 
          width:33%;
    }
</style>


<div class="left">...</div>
<div class="left">...</div>
<div class="left">...</div>

See line breaks and carriage returns in editor

:set list in Vim will show whitespace. End of lines show as '$' and carriage returns usually show as '^M'.

Play sound file in a web-page in the background

If you don't want to show controls then try this code

<audio  autoplay>
 <source src="song.ogg"  type="audio/ogg">
Your browser does not support the audio element.
</audio>

How to make an autocomplete address field with google maps api?

Like others have mentioned, the Google Places Autocomplete API is missing some important functions. Case in point, Google will not validate that the street number is real, and they also will not put it into a standardized format. So, it is the user's responsibility to enter that portion of the address correctly.

Google also won't predict PO Boxes or apartment numbers. So, if you are using their API for shipping, address cleansing or data governance, you may want one that will validate the building number, autocomplete the unit number and standardize the information.

Full Disclosure, I work for SmartyStreets

Difference Between Schema / Database in MySQL

Depends on the database server. MySQL doesn't care, its basically the same thing.

Oracle, DB2, and other enterprise level database solutions make a distinction. Usually a schema is a collection of tables and a Database is a collection of schemas.

using OR and NOT in solr query

I don't know why that doesn't work, but this one is logically equivalent and it does work:

-(myField:superneat AND -myOtherField:somethingElse)

Maybe it has something to do with defining the same field twice in the query...

Try asking in the solr-user group, then post back here the final answer!

How do I create a crontab through a script

As a correction to those suggesting crontab -l | crontab -: This does not work on every system. For example, I had to add a job to the root crontab on dozens of servers running an old version SUSE (don't ask why). Old SUSEs prepend comment lines to the output of crontab -l, making crontab -l | crontab - non-idempotent (Debian recognizes this problem in the crontab manpage and patched its version of Vixie Cron to change the default behaviour of crontab -l).

To edit crontabs programmatically on systems where crontab -l adds comments, you can try the following:

EDITOR=cat crontab -e > old_crontab; cat old_crontab new_job | crontab -

EDITOR=cat tells crontab to use cat as an editor (not the usual default vi), which doesn't change the file, but instead copies it to stdout. This might still fail if crontab - expects input in a format different from what crontab -e outputs. Do not try to replace the final crontab - with crontab -e - it will not work.

Display array values in PHP

You can use implode to return your array with a string separator.

$withComma = implode(",", $array);

echo $withComma;
// Will display apple,banana,orange

Re-sign IPA (iPhone)

I successfully followed this answer, but since entitlements have changed, I simply removed the --entitlements "Payload/Application.app/Entitlements.plist" part of the second to last statement, and it worked like a charm.

How to print an unsigned char in C?

Because char is by default signed declared that means the range of the variable is

-127 to +127>

your value is overflowed. To get the desired value you have to declared the unsigned modifier. the modifier's (unsigned) range is:

 0 to 255

to get the the range of any data type follow the process 2^bit example charis 8 bit length to get its range just 2 ^(power) 8.

SonarQube Exclude a directory

what version of sonar are you using? There is one option called "sonar.skippedModules=yourmodulename".

This will skip the whole module. So be aware of it.

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

Convert .pfx to .cer

the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.

How to validate an email address using a regular expression?

Just about every RegEx I've seen - including some used by Microsoft will not allow the following valid email to get through : [email protected]

Just had a real customer with an email address in this format who couldn't place an order.

Here's what I settled on:

  • A minimal Regex that won't have false negatives. Alternatively use the MailAddress constructor with some additional checks (see below):
  • Checking for common typos .cmo or .gmial.com and asking for confirmation Are you sure this is your correct email address. It looks like there may be a mistake. Allow the user to accept what they typed if they are sure.
  • Handling bounces when the email is actually sent and manually verifying them to check for obvious mistakes.

        try
        {
            var email = new MailAddress(str);

            if (email.Host.EndsWith(".cmo"))
            {
                return EmailValidation.PossibleTypo;
            }

            if (!email.Host.EndsWith(".") && email.Host.Contains("."))
            {
                return EmailValidation.OK;
            }
        }
        catch
        {
            return EmailValidation.Invalid;
        }

How to append elements into a dictionary in Swift?

There is no function to append the data in dictionary. You just assign the value against new key in existing dictionary. it will automatically add value to the dictionary.

var param  = ["Name":"Aloha","user" : "Aloha 2"]
param["questions"] = "Are you mine?"
print(param)

The output will be like

["Name":"Aloha","user" : "Aloha 2","questions" : ""Are you mine"?"]

how to add jquery in laravel project

In Laravel 6 you can get it like this:

try {
    window.$ = window.jQuery = require('jquery');
} catch (e) {}

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

The following code uses both data.table and fastmatch for increased speed.

library("data.table")
library("fastmatch")

a1 <- setDT(data.frame(a = 1:5, b=letters[1:5]))
a2 <- setDT(data.frame(a = 1:3, b=letters[1:3]))

compare_rows <- a1$a %fin% a2$a
# the %fin% function comes from the `fastmatch` package

added_rows <- a1[which(compare_rows == FALSE)]

added_rows

#    a b
# 1: 4 d
# 2: 5 e

React onClick function fires on render

Because you are calling that function instead of passing the function to onClick, change that line to this:

<button type="submit" onClick={() => { this.props.removeTaskFunction(todo) }}>Submit</button>

=> called Arrow Function, which was introduced in ES6, and will be supported on React 0.13.3 or upper.

Can I assume (bool)true == (int)1 for any C++ compiler?

Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."

Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...

Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as ints that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h> only require zero or non-zero, not necessarily zero or one.

If you cast that to bool, zero will convert to false, and non-zero to true (as you'd expect).

Open Cygwin at a specific folder

based on @LindseyD answer I created a simple BAT file, that opens cygwin in current directory, it may be useful (for me it is). Assuming that You have cygwin's bin directory in PATH.

FOR /F %%x IN ('sh -c pwd') DO bash -l -i -c 'cd %%x; exec bash'

Angular 4/5/6 Global Variables

You can access Globals entity from any point of your App via Angular dependency injection. If you want to output Globals.role value in some component's template, you should inject Globals through the component's constructor like any service:

// hello.component.ts
import { Component } from '@angular/core';
import { Globals } from './globals';

@Component({
  selector: 'hello',
  template: 'The global role is {{globals.role}}',
  providers: [ Globals ] // this depends on situation, see below
})

export class HelloComponent {
  constructor(public globals: Globals) {}
}

I provided Globals in the HelloComponent, but instead it could be provided in some HelloComponent's parent component or even in AppModule. It will not matter until your Globals has only static data that could not be changed (say, constants only). But if it's not true and for example different components/services might want to change that data, then the Globals must be a singleton. In that case it should be provided in the topmost level of the hierarchy where it is going to be used. Let's say this is AppModule:

import { Globals } from './globals'

@NgModule({
  // ... imports, declarations etc
  providers: [
    // ... other global providers
    Globals // so do not provide it into another components/services if you want it to be a singleton
  ]
})

Also, it's impossible to use var the way you did, it should be

// globals.ts
import { Injectable } from '@angular/core';

@Injectable()
export class Globals {
  role: string = 'test';
}

Update

At last, I created a simple demo on stackblitz, where single Globals is being shared between 3 components and one of them can change the value of Globals.role.

How to split a string with any whitespace chars as delimiters

In most regex dialects there are a set of convenient character summaries you can use for this kind of thing - these are good ones to remember:

\w - Matches any word character.

\W - Matches any nonword character.

\s - Matches any white-space character.

\S - Matches anything but white-space characters.

\d - Matches any digit.

\D - Matches anything except digits.

A search for "Regex Cheatsheets" should reward you with a whole lot of useful summaries.

CSS change button style after click

What is the code of your button? If it's an a tag, then you could do this:

_x000D_
_x000D_
a {_x000D_
  padding: 5px;_x000D_
  background: green;_x000D_
}_x000D_
a:visited {_x000D_
  background: red;_x000D_
}
_x000D_
<a href="#">A button</a>
_x000D_
_x000D_
_x000D_

Or you could use jQuery to add a class on click, as below:

_x000D_
_x000D_
$("#button").click(function() {_x000D_
  $("#button").addClass('button-clicked');_x000D_
});
_x000D_
.button-clicked {_x000D_
  background: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="button">Button</button>
_x000D_
_x000D_
_x000D_

Changing Underline color

No. The best you can do is to use a border-bottom with a different color, but that isn't really underlining.

How to replace NaNs by preceding values in pandas DataFrame?

You can use pandas.DataFrame.fillna with the method='ffill' option. 'ffill' stands for 'forward fill' and will propagate last valid observation forward. The alternative is 'bfill' which works the same way, but backwards.

import pandas as pd

df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
df = df.fillna(method='ffill')

print(df)
#   0  1  2
#0  1  2  3
#1  4  2  3
#2  4  2  9

There is also a direct synonym function for this, pandas.DataFrame.ffill, to make things simpler.

MySQL direct INSERT INTO with WHERE clause

INSERT syntax cannot have WHERE but you can use UPDATE.

The syntax is as follows:

UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;

The way to check a HDFS directory's size?

Extending to Matt D and others answers, the command can be till Apache Hadoop 3.0.0

hadoop fs -du [-s] [-h] [-v] [-x] URI [URI ...]

It displays sizes of files and directories contained in the given directory or the length of a file in case it's just a file.

Options:

  • The -s option will result in an aggregate summary of file lengths being displayed, rather than the individual files. Without the -s option, the calculation is done by going 1-level deep from the given path.
  • The -h option will format file sizes in a human-readable fashion (e.g 64.0m instead of 67108864)
  • The -v option will display the names of columns as a header line.
  • The -x option will exclude snapshots from the result calculation. Without the -x option (default), the result is always calculated from all INodes, including all snapshots under the given path.

du returns three columns with the following format:

 +-------------------------------------------------------------------+ 
 | size  |  disk_space_consumed_with_all_replicas  |  full_path_name | 
 +-------------------------------------------------------------------+ 

##Example command:

hadoop fs -du /user/hadoop/dir1 \
    /user/hadoop/file1 \
    hdfs://nn.example.com/user/hadoop/dir1 

Exit Code: Returns 0 on success and -1 on error.

source: Apache doc

Plot two histograms on single chart with matplotlib

Here is a simple method to plot two histograms, with their bars side-by-side, on the same plot when the data has different sizes:

def plotHistogram(p, o):
    """
    p and o are iterables with the values you want to 
    plot the histogram of
    """
    plt.hist([p, o], color=['g','r'], alpha=0.8, bins=50)
    plt.show()

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

This looks like a Json array list.Therefore its best to use ArrayList to handle the data. In your api end point add array list like this

 @GET("places/")
Call<ArrayList<Place>> getNearbyPlaces(@Query("latitude") String latitude, @Query("longitude") String longitude);

Command to find information about CPUs on a UNIX machine

There is no standard Unix command, AFAIK. I haven't used Sun OS, but on Linux, you can use this:

cat /proc/cpuinfo

Sorry that it is Linux, not Sun OS. There is probably something similar though for Sun OS.

Cannot get a text value from a numeric cell “Poi”

This will work:

WebElement searchbox = driver.findElement(By.name("j_username"));
WebElement searchbox2 = driver.findElement(By.name("j_password"));         


try {

      FileInputStream file = new FileInputStream(new File("C:\\paulo.xls")); 
      HSSFWorkbook workbook = new HSSFWorkbook(file);

      HSSFSheet sheet = workbook.getSheetAt(0);

    for (int i=1; i <= sheet.getLastRowNum(); i++){

            HSSFCell j_username = sheet.getRow(i).getCell(0)
            HSSFCell j_password = sheet.getRow(i).getCell(0)

            //Setting the Cell type as String
            j_username.setCellType(j_username.CELL_TYPE_STRING)
            j_password.setCellType(j_password.CELL_TYPE_STRING)

            searchbox.sendKeys(j_username.toString());
            searchbox2.sendKeys(j_password.toString());


            searchbox.submit();       

            driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);

    }

      workbook.close();
      file.close();

     } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace();
     } catch (IOException ioe) {
      ioe.printStackTrace();
     }

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

None of the answers, including the checked one did not work for me.

The solution was far more simple. I first removed the references from my BUS layer. Then deleted the dll's from the project (to make sure it's gone), then reinstalled JSON.NET from nuget packeges. And, the tricky part was, "turning it off and on again".

I just restarted visual studio, and there it worked!

So, if you try everything possible and still can't solve the problem, just try turning visual studio off and on again, it might help.

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

In my case I had an issue around using Microsoft.ReportViewer.WebForms. I removed validate=true from add verb line in web.config and it started working:

<system.web>
    <httpHandlers>
      <add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

How to add header to a dataset in R?

You can do the following:

Load the data:

test <- read.csv(
          "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
          header=FALSE)

Note that the default value of the header argument for read.csv is TRUE so in order to get all lines you need to set it to FALSE.

Add names to the different columns in the data.frame

names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

or alternative and faster as I understand (not reloading the entire dataset):

colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

Switch case with fallthrough?

If the values are integer then you can use [2-3] or you can use [5,7,8] for non continuous values.

#!/bin/bash
while [ $# -gt 0 ];
do
    case $1 in
    1)
        echo "one"
        ;;
    [2-3])
        echo "two or three"
        ;;
    [4-6])
        echo "four to six"
        ;;
    [7,9])
        echo "seven or nine"
        ;;
    *)
        echo "others"
        ;;
    esac
    shift
done

If the values are string then you can use |.

#!/bin/bash
while [ $# -gt 0 ];
do
    case $1 in
    "one")
        echo "one"
        ;;
    "two" | "three")
        echo "two or three"
        ;;
    *)
        echo "others"
        ;;
    esac
    shift
done

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

Group a list of objects by an attribute

You can sort like this:

    Collections.sort(studlist, new Comparator<Student>() {

        @Override
        public int compare(Student o1, Student o2) {
            return o1.getStud_location().compareTo(o2.getStud_location());
        }
    });

Assuming you also have the getter for location on your Student class.

build maven project with propriatery libraries included

Create a repository folder under your project. Let's take

${project.basedir}/src/main/resources/repo

Then, install your custom jar to this repo:

mvn install:install-file -Dfile=[FILE_PATH] \
-DgroupId=[GROUP] -DartifactId=[ARTIFACT] -Dversion=[VERS] \ 
-Dpackaging=jar -DlocalRepositoryPath=[REPO_DIR]

Lastly, add the following repo and dependency definitions to the projects pom.xml:

<repositories>
    <repository>
        <id>project-repo</id>
        <url>file://${project.basedir}/src/main/resources/repo</url>
    </repository>
</repositories>

<dependencies>    
    <dependency>
        <groupId>[GROUP]</groupId>
        <artifactId>[ARTIFACT]</artifactId>
        <version>[VERS]</version>
    </dependency>
</dependencies>

ASP.NET Identity reset password

In case of password reset, it is recommended to reset it through sending password reset token to registered user email and ask user to provide new password. If have created a easily usable .NET library over Identity framework with default configuration settins. You can find details at blog link and source code at github.

How to select a value in dropdown javascript?

Use the selectedIndex property:

document.getElementById("Mobility").selectedIndex = 12; //Option 10

Alternate method:

Loop through each value:

//Get select object
var objSelect = document.getElementById("Mobility");

//Set selected
setSelectedValue(objSelect, "10");

function setSelectedValue(selectObj, valueToSet) {
    for (var i = 0; i < selectObj.options.length; i++) {
        if (selectObj.options[i].text== valueToSet) {
            selectObj.options[i].selected = true;
            return;
        }
    }
}

How can I round down a number in Javascript?

Here is math.floor being used in a simple example. This might help a new developer to get an idea how to use it in a function and what it does. Hope it helps!

<script>

var marks = 0;

function getRandomNumbers(){    //  generate a random number between 1 & 10
    var number = Math.floor((Math.random() * 10) + 1);
    return number;
}

function getNew(){  
/*  
    This function can create a new problem by generating two random numbers. When the page is loading as the first time, this function is executed with the onload event and the onclick event of "new" button.
*/
document.getElementById("ans").focus();
var num1 = getRandomNumbers();
var num2 = getRandomNumbers();
document.getElementById("num1").value = num1;
document.getElementById("num2").value = num2;

document.getElementById("ans").value ="";
document.getElementById("resultBox").style.backgroundColor = "maroon"
document.getElementById("resultBox").innerHTML = "***"

}

function checkAns(){
/*
    After entering the answer, the entered answer will be compared with the correct answer. 
        If the answer is correct, the text of the result box should be "Correct" with a green background and 10 marks should be added to the total marks.
        If the answer is incorrect, the text of the result box should be "Incorrect" with a red background and 3 marks should be deducted from the total.
        The updated total marks should be always displayed at the total marks box.
*/

var num1 = eval(document.getElementById("num1").value);
var num2 = eval(document.getElementById("num2").value);
var answer = eval(document.getElementById("ans").value);

if(answer==(num1+num2)){
    marks = marks + 10;
    document.getElementById("resultBox").innerHTML = "Correct";
    document.getElementById("resultBox").style.backgroundColor = "green";
    document.getElementById("totalMarks").innerHTML= "Total marks : " + marks;

}

else{
    marks = marks - 3;
    document.getElementById("resultBox").innerHTML = "Wrong";
    document.getElementById("resultBox").style.backgroundColor = "red";
    document.getElementById("totalMarks").innerHTML = "Total Marks: " + marks ;
}




}

</script>
</head>

<body onLoad="getNew()">
    <div class="container">
        <h1>Let's add numbers</h1>
        <div class="sum">
            <input id="num1" type="text" readonly> + <input id="num2" type="text" readonly>
        </div>
        <h2>Enter the answer below and click 'Check'</h2>
        <div class="answer">
            <input id="ans" type="text" value="">
        </div>
        <input id="btnchk" onClick="checkAns()" type="button" value="Check" >
        <div id="resultBox">***</div>
        <input id="btnnew" onClick="getNew()" type="button" value="New">
        <div id="totalMarks">Total marks : 0</div>  
    </div>
</body>
</html>

How to completely remove Python from a Windows machine?

Windows 7 64-bit, with both Python3.4 and Python2.7 installed at some point :)

I'm using Py.exe to route to Py2 or Py3 depending on the script's needs - but I previously improperly uninstalled Python27 before.

Py27 was removed manually from C:\python\Python27 (the folder Python27 was deleted by me previously)

Upon re-installing Python27, it gave the above error you specify.
It would always back out while trying to 'remove shortcuts' during the installation process.

I placed a copy of Python27 back in that original folder, at C:\Python\Python27, and re-ran the same failing Python27 installer. It was happy locating those items and removing them, and proceeded with the install.

This is not the answer that addresses registry key issues (others mention that) but it is somewhat of a workaround if you know of previous installations that were improperly removed.

You could have some insight to this by opening "regedit" and searching for "Python27" - a registry key appeared in my command-shell Cache pointing at c:\python\python27\ (which had been removed and was not present when searching in the registry upon finding it).

That may help point to previously improperly removed installations.

Good luck!

How do I get the list of keys in a Dictionary?

List<string> keyList = new List<string>(this.yourDictionary.Keys);

Display the binary representation of a number in C?

There is no direct format specifier for this in the C language. Although I wrote this quick python snippet to help you understand the process step by step to roll your own.

#!/usr/bin/python

dec = input("Enter a decimal number to convert: ")
base = 2
solution = ""

while dec >= base:
    solution = str(dec%base) + solution
    dec = dec/base
if dec > 0:
    solution = str(dec) + solution

print solution

Explained:

dec = input("Enter a decimal number to convert: ") - prompt the user for numerical input (there are multiple ways to do this in C via scanf for example)

base = 2 - specify our base is 2 (binary)

solution = "" - create an empty string in which we will concatenate our solution

while dec >= base: - while our number is bigger than the base entered

solution = str(dec%base) + solution - get the modulus of the number to the base, and add it to the beginning of our string (we must add numbers right to left using division and remainder method). the str() function converts the result of the operation to a string. You cannot concatenate integers with strings in python without a type conversion.

dec = dec/base - divide the decimal number by the base in preperation to take the next modulo

if dec > 0: solution = str(dec) + solution - if anything is left over, add it to the beginning (this will be 1, if anything)

print solution - print the final number

How do I set up the database.yml file in Rails?

The database.yml is a file that is created with new rails applications in /config and defines the database configurations that your application will use in different environments. Read this for details.

Example database.yml:

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: mysql
  encoding: utf8
  database: your_db
  username: root
  password: your_pass
  socket: /tmp/mysql.sock
  host: your_db_ip     #defaults to 127.0.0.1
  port: 3306           

Change class on mouseover in directive

I think it would be much easier to put an anchor tag around i. You can just use the css :hover selector. Less moving parts makes maintenance easier, and less javascript to load makes the page quicker.

This will do the trick:

<style>
 a.icon-link:hover {
   background-color: pink;
 }
</style>

<a href="#" class="icon-link" id="course-0"><i class="icon-thumbsup"></id></a>

jsfiddle example

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

This is how you save the relevant file as a Excel12 (.xlsx) file... It is not as you would intuitively think i.e. using Excel.XlFileFormat.xlExcel12 but Excel.XlFileFormat.xlOpenXMLWorkbook. The actual C# command was

excelWorkbook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
    Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange, 
    Excel.XlSaveConflictResolution.xlUserResolution, true, 
    Missing.Value, Missing.Value, Missing.Value);

I hope this helps someone else in the future.


Missing.Value is found in the System.Reflection namespace.

Serializing/deserializing with memory stream

This code works for me:

public void Run()
{
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());
}

Where the types are like this:

[Serializable]
public enum DogColor
{
    Brown,
    Black,
    Mottled
}

[Serializable]
public class Dog
{
    public String Name
    {
        get; set;
    }

    public DogColor Color
    {
        get;set;
    }

    public override String ToString()
    {
        return String.Format("Dog: {0}/{1}", Name, Color);
    }
}

and the utility methods are:

public static MemoryStream SerializeToStream(object o)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;
}

public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;
}

How can I get selector from jQuery object

Taking in account some answers read here I'd like to propose this:

function getSelectorFromElement($el) {
  if (!$el || !$el.length) {
    return ;
  }

  function _getChildSelector(index) {
    if (typeof index === 'undefined') {
      return '';
    }

    index = index + 1;
    return ':nth-child(' + index + ')';
  }

  function _getIdAndClassNames($el) {
    var selector = '';

    // attach id if exists
    var elId = $el.attr('id');
    if(elId){
      selector += '#' + elId;
    }

    // attach class names if exists
    var classNames = $el.attr('class');
    if(classNames){
      selector += '.' + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, '.');
    }

    return selector;
  }

  // get all parents siblings index and element's tag name,
  // except html and body elements
  var selector = $el.parents(':not(html,body)')
    .map(function() {
      var parentIndex = $(this).index();

      return this.tagName + _getChildSelector(parentIndex);
    })
    .get()
    .reverse()
    .join(' ');

  if (selector) {
    // get node name from the element itself
    selector += ' ' + $el[0].nodeName +
      // get child selector from element ifself
      _getChildSelector($el.index());
  }

  selector += _getIdAndClassNames($el);

  return selector;
}

Maybe useful to create a jQuery plugin?

Convert Variable Name to String?

You somehow have to refer to the variable you want to print the name of. So it would look like:

print varname(something_else)

There is no such function, but if there were it would be kind of pointless. You have to type out something_else, so you can as well just type quotes to the left and right of it to print the name as a string:

print "something_else"

PHPExcel Make first row bold

The simple way to make bold headers:

$row = 1;
foreach($tittles as $index => $tittle) {
    $worksheet->getStyleByColumnAndRow($index + 1, $row)->getFont()->setBold(true);
    $worksheet->setCellValueByColumnAndRow($index + 1, $row, $tittle);
}

How to replace comma with a dot in the number (or any replacement)

As replace() creates/returns a new string rather than modifying the original (tt), you need to set the variable (tt) equal to the new string returned from the replace function.

tt = tt.replace(/,/g, '.')

JSFiddle

How to get the URL without any parameters in JavaScript?

Every answer is rather convoluted. Here:

var url = window.location.href.split('?')[0];

Even if a ? isn't present, it'll still return the first argument, which will be your full URL, minus query string.

It's also protocol-agnostic, meaning you could even use it for things like ftp, itunes.etc.

Reading a resource file from within jar

Rather than trying to address the resource as a File just ask the ClassLoader to return an InputStream for the resource instead via getResourceAsStream:

InputStream in = getClass().getResourceAsStream("/file.txt"); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

As long as the file.txt resource is available on the classpath then this approach will work the same way regardless of whether the file.txt resource is in a classes/ directory or inside a jar.

The URI is not hierarchical occurs because the URI for a resource within a jar file is going to look something like this: file:/example.jar!/file.txt. You cannot read the entries within a jar (a zip file) like it was a plain old File.

This is explained well by the answers to:

How to remove all the occurrences of a char in c++ string

Using copy_if:

#include <string>
#include <iostream>
#include <algorithm>
int main() {
    std::string s1 = "a1a2b3c4a5";
    char s2[256];
    std::copy_if(s1.begin(), s1.end(), s2, [](char c){return c!='a';});
    std::cout << s2 << std::endl;
    return 0;
}

Find a file by name in Visual Studio Code

When you have opened a folder in a workspace you can do Ctrl+P (Cmd+P on Mac) and start typing the filename, or extension to filter the list of filenames

if you have:

  • plugin.ts
  • page.css
  • plugger.ts

You can type css and press enter and it will open the page.css. If you type .ts the list is filtered and contains two items.

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

Git - How to use .netrc file on Windows to save user and password

Is it possible to use a .netrc file on Windows?

Yes: You must:

  • define environment variable %HOME% (pre-Git 2.0, no longer needed with Git 2.0+)
  • put a _netrc file in %HOME%

If you are using Windows 7/10, in a CMD session, type:

setx HOME %USERPROFILE%

and the %HOME% will be set to 'C:\Users\"username"'.
Go that that folder (cd %HOME%) and make a file called '_netrc'

Note: Again, for Windows, you need a '_netrc' file, not a '.netrc' file.

Its content is quite standard (Replace the <examples> with your values):

machine <hostname1>
login <login1>
password <password1>
machine <hostname2>
login <login2>
password <password2>

Luke mentions in the comments:

Using the latest version of msysgit on Windows 7, I did not need to set the HOME environment variable. The _netrc file alone did the trick.

This is indeed what I mentioned in "Trying to “install” github, .ssh dir not there":
git-cmd.bat included in msysgit does set the %HOME% environment variable:

@if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%

??? believes in the comments that "it seems that it won't work for http protocol"

However, I answered that netrc is used by curl, and works for HTTP protocol, as shown in this example (look for 'netrc' in the page): . Also used with HTTP protocol here: "_netrc/.netrc alternative to cURL".


A common trap with with netrc support on Windows is that git will bypass using it if an origin https url specifies a user name.

For example, if your .git/config file contains:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://[email protected]/p/my-project/

Git will not resolve your credentials via _netrc, to fix this remove your username, like so:

[remote "origin"]
     fetch = +refs/heads/*:refs/remotes/origin/*
     url = https://code.google.com/p/my-project/

Alternative solution: With git version 1.7.9+ (January 2012): This answer from Mark Longair details the credential cache mechanism which also allows you to not store your password in plain text as shown below.


With Git 1.8.3 (April 2013):

You now can use an encrypted .netrc (with gpg).
On Windows: %HOME%/_netrc (_, not '.')

A new read-only credential helper (in contrib/) to interact with the .netrc/.authinfo files has been added.

That script would allow you to use gpg-encrypted netrc files, avoiding the issue of having your credentials stored in a plain text file.

Files with the .gpg extension will be decrypted by GPG before parsing.
Multiple -f arguments are OK. They are processed in order, and the first matching entry found is returned via the credential helper protocol.

When no -f option is given, .authinfo.gpg, .netrc.gpg, .authinfo, and .netrc files in your home directory are used in this order.

To enable this credential helper:

git config credential.helper '$shortname -f AUTHFILE1 -f AUTHFILE2'

(Note that Git will prepend "git-credential-" to the helper name and look for it in the path.)

# and if you want lots of debugging info:
git config credential.helper '$shortname -f AUTHFILE -d'

#or to see the files opened and data found:
git config credential.helper '$shortname -f AUTHFILE -v'

See a full example at "Is there a way to skip password typing when using https:// github"


With Git 2.18+ (June 2018), you now can customize the GPG program used to decrypt the encrypted .netrc file.

See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).
(Merged by Junio C Hamano -- gitster -- in commit 017b7c5, 30 May 2018)

git-credential-netrc: accept gpg option

git-credential-netrc was hardcoded to decrypt with 'gpg' regardless of the gpg.program option.
This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2'

Basic authentication with fetch?

I'll share a code which has Basic Auth Header form data request body,

let username = 'test-name';
let password = 'EbQZB37gbS2yEsfs';
let formdata = new FormData();
let headers = new Headers();


formdata.append('grant_type','password');
formdata.append('username','testname');
formdata.append('password','qawsedrf');

headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch('https://www.example.com/token.php', {
 method: 'POST',
 headers: headers,
 body: formdata
}).then((response) => response.json())
.then((responseJson) => {
 console.log(responseJson);

 this.setState({
    data: responseJson
 })
  })
   .catch((error) => {
 console.error(error);
   });

How can I install Visual Studio Code extensions offline?

For Python users the pattern to use with t3chbot's excellent answer looks like:

https://marketplace.visualstudio.com/_apis/public/gallery/publishers/ms-python/vsextensions/python/{version_number}/vspackage

be sure to scroll right to see where you have to enter the version number.

How to comment out a block of code in Python

The only cure I know for this is a good editor. Sorry.

JQuery create new select option

Something like:

function populate(selector) {
  $(selector)
    .append('<option value="foo">foo</option>')
    .append('<option value="bar">bar</option>')
}

populate('#myform .myselect');

Or even:

$.fn.populate = function() {
  $(this)
    .append('<option value="foo">foo</option>')
    .append('<option value="bar">bar</option>')
}

$('#myform .myselect').populate();

Best practice to run Linux service as a different user

On Debian we use the start-stop-daemon utility, which handles pid-files, changing the user, putting the daemon into background and much more.

I'm not familiar with RedHat, but the daemon utility that you are already using (which is defined in /etc/init.d/functions, btw.) is mentioned everywhere as the equivalent to start-stop-daemon, so either it can also change the uid of your program, or the way you do it is already the correct one.

If you look around the net, there are several ready-made wrappers that you can use. Some may even be already packaged in RedHat. Have a look at daemonize, for example.

Linq to SQL .Sum() without group ... into

Try:

itemsCard.ToList().Select(c=>c.Price).Sum();

Actually this would perform better:

var itemsInCart = from o in db.OrderLineItems
              where o.OrderId == currentOrder.OrderId
              select new { o.WishListItem.Price };
var sum = itemsCard.ToList().Select(c=>c.Price).Sum();

Because you'll only be retrieving one column from the database.

How to read from a file or STDIN in Bash?

as a workaround you can use the stdin device in /dev directory

....| for item in `cat /dev/stdin` ; do echo $item ;done

Clear MySQL query cache without restarting server

according the documentation, this should do it...

RESET QUERY CACHE 

How do I pipe or redirect the output of curl -v?

The answer above didn't work for me, what did eventually was this syntax:

curl https://${URL} &> /dev/stdout | tee -a ${LOG}

tee puts the output on the screen, but also appends it to my log.

PHP Array to JSON Array using json_encode();

I want to add to Michael Berkowski's answer that this can also happen if the array's order is reversed, in which case it's a bit trickier to observe the issue, because in the json object, the order will be ordered ascending.

For example:

[
    3 => 'a',
    2 => 'b',
    1 => 'c',
    0 => 'd'
]

Will return:

{
    0: 'd',
    1: 'c',
    2: 'b',
    3: 'a'
}

So the solution in this case, is to use array_reverse before encoding it to json

Fastest way to get the first object from a queryset in django?

Now, in Django 1.9 you have first() method for querysets.

YourModel.objects.all().first()

This is a better way than .get() or [0] because it does not throw an exception if queryset is empty, Therafore, you don't need to check using exists()

SQL SERVER DATETIME FORMAT

This is my favorite use of 112 and 114

select (convert(varchar, getdate(), 112)+ replace(convert(varchar, getdate(), 114),':','')) as 'Getdate() 

112 + 114 or YYYYMMDDHHMMSSMSS'

Result:

Getdate() 112 + 114 or YYYYMMDDHHMMSSMSS

20171016083349100

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

You cannot do this with an attribute because they are just meta information generated at compile time. Just add code to the constructor to initialize the date if required, create a trigger and handle missing values in the database, or implement the getter in a way that it returns DateTime.Now if the backing field is not initialized.

public DateTime DateCreated
{
   get
   {
      return this.dateCreated.HasValue
         ? this.dateCreated.Value
         : DateTime.Now;
   }

   set { this.dateCreated = value; }
}

private DateTime? dateCreated = null;

How to add a default "Select" option to this ASP.NET DropDownList control?

If you do an "Add" it will add it to the bottom of the list. You need to do an "Insert" if you want the item added to the top of the list.

Get the current file name in gulp.src()

For my case gulp-ignore was perfect. As option you may pass a function there:

function condition(file) {
 // do whatever with file.path
 // return boolean true if needed to exclude file 
}

And the task would look like this:

var gulpIgnore = require('gulp-ignore');

gulp.task('task', function() {
  gulp.src('./**/*.js')
    .pipe(gulpIgnore.exclude(condition))
    .pipe(gulp.dest('./dist/'));
});

Easy way to dismiss keyboard?

Yes, endEditing is the best option. And From iOW 7.0, UIScrollView has a cool feature to dismiss the keyboard on interacting with the scroll view. For achieving this, you can set keyboardDismissMode property of UIScrollView.

Set the keyboard dismiss mode as:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag

It has few other types. Have a look at this apple document.

Naming conventions for Java methods that return boolean

I want to post this link as it may help further for peeps checking this answer and looking for more java style convention

Java Programming Style Guidelines

Item "2.13 is prefix should be used for boolean variables and methods." is specifically relevant and suggests the is prefix.

The style guide goes on to suggest:

There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:

boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;

If you follow the Guidelines I believe the appropriate method would be named:

shouldCreateFreshSnapshot()