Programs & Examples On #Formmail

"if not exist" command in batch file

When testing for directories remember that every directory contains two special files.

One is called '.' and the other '..'

. is the directory's own name while .. is the name of it's parent directory.

To avoid trailing backslash problems just test to see if the directory knows it's own name.

eg:

if not exist %temp%\buffer\. mkdir %temp%\buffer

How to check for an active Internet connection on iOS or macOS?

For my iOS Projects, I recommend using

Reachability Class

Declared in Swift. For me, it works simply fine with

Wi-Fi and Cellular data

.

 import SystemConfiguration

 public class Reachability {

 class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }

    var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
    if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
        return false
    }

    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    let ret = (isReachable && !needsConnection)
    return ret
} }

Use conditional statement,

if Reachability.isConnectedToNetwork(){
          * Enter Your Code Here*
        }
    }
    else{
        print("NO Internet connection")
    }

This class is useful in almost every case your app uses the Internet Connection. Such as if the condition is true, API can be called or task could be performed.

jQuery check if it is clicked or not

Alright, before I go into the solution, lets be on the same line about this one fact: Javascript is Event Based. So you'll usually have to setup callbacks to be able to do procedures.

Based on your comment I assumed you have a trigger that will do the logic that launched the function depending if the element is clicked; for sake of demonstration I made it a "submit button"; but this can be a timer or something else.

var the_action = function(type) {
    switch(type) {
        case 'a':
            console.log('Case A');
            break;
         case 'b':
            console.log('Case B');
            break;
    }
};

$('.clickme').click(function() { 
    console.log('Clicked');
    $(this).data('clicked', true);
});

$('.submit').click(function() {
    // All your logic can go here if you want.
    if($('.clickme').data('clicked') == true) {
        the_action('a');
    } else {
        the_action('b');
    }
});

Live Example: http://jsfiddle.net/kuroir/6MCVJ/

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

OSError [Errno 22] invalid argument when use open() in Python

I got this error because old server instance was running and using log file, hence new instance was not able to write to log file. Post deleting log file this issue got resolved.

How do I collapse sections of code in Visual Studio Code for Windows?

On a Mac, it's the RHS Command key, ?K, not the left for the code folding commands.

Otherwise the left hand Command key will delete the current line, ?K.

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

Here is what you do in Excel 2003:

  1. In your sheet of interest, go to Format -> Sheet -> Hide and hide your sheet.
  2. Go to Tools -> Protection -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Here is what you do in Excel 2007:

  1. In your sheet of interest, go to Home ribbon -> Format -> Hide & Unhide -> Hide Sheet and hide your sheet.
  2. Go to Review ribbon -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Once this is done, the sheet is hidden and cannot be unhidden without the password. Make sense?


If you really need to keep some calculations secret, try this: use Access (or another Excel workbook or some other DB of your choice) to calculate what you need calculated, and export only the "unclassified" results to your Excel workbook.

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

Another easy way to circumvent google's check is to use another compression algorithm with tar, like bz2:

tar -cvjf my.tar.bz2 dir/

Note that 'j' (for bz2 compression) is used above instead of 'z' (gzip compression).

Is it possible to insert HTML content in XML document?

You can include HTML content. One possibility is encoding it in BASE64 as you have mentioned.

Another might be using CDATA tags.

Example using CDATA:

<xml>
    <title>Your HTML title</title>
    <htmlData><![CDATA[<html>
        <head>
            <script/>
        </head>
        <body>
        Your HTML's body
        </body>
        </html>
     ]]>
    </htmlData>
</xml>

Please note:

CDATA's opening character sequence: <![CDATA[

CDATA's closing character sequence: ]]>

how to parse JSONArray in android

If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?

Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:

List<String> allNames = new ArrayList<String>();

JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
    JSONObject actor = cast.getJSONObject(i);
    String name = actor.getString("name");
    allNames.add(name);
}

(typed straight into the browser, so not tested).

Win32Exception (0x80004005): The wait operation timed out

In our case we were able to narrow the cause down to a number of views which had WITH SCHEMABINDING on them. Although this is supposed to improve performance it was resulting in an awful query plan (doing a single record update on a table which was being referenced by these views was taking nearly 2 seconds of elapsed time). Removing WITH SCHEMABINDING has meant all is running smoothly again and the "wait operation timed out" errors have gone.

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

Here's a version using the excellent requests library:

from requests import session

payload = {
    'action': 'login',
    'username': USERNAME,
    'password': PASSWORD
}

with session() as c:
    c.post('http://example.com/login.php', data=payload)
    response = c.get('http://example.com/protected_page.php')
    print(response.headers)
    print(response.text)

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

Command to close an application of console?

So you didn't say you wanted the application to quit or exit abruptly, so as another option, perhaps just have the response loop end out elegantly. (I am assuming you have a while loop waiting for user instructions. This is some code from a project I just wrote today.

        Console.WriteLine("College File Processor");
        Console.WriteLine("*************************************");
        Console.WriteLine("(H)elp");
        Console.WriteLine("Process (W)orkouts");
        Console.WriteLine("Process (I)nterviews");
        Console.WriteLine("Process (P)ro Days");
        Console.WriteLine("(S)tart Processing");
        Console.WriteLine("E(x)it");
        Console.WriteLine("*************************************");

        string response = "";
        string videotype = "";
        bool starting = false;
        bool exiting = false;

        response = Console.ReadLine();

        while ( response != "" )
        {
            switch ( response  )
            {
                case "H":
                case "h":
                    DisplayHelp();
                    break;

                case "W":
                case "w":
                    Console.WriteLine("Video Type set to Workout");
                    videotype = "W";
                    break;

                case "I":
                case "i":
                    Console.WriteLine("Video Type set to Interview");
                    videotype = "I";
                    break;

                case "P":
                case "p":
                    Console.WriteLine("Video Type set to Pro Day");
                    videotype = "P";
                    break;

                case "S":
                case "s":
                    if ( videotype == "" )
                    {
                        Console.WriteLine("Please Select Video Type Before Starting");
                    }
                    else
                    {
                        Console.WriteLine("Starting...");
                        starting = true;
                    }
                    break;

                case "E":
                case "e":
                    Console.WriteLine("Good Bye!");
                    System.Threading.Thread.Sleep(100);
                    exiting = true;
                    break;
            }

            if ( starting || exiting)
            {
                break;
            }
            else
            {
                response = Console.ReadLine();
            }
        }

        if ( starting )
        {
            ProcessFiles();
        }

iPhone app could not be installed at this time

in my case app want to use iCloud services, but in distr. provision profile wasn't set iCloud enabled. turn it on and refresh profile.

How to set button click effect in Android?

This can be achieved by creating a drawable xml file containing a list of states for the button. So for example if you create a new xml file called "button.xml" with the following code:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/YOURIMAGE" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:drawable="@drawable/YOURIMAGE" />
</selector>

To keep the background image with a darkened appearance on press, create a second xml file and call it gradient.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <bitmap android:src="@drawable/YOURIMAGE"/>
    </item>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <gradient android:angle="90" android:startColor="#880f0f10" android:centerColor="#880d0d0f" android:endColor="#885d5d5e"/>
        </shape>
    </item>
</layer-list>

In the xml of your button set the background to be the button xml e.g.

android:background="@drawable/button"

Hope this helps!

Edit: Changed the above code to show an image (YOURIMAGE) in the button as opposed to a block colour.

C - freeing structs

You can't free types that aren't dynamically allocated. Although arrays are syntactically similar (int* x = malloc(sizeof(int) * 4) can be used in the same way that int x[4] is), calling free(firstName) would likely cause an error for the latter.

For example, take this code:

int x;
free(&x);

free() is a function which takes in a pointer. &x is a pointer. This code may compile, even though it simply won't work.

If we pretend that all memory is allocated in the same way, x is "allocated" at the definition, "freed" at the second line, and then "freed" again after the end of the scope. You can't free the same resource twice; it'll give you an error.

This isn't even mentioning the fact that for certain reasons, you may be unable to free the memory at x without closing the program.

tl;dr: Just free the struct and you'll be fine. Don't call free on arrays; only call it on dynamically allocated memory.

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

cURL error 60: SSL certificate: unable to get local issuer certificate

I just experienced this same problem with the Laravel 4 php framework which uses the guzzlehttp/guzzle composer package. For some reason, the SSL certificate for mailgun stopped validating suddenly and I got that same "error 60" message.

If, like me, you are on a shared hosting without access to php.ini, the other solutions are not possible. In any case, Guzzle has this client initializing code that would most likely nullify the php.ini effects:

// vendor/guzzlehttp/guzzle/src/Client.php
    $settings = [
        'allow_redirects' => true,
        'exceptions'      => true,
        'decode_content'  => true,
        'verify'          => __DIR__ . '/cacert.pem'
    ];

Here Guzzle forces usage of its own internal cacert.pem file, which is probably now out of date, instead of using the one provided by cURL's environment. Changing this line (on Linux at least) configures Guzzle to use cURL's default SSL verification logic and fixed my problem:

        'verify'          => true

You can also set this to false if you don't care about the security of your SSL connection, but that's not a good solution.

Since the files in vendor are not meant to be tampered with, a better solution would be to configure the Guzzle client on usage, but this was just too difficult to do in Laravel 4.

Hope this saves someone else a couple hours of debugging...

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

Ask the person maintaining the server at http://172.16.1.157:8002/ to add your hostname to Access-Control-Allow-Origin hosts, the server should return a header similar to the following with the response-

Access-Control-Allow-Origin: yourhostname:port

Shrink to fit content in flexbox, or flex-basis: content workaround?

It turns out that it was shrinking and growing correctly, providing the desired behaviour all along; except that in all current browsers flexbox wasn't accounting for the vertical scrollbar! Which is why the content appears to be getting cut off.

You can see here, which is the original code I was using before I added the fixed widths, that it looks like the column isn't growing to accomodate the text:

http://jsfiddle.net/2w157dyL/1/

However if you make the content in that column wider, you'll see that it always cuts it off by the same amount, which is the width of the scrollbar.

So the fix is very, very simple - add enough right padding to account for the scrollbar:

http://jsfiddle.net/2w157dyL/2/

_x000D_
_x000D_
  main > section {_x000D_
    overflow-y: auto;_x000D_
    padding-right: 2em;_x000D_
  }
_x000D_
_x000D_
_x000D_

It was when I was trying some things suggested by Michael_B (specifically adding a padding buffer) that I discovered this, thanks so much!

Edit: I see that he also posted a fiddle which does the same thing - again, thanks so much for all your help

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

using jquery $.ajax to call a PHP function

Use $.ajax to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:

$.ajax({ url: '/my/site',
         data: {action: 'test'},
         type: 'post',
         success: function(output) {
                      alert(output);
                  }
});

On the server side, the action POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'test' : test();break;
        case 'blah' : blah();break;
        // ...etc...
    }
}

I believe that's a simple incarnation of the Command pattern.

NULL or BLANK fields (ORACLE)

One should NEVER treat "BLANK" and NULL as the same.

Back in the olden days before there was a SQL standard, Oracle made the design decision that empty strings in VARCHAR/ VARCHAR2 columns were NULL and that there was only one sense of NULL (there are relational theorists that would differentiate between data that has never been prompted for, data where the answer exists but is not known by the user, data where there is no answer, etc. all of which constitute some sense of NULL). By the time that the SQL standard came around and agreed that NULL and the empty string were distinct entities, there were already Oracle users that had code that assumed the two were equivalent. So Oracle was basically left with the options of breaking existing code, violating the SQL standard, or introducing some sort of initialization parameter that would change the functionality of potentially large number of queries. Violating the SQL standard (IMHO) was the least disruptive of these three options.

Oracle has left open the possibility that the VARCHAR data type would change in a future release to adhere to the SQL standard (which is why everyone uses VARCHAR2 in Oracle since that data type's behavior is guaranteed to remain the same going forward).

Why not use Double or Float to represent currency?

As said earlier "Representing money as a double or float will probably look good at first as the software rounds off the tiny errors, but as you perform more additions, subtractions, multiplications and divisions on inexact numbers, you’ll lose more and more precision as the errors add up. This makes floats and doubles inadequate for dealing with money, where perfect accuracy for multiples of base 10 powers is required."

Finally Java has a standard way to work with Currency And Money!

JSR 354: Money and Currency API

JSR 354 provides an API for representing, transporting, and performing comprehensive calculations with Money and Currency. You can download it from this link:

JSR 354: Money and Currency API Download

The specification consists of the following things:

  1. An API for handling e. g. monetary amounts and currencies
  2. APIs to support interchangeable implementations
  3. Factories for creating instances of the implementation classes
  4. Functionality for calculations, conversion and formatting of monetary amounts
  5. Java API for working with Money and Currencies, which is planned to be included in Java 9.
  6. All specification classes and interfaces are located in the javax.money.* package.

Sample Examples of JSR 354: Money and Currency API:

An example of creating a MonetaryAmount and printing it to the console looks like this:

MonetaryAmountFactory<?> amountFactory = Monetary.getDefaultAmountFactory();
MonetaryAmount monetaryAmount = amountFactory.setCurrency(Monetary.getCurrency("EUR")).setNumber(12345.67).create();
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.getDefault());
System.out.println(format.format(monetaryAmount));

When using the reference implementation API, the necessary code is much simpler:

MonetaryAmount monetaryAmount = Money.of(12345.67, "EUR");
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.getDefault());
System.out.println(format.format(monetaryAmount));

The API also supports calculations with MonetaryAmounts:

MonetaryAmount monetaryAmount = Money.of(12345.67, "EUR");
MonetaryAmount otherMonetaryAmount = monetaryAmount.divide(2).add(Money.of(5, "EUR"));

CurrencyUnit and MonetaryAmount

// getting CurrencyUnits by locale
CurrencyUnit yen = MonetaryCurrencies.getCurrency(Locale.JAPAN);
CurrencyUnit canadianDollar = MonetaryCurrencies.getCurrency(Locale.CANADA);

MonetaryAmount has various methods that allow accessing the assigned currency, the numeric amount, its precision and more:

MonetaryAmount monetaryAmount = Money.of(123.45, euro);
CurrencyUnit currency = monetaryAmount.getCurrency();
NumberValue numberValue = monetaryAmount.getNumber();

int intValue = numberValue.intValue(); // 123
double doubleValue = numberValue.doubleValue(); // 123.45
long fractionDenominator = numberValue.getAmountFractionDenominator(); // 100
long fractionNumerator = numberValue.getAmountFractionNumerator(); // 45
int precision = numberValue.getPrecision(); // 5

// NumberValue extends java.lang.Number.
// So we assign numberValue to a variable of type Number
Number number = numberValue;

MonetaryAmounts can be rounded using a rounding operator:

CurrencyUnit usd = MonetaryCurrencies.getCurrency("USD");
MonetaryAmount dollars = Money.of(12.34567, usd);
MonetaryOperator roundingOperator = MonetaryRoundings.getRounding(usd);
MonetaryAmount roundedDollars = dollars.with(roundingOperator); // USD 12.35

When working with collections of MonetaryAmounts, some nice utility methods for filtering, sorting and grouping are available.

List<MonetaryAmount> amounts = new ArrayList<>();
amounts.add(Money.of(2, "EUR"));
amounts.add(Money.of(42, "USD"));
amounts.add(Money.of(7, "USD"));
amounts.add(Money.of(13.37, "JPY"));
amounts.add(Money.of(18, "USD"));

Custom MonetaryAmount operations

// A monetary operator that returns 10% of the input MonetaryAmount
// Implemented using Java 8 Lambdas
MonetaryOperator tenPercentOperator = (MonetaryAmount amount) -> {
    BigDecimal baseAmount = amount.getNumber().numberValue(BigDecimal.class);
    BigDecimal tenPercent = baseAmount.multiply(new BigDecimal("0.1"));
    return Money.of(tenPercent, amount.getCurrency());
};

MonetaryAmount dollars = Money.of(12.34567, "USD");

// apply tenPercentOperator to MonetaryAmount
MonetaryAmount tenPercentDollars = dollars.with(tenPercentOperator); // USD 1.234567

Resources:

Handling money and currencies in Java with JSR 354

Looking into the Java 9 Money and Currency API (JSR 354)

See Also: JSR 354 - Currency and Money

how to hide keyboard after typing in EditText in android?

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

public class KeyboardUtils {

    private static KeyboardUtils instance;
    private InputMethodManager inputMethodManager;

    private KeyboardUtils() {
    }

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

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

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

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

public class MainActivity extends AppCompatActivity {

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

}

Reliable way for a Bash script to get the full path to itself

The accepted solution has the inconvenient (for me) to not be "source-able":
if you call it from a "source ../../yourScript", $0 would be "bash"!

The following function (for bash >= 3.0) gives me the right path, however the script might be called (directly or through source, with an absolute or a relative path):
(by "right path", I mean the full absolute path of the script being called, even when called from another path, directly or with "source")

#!/bin/bash
echo $0 executed

function bashscriptpath() {
  local _sp=$1
  local ascript="$0"
  local asp="$(dirname $0)"
  #echo "b1 asp '$asp', b1 ascript '$ascript'"
  if [[ "$asp" == "." && "$ascript" != "bash" && "$ascript" != "./.bashrc" ]] ; then asp="${BASH_SOURCE[0]%/*}"
  elif [[ "$asp" == "." && "$ascript" == "./.bashrc" ]] ; then asp=$(pwd)
  else
    if [[ "$ascript" == "bash" ]] ; then
      ascript=${BASH_SOURCE[0]}
      asp="$(dirname $ascript)"
    fi  
    #echo "b2 asp '$asp', b2 ascript '$ascript'"
    if [[ "${ascript#/}" != "$ascript" ]]; then asp=$asp ;
    elif [[ "${ascript#../}" != "$ascript" ]]; then
      asp=$(pwd)
      while [[ "${ascript#../}" != "$ascript" ]]; do
        asp=${asp%/*}
        ascript=${ascript#../}
      done
    elif [[ "${ascript#*/}" != "$ascript" ]];  then
      if [[ "$asp" == "." ]] ; then asp=$(pwd) ; else asp="$(pwd)/${asp}"; fi
    fi  
  fi  
  eval $_sp="'$asp'"
}

bashscriptpath H
export H=${H}

The key is to detect the "source" case and to use ${BASH_SOURCE[0]} to get back the actual script.

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

How to install grunt and how to build script with it

I got the same issue, but i solved it with changing my Grunt.js to Gruntfile.js Check your file name before typing grunt.cmd on windows cmd (if you're using windows).

Difference between frontend, backend, and middleware in web development

Here is a real world example which shows front/mid/back end.

General description:

  • Frontend is responsible for presenting data to user. Please note interesting quirk that you may have two different front ends associated with single backend
  • Backend provides business logic/data persistence.
  • Middleware (activemq in the picture) is responsible for system to system. integration between backends. Usually it is installed as separate application enter image description here

Overlapping:

It is possible to have overlapping between frontend and backend. This usually leaads to long-term issues with application maintenance and scalability. Fairly common in legacy applications.

Most modern technology stacks encourage developers to have strict separation. For example in the picture you can see that backend of the first system has rest web service which is a clear separation line.

Bottlenecks

Most bottlenecks in large are caused by database/network. Databases are located in backend. As for network issues every connection goes through netowrk, so every connection has potential for being slow. With good application design these issues are avoidable to large extend.

Codesign error: Provisioning profile cannot be found after deleting expired profile

One suggestion I'll make since no one yet has said it: PLEASE PLEASE PLEASE make a backup of your whole .xcodeproj file BEFORE you start modifying it's contents. Screwing up the project file and having no backup will lead to a very very unpleasant experience.

Being able to back out of an edit can be a godsend.

Detecting value change of input[type=text] in jQuery

This combination of events worked for me:

$("#myTextBox").on("input paste", function() {
   alert($(this).val()); 
});

How can I remove specific rules from iptables?

The best solution that works for me without any problems looks this way:
1. Add temporary rule with some comment:

comment=$(cat /proc/sys/kernel/random/uuid | sed 's/\-//g')
iptables -A ..... -m comment --comment "${comment}" -j REQUIRED_ACTION

2. When the rule added and you wish to remove it (or everything with this comment), do:

iptables-save | grep -v "${comment}" | iptables-restore

So, you'll 100% delete all rules that match the $comment and leave other lines untouched. This solution works for last 2 months with about 100 changes of rules per day - no issues.Hope, it helps

Hibernate Criteria for Dates

Why do you use Restrictions.like(...)?

You should use Restrictions.eq(...).

Note you can also use .le, .lt, .ge, .gt on date objects as comparison operators. LIKE operator is not appropriate for this case since LIKE is useful when you want to match results according to partial content of a column. Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.

For example if you have a name column with some people's full name, you can do where name like 'robert %' so that you will return all entries with name starting with 'robert ' (% can replace any character).

In your case you know the full content of the date you're trying to match so you shouldn't use LIKE but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...).

Your date object you got with the code:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);

This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.

This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".

If you want to retrieve all entries of your database from a given day, you will have to use the following code:

    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
    String myDate = "17-04-2011";
    // Create date 17-04-2011 - 00h00
    Date minDate = formatter.parse(myDate);
    // Create date 18-04-2011 - 00h00 
    // -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
    Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
    Conjunction and = Restrictions.conjunction();
    // The order date must be >= 17-04-2011 - 00h00
    and.add( Restrictions.ge("orderDate", minDate) );
    // And the order date must be < 18-04-2011 - 00h00
    and.add( Restrictions.lt("orderDate", maxDate) ); 

No module named pkg_resources

Apparently you're missing setuptools. Some virtualenv versions use distribute instead of setuptools by default. Use the --setuptools option when creating the virtualenv or set the VIRTUALENV_SETUPTOOLS=1 in your environment.

linux execute command remotely

 ssh user@machine 'bash -s' < local_script.sh

or you can just

 ssh user@machine "remote command to run" 

Improve INSERT-per-second performance of SQLite

The answer to your question is that the newer SQLite 3 has improved performance, use that.

This answer Why is SQLAlchemy insert with sqlite 25 times slower than using sqlite3 directly? by SqlAlchemy Orm Author has 100k inserts in 0.5 sec, and I have seen similar results with python-sqlite and SqlAlchemy. Which leads me to believe that performance has improved with SQLite 3.

Python: pandas merge multiple dataframes

There are 2 solutions for this, but it return all columns separately:

import functools

dfs = [df1, df2, df3]

df_final = functools.reduce(lambda left,right: pd.merge(left,right,on='date'), dfs)
print (df_final)
          date     a_x   b_x       a_y      b_y   c_x         a        b   c_y
0  May 15,2017  900.00  0.2%  1,900.00  1000000  0.2%  2,900.00  2000000  0.2%

k = np.arange(len(dfs)).astype(str)
df = pd.concat([x.set_index('date') for x in dfs], axis=1, join='inner', keys=k)
df.columns = df.columns.map('_'.join)
print (df)
                0_a   0_b       1_a      1_b   1_c       2_a      2_b   2_c
date                                                                       
May 15,2017  900.00  0.2%  1,900.00  1000000  0.2%  2,900.00  2000000  0.2%

How do I get the current mouse screen coordinates in WPF?

You may use combination of TimerDispatcher (WPF Timer analog) and Windows "Hooks" to catch cursor position from operational system.

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool GetCursorPos(out POINT pPoint);

Point is a light struct. It contains only X, Y fields.

    public MainWindow()
    {
        InitializeComponent();

        DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
        dt.Tick += new EventHandler(timer_tick);
        dt.Interval = new TimeSpan(0,0,0,0, 50);
        dt.Start();
    }

    private void timer_tick(object sender, EventArgs e)
    {
        POINT pnt;
        GetCursorPos(out pnt);
        current_x_box.Text = (pnt.X).ToString();
        current_y_box.Text = (pnt.Y).ToString();
    }

    public struct POINT
    {
        public int X;
        public int Y;

        public POINT(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }

This solution is also resolving the problem with too often or too infrequent parameter reading so you can adjust it by yourself. But remember about WPF method overload with one arg which is representing ticks not milliseconds.

TimeSpan(50); //ticks

iterating quickly through list of tuples

Assuming a bit more memory usage is not a problem and if the first item of your tuple is hashable, you can create a dict out of your list of tuples and then looking up the value is as simple as looking up a key from the dict. Something like:

dct = dict(tuples)
val = dct.get(key) # None if item not found else the corresponding value

EDIT: To create a reverse mapping, use something like:

revDct = dict((val, key) for (key, val) in tuples)

Python map object is not subscriptable

map() doesn't return a list, it returns a map object.

You need to call list(map) if you want it to be a list again.

Even better,

from itertools import imap
payIntList = list(imap(int, payList))

Won't take up a bunch of memory creating an intermediate object, it will just pass the ints out as it creates them.

Also, you can do if choice.lower() == 'n': so you don't have to do it twice.

Python supports +=: you can do payIntList[i] += 1000 and numElements += 1 if you want.

If you really want to be tricky:

from itertools import count
for numElements in count(1):
    payList.append(raw_input("Enter the pay amount: "))
    if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
         break

and / or

for payInt in payIntList:
    payInt += 1000
    print payInt

Also, four spaces is the standard indent amount in Python.

Cast to generic type in C#

Type type = typeof(MessageProcessor<>).MakeGenericType(key);

That's the best you can do, however without actually knowing what type it is, there's really not much more you can do with it.

EDIT: I should clarify. I changed from var type to Type type. My point is, now you can do something like this:

object obj = Activator.CreateInstance(type);

obj will now be the correct type, but since you don't know what type "key" is at compile time, there's no way to cast it and do anything useful with it.

How to use cURL to get jSON data and decode the data?

you can also use

$result = curl_exec($ch);
return response()->json(json_decode($result));

jQuery - Click event on <tr> elements with in a table and getting <td> element values

<script>
jQuery(document).ready(function() {
    jQuery("tr").click(function(){
       alert("Click! "+ jQuery(this).find('td').html());
    });
});
</script>

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

For those who need the same feature in IE 8, this is how I solved the problem:

  var myImage = $('<img/>');

               myImage.attr('width', 300);
               myImage.attr('height', 300);
               myImage.attr('class', "groupMediaPhoto");
               myImage.attr('src', photoUrl);

I could not force IE8 to use object in constructor.

The process cannot access the file because it is being used by another process (File is created but contains nothing)

File.AppendAllText does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText will fail, throwing the exception you see.

I suggest you used str.Write or str.WriteLine instead, as you already do elsewhere in your code.

Your file is created but contains nothing because the exception is thrown before str.Flush() and str.Close() are called.

Transpose/Unzip Function (inverse of zip)?

I like to use zip(*iterable) (which is the piece of code you're looking for) in my programs as so:

def unzip(iterable):
    return zip(*iterable)

I find unzip more readable.

SQL Server 2008 R2 can't connect to local database in Management Studio

I had this problem. My solution is: change same password of other in windowns. Restart Service (check logon in tab Service SQL).

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

I usually use some #define and constants to make the calculation easy:

#define NANO_SECOND_MULTIPLIER  1000000  // 1 millisecond = 1,000,000 Nanoseconds
const long INTERVAL_MS = 500 * NANO_SECOND_MULTIPLIER;

Hence my code would look like this:

timespec sleepValue = {0};

sleepValue.tv_nsec = INTERVAL_MS;
nanosleep(&sleepValue, NULL);

How to convert date format to milliseconds?

beginupd.getTime() will give you time in milliseconds since January 1, 1970, 00:00:00 GMT till the time you have specified in Date object

Single quotes vs. double quotes in C or C++

Single quotes are for a single character. Double quotes are for a string (array of characters). You can use single quotes to build up a string one character at a time, if you like.

char myChar     = 'A';
char myString[] = "Hello Mum";
char myOtherString[] = { 'H','e','l','l','o','\0' };

Angular2 multiple router-outlet in the same template

Aux routes syntax has changed with the new RC.3 router.

There are some known issues with aux routes but basic support is available.

You can define routes to show components in a named <router-outlet>

Route config

{path: 'chat', component: ChatCmp, outlet: 'aux'}

Named router outlet

<router-outlet name="aux">

Navigate aux routes

this._router.navigateByUrl("/crisis-center(aux:chat;open=true)");

It seems navigating aux routes from routerLink is not yet supported

<a [routerLink]="'/team/3(aux:/chat;open=true)'">Test</a>

<a [routerLink]="['/team/3', {outlets: {aux: 'chat'}}]">c</a>

Not tried myself yet

See also Angular2 router in one component

RC.5 routerLink DSL (same as createUrlTree parameter) https://angular.io/docs/ts/latest/api/router/index/Router-class.html#!#createUrlTree-anchor

MVC 3 file upload and model binding

Solved

Model

public class Book
{
public string Title {get;set;}
public string Author {get;set;}
}

Controller

public class BookController : Controller
{
     [HttpPost]
     public ActionResult Create(Book model, IEnumerable<HttpPostedFileBase> fileUpload)
     {
         throw new NotImplementedException();
     }
}

And View

@using (Html.BeginForm("Create", "Book", FormMethod.Post, new { enctype = "multipart/form-data" }))
{      
     @Html.EditorFor(m => m)

     <input type="file" name="fileUpload[0]" /><br />      
     <input type="file" name="fileUpload[1]" /><br />      
     <input type="file" name="fileUpload[2]" /><br />      

     <input type="submit" name="Submit" id="SubmitMultiply" value="Upload" />
}

Note title of parameter from controller action must match with name of input elements IEnumerable<HttpPostedFileBase> fileUpload -> name="fileUpload[0]"

fileUpload must match

How to model type-safe enum types?

Starting from Scala 3, there is now enum keyword which can represent a set of constants (and other use cases)

enum Color:
   case Red, Green, Blue

scala> val red = Color.Red
val red: Color = Red
scala> red.ordinal
val res0: Int = 0

How do I pass command-line arguments to a WinForms application?

Consider you need to develop a program through which you need to pass two arguments. First of all, you need to open Program.cs class and add arguments in the Main method as like below and pass these arguments to the constructor of the Windows form.

static class Program
{    
   [STAThread]
   static void Main(string[] args)
   {            
       Application.EnableVisualStyles();
       Application.SetCompatibleTextRenderingDefault(false);
       Application.Run(new Form1(args[0], Convert.ToInt32(args[1])));           
   }
}

In windows form class, add a parameterized constructor which accepts the input values from Program class as like below.

public Form1(string s, int i)
{
    if (s != null && i > 0)
       MessageBox.Show(s + " " + i);
}

To test this, you can open command prompt and go to the location where this exe is placed. Give the file name then parmeter1 parameter2. For example, see below

C:\MyApplication>Yourexename p10 5

From the C# code above, it will prompt a Messagebox with value p10 5.

Difference between "this" and"super" keywords in Java

super() & this()

  • super() - to call parent class constructor.
  • this() - to call same class constructor.

NOTE:

  • We can use super() and this() only in constructor not anywhere else, any attempt to do so will lead to compile-time error.

  • We have to keep either super() or this() as the first line of the constructor but NOT both simultaneously.

super & this keyword

  • super - to call parent class members(variables and methods).
  • this - to call same class members(variables and methods).

NOTE: We can use both of them anywhere in a class except static areas(static block or method), any attempt to do so will lead to compile-time error.

How to write a std::string to a UTF-8 text file

Use Glib::ustring from glibmm.

It is the only widespread UTF-8 string container (AFAIK). While glyph (not byte) based, it has the same method signatures as std::string so the port should be simple search and replace (just make sure that your data is valid UTF-8 before loading it into a ustring).

How to delete from multiple tables in MySQL?

I found this article which showing you how to delete data from multiple tables by using MySQL DELETE JOIN statement with good explanation.

enter image description here

How to trigger an event in input text after I stop typing/writing?

SOLUTION:

Here is the solution. Executing a function after the user has stopped typing for a specified amount of time:

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
  clearTimeout (timer);
  timer = setTimeout(callback, ms);
 };
})();

Usage

$('input').keyup(function() {
  delay(function(){
    alert('Hi, func called');
  }, 1000 );
});

How to SUM two fields within an SQL query

SUM is an aggregate function. It will calculate the total for each group. + is used for calculating two or more columns in a row.

Consider this example,

ID  VALUE1  VALUE2
===================
1   1       2
1   2       2
2   3       4
2   4       5

 

SELECT  ID, SUM(VALUE1), SUM(VALUE2)
FROM    tableName
GROUP   BY ID

will result

ID, SUM(VALUE1), SUM(VALUE2)
1   3           4
2   7           9

 

SELECT  ID, VALUE1 + VALUE2
FROM    TableName

will result

ID, VALUE1 + VALUE2
1   3
1   4
2   7
2   9

 

SELECT  ID, SUM(VALUE1 + VALUE2)
FROM    tableName
GROUP   BY ID

will result

ID, SUM(VALUE1 + VALUE2)
1   7
2   16

SQL Server Regular expressions in T-SQL

In case anyone else is still looking at this question, http://www.sqlsharp.com/ is a free, easy way to add regular expression CLR functions into your database.

Difference between char* and const char*?

The first you can actually change if you want to, the second you can't. Read up about const correctness (there's some nice guides about the difference). There is also char const * name where you can't repoint it.

Is it possible to create static classes in PHP (like in C#)?

final Class B{

    static $staticVar;
    static function getA(){
        self::$staticVar = New A;
    }
}

the stucture of b is calld a singeton handler you can also do it in a

Class a{
    static $instance;
    static function getA(...){
        if(!isset(self::$staticVar)){
            self::$staticVar = New A(...);
        }
        return self::$staticVar;
    }
}

this is the singleton use $a = a::getA(...);

Java error: Implicit super constructor is undefined for default constructor

It is possible but not the way you have it.

You have to add a no-args constructor to the base class and that's it!

public abstract class A {
    private String name;
    public A(){
        this.name = getName();
    }
    public abstract String getName();


    public String toString(){
        return "simple class name: " + this.getClass().getSimpleName() + " name:\"" + this.name + "\"";
    }
}
class B extends A {
    public String getName(){
        return "my name is B";
    }
    public static void main( String [] args ) {
        System.out.println( new C() );
    }
}
class C extends A {
    public String getName() {
        return "Zee";
    }
}

When you don't add a constructor ( any ) to a class the compiler add the default no arg contructor for you.

When the defualt no arg calls to super(); and since you don't have it in the super class you get that error message.

That's about the question it self.

Now, expanding the answer:

Are you aware that creating a subclass ( behavior ) to specify different a different value ( data ) makes no sense??!!! I hope you do.

If the only thing that is changes is the "name" then a single class parametrized is enough!

So you don't need this:

MyClass a = new A("A");
MyClass b = new B("B");
MyClass c = new C("C");
MyClass d = new D("D");

or

MyClass a = new A(); // internally setting "A" "B", "C" etc.
MyClass b = new B();
MyClass c = new C();
MyClass d = new D();

When you can write this:

MyClass a = new MyClass("A");
MyClass b = new MyClass("B");
MyClass c = new MyClass("C");
MyClass d = new MyClass("D");

If I were to change the method signature of the BaseClass constructor, I would have to change all the subclasses.

Well that's why inheritance is the artifact that creates HIGH coupling, which is undesirable in OO systems. It should be avoided and perhaps replaced with composition.

Think if you really really need them as subclass. That's why you see very often interfaces used insted:

 public interface NameAware {
     public String getName();
 }



 class A implements NameAware ...
 class B implements NameAware ...
 class C ... etc. 

Here B and C could have inherited from A which would have created a very HIGH coupling among them, by using interfaces the coupling is reduced, if A decides it will no longer be "NameAware" the other classes won't broke.

Of course, if you want to reuse behavior this won't work.

What version of MongoDB is installed on Ubuntu

When you entered in mongo shell using "mongo" command , that time only you will notice

MongoDB shell version v3.4.0-rc2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.0-rc2

also you can try command,in mongo shell , db.version()

How can I change a button's color on hover?

Seems your selector is wrong, try using:

a.button:hover{
     background: #383;
}

Your code

a.button a:hover

Means it is going to search for an a element inside a with class button.

How to create global variables accessible in all views using Express / Node.JS?

In your app.js you need add something like this

global.myvar = 100;

Now, in all your files you want use this variable, you can just access it as myvar

Basic text editor in command prompt?

As said by Morne you can use the vi editor for windows
Also you can get CodeBlocks for windows from here
Install it and direct your PATH environment variable of your windows installation to gcc or other binaries in bin folder of codeblocks installation folder.
Now you can use gcc or other compilers from cmd like linux.

PHP array() to javascript array()

 <script> var disabledDaysRange = $disabledDaysRange ???? Please Help;
 $(function() {
     function disableRangeOfDays(d) {

in the above assign array to javascript variable "disableDaysRange"

$disallowDates = "";
echo "[";
foreach($disabledDaysRange as $disableDates){
 $disallowDates .= "'".$disableDates."',";
}

echo substr(disallowDates,0,(strlen(disallowDates)-1)); // this will escape the last comma from $disallowDates
echo "];";

so your javascript var diableDateRange shoudl be 

var diableDateRange = ["2013-01-01","2013-01-02","2013-01-03"];

Retrieve column values of the selected row of a multicolumn Access listbox

Just a little addition. If you've only selected 1 row then the code below will select the value of a column (index of 4, but 5th column) for the selected row:

me.lstIssues.Column(4)

This saves having to use the ItemsSelected property.

Kristian

What is "git remote add ..." and "git push origin master"?

git is like UNIX. User friendly but picky about its friends. It's about as powerful and as user friendly as a shell pipeline.

That being said, once you understand its paradigms and concepts, it has the same zenlike clarity that I've come to expect from UNIX command line tools. You should consider taking some time off to read one of the many good git tutorials available online. The Pro Git book is a good place to start.

To answer your first question.

  1. What is git remote add ...

    As you probably know, git is a distributed version control system. Most operations are done locally. To communicate with the outside world, git uses what are called remotes. These are repositories other than the one on your local disk which you can push your changes into (so that other people can see them) or pull from (so that you can get others changes). The command git remote add origin [email protected]:peter/first_app.gitcreates a new remote called origin located at [email protected]:peter/first_app.git. Once you do this, in your push commands, you can push to origin instead of typing out the whole URL.

  2. What is git push origin master

    This is a command that says "push the commits in the local branch named master to the remote named origin". Once this is executed, all the stuff that you last synchronised with origin will be sent to the remote repository and other people will be able to see them there.

Now about transports (i.e. what git://) means. Remote repository URLs can be of many types (file://, https:// etc.). Git simply relies on the authentication mechanism provided by the transport to take care of permissions and stuff. This means that for file:// URLs, it will be UNIX file permissions, etc. The git:// scheme is asking git to use its own internal transport protocol, which is optimised for sending git changesets around. As for the exact URL, it's the way it is because of the way github has set up its git server.

Now the verbosity. The command you've typed is the general one. It's possible to tell git something like "the branch called master over here is local mirror of the branch called foo on the remote called bar". In git speak, this means that master tracks bar/foo. When you clone for the first time, you will get a branch called master and a remote called origin (where you cloned from) with the local master set to track the master on origin. Once this is set up, you can simply say git push and it'll do it. The longer command is available in case you need it (e.g. git push might push to the official public repo and git push review master can be used to push to a separate remote which your team uses to review code). You can set your branch to be a tracking branch using the --set-upstream option of the git branch command.

I've felt that git (unlike most other apps I've used) is better understood from the inside out. Once you understand how data is stored and maintained inside the repository, the commands and what they do become crystal clear. I do agree with you that there's some elitism amongst many git users but I also found that with UNIX users once upon a time, and it was worth ploughing past them to learn the system. Good luck!

Support for "border-radius" in IE

A workaround and a handy tool:

CSS3Pie uses .htc files and the behavior property to implement CSS3 into IE 6 - 8.

Modernizr is a bit of javascript that will put classes on your html element, allowing you to serve different style definitions to different browsers based on their capabilities.

Obviously, these both add more overhead, but with IE9 due to only run on Vista/7 we might be stuck for quite awhile. As of August 2010 Windows XP still accounts for 48% of web client OSes.

How to extract the decision rules from scikit-learn decision-tree?

I needed a more human-friendly format of rules from the Decision Tree. I'm building open-source AutoML Python package and many times MLJAR users want to see the exact rules from the tree.

That's why I implemented a function based on paulkernfeld answer.

def get_rules(tree, feature_names, class_names):
    tree_ = tree.tree_
    feature_name = [
        feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
        for i in tree_.feature
    ]

    paths = []
    path = []
    
    def recurse(node, path, paths):
        
        if tree_.feature[node] != _tree.TREE_UNDEFINED:
            name = feature_name[node]
            threshold = tree_.threshold[node]
            p1, p2 = list(path), list(path)
            p1 += [f"({name} <= {np.round(threshold, 3)})"]
            recurse(tree_.children_left[node], p1, paths)
            p2 += [f"({name} > {np.round(threshold, 3)})"]
            recurse(tree_.children_right[node], p2, paths)
        else:
            path += [(tree_.value[node], tree_.n_node_samples[node])]
            paths += [path]
            
    recurse(0, path, paths)

    # sort by samples count
    samples_count = [p[-1][1] for p in paths]
    ii = list(np.argsort(samples_count))
    paths = [paths[i] for i in reversed(ii)]
    
    rules = []
    for path in paths:
        rule = "if "
        
        for p in path[:-1]:
            if rule != "if ":
                rule += " and "
            rule += str(p)
        rule += " then "
        if class_names is None:
            rule += "response: "+str(np.round(path[-1][0][0][0],3))
        else:
            classes = path[-1][0][0]
            l = np.argmax(classes)
            rule += f"class: {class_names[l]} (proba: {np.round(100.0*classes[l]/np.sum(classes),2)}%)"
        rule += f" | based on {path[-1][1]:,} samples"
        rules += [rule]
        
    return rules

The rules are sorted by the number of training samples assigned to each rule. For each rule, there is information about the predicted class name and probability of prediction for classification tasks. For the regression task, only information about the predicted value is printed.

Example

from sklearn import datasets
from sklearn.tree import DecisionTreeRegressor
from sklearn import tree

# Prepare the data data
boston = datasets.load_boston()
X = boston.data
y = boston.target

# Fit the regressor, set max_depth = 3
regr = DecisionTreeRegressor(max_depth=3, random_state=1234)
model = regr.fit(X, y)

# Print rules
rules = get_rules(regr, boston.feature_names, None)
for r in rules:
    print(r)

The printed rules:

if (RM <= 6.941) and (LSTAT <= 14.4) and (DIS > 1.385) then response: 22.905 | based on 250 samples
if (RM <= 6.941) and (LSTAT > 14.4) and (CRIM <= 6.992) then response: 17.138 | based on 101 samples
if (RM <= 6.941) and (LSTAT > 14.4) and (CRIM > 6.992) then response: 11.978 | based on 74 samples
if (RM > 6.941) and (RM <= 7.437) and (NOX <= 0.659) then response: 33.349 | based on 43 samples
if (RM > 6.941) and (RM > 7.437) and (PTRATIO <= 19.65) then response: 45.897 | based on 29 samples
if (RM <= 6.941) and (LSTAT <= 14.4) and (DIS <= 1.385) then response: 45.58 | based on 5 samples
if (RM > 6.941) and (RM <= 7.437) and (NOX > 0.659) then response: 14.4 | based on 3 samples
if (RM > 6.941) and (RM > 7.437) and (PTRATIO > 19.65) then response: 21.9 | based on 1 samples

I've summarized the ways to extract rules from the Decision Tree in my article: Extract Rules from Decision Tree in 3 Ways with Scikit-Learn and Python.

Animate element transform rotate

I stumbled upon this post, looking to use CSS transform in jQuery for an infinite loop animation. This one worked fine for me. I don't know how professional it is though.

function progressAnim(e) {
    var ang = 0;

    setInterval(function () {
        ang += 3;
        e.css({'transition': 'all 0.01s linear',
        'transform': 'rotate(' + ang + 'deg)'});
    }, 10);
}

Example of using:

var animated = $('#elem');
progressAnim(animated)

What is the equivalent of ngShow and ngHide in Angular 2+?

According to Angular 1 documentation of ngShow and ngHide, both of these directive adds the css style display: none !important;, to the element according to the condition of that directive (for ngShow adds the css on false value, and for ngHide adds the css for true value).

We can achieve this behavior using Angular 2 directive ngClass:

/* style.css */
.hide 
{
    display: none !important;
}

<!-- old angular1 ngShow -->
<div ng-show="ngShowVal"> I'm Angular1 ngShow... </div>

<!-- become new angular2 ngClass -->
<div [ngClass]="{ 'hide': !ngShowVal }"> I'm Angular2 ngShow... </div>

<!-- old angular2 ngHide -->
<div ng-hide="ngHideVal"> I'm Angular1 ngHide... </div>

<!-- become new angular2 ngClass -->
<div [ngClass]="{ 'hide': ngHideVal }"> I'm Angular2 ngHide... </div>

Notice that for show behavior in Angular2 we need to add ! (not) before the ngShowVal, and for hide behavior in Angular2 we don't need to add ! (not) before the ngHideVal.

How to reload page every 5 seconds?

setTimeout(function () { location.reload(1); }, 5000);

But as development tools go, you are probably better off with https://addons.mozilla.org/en-US/firefox/addon/115

How do I get the full path of the current file's directory?

import os
print os.path.dirname(__file__)

How do I find a default constraint using INFORMATION_SCHEMA?

Necromancing.
If you only need to check if a default-constraint exists
(default-constraint(s) may have different name in poorly-managed DBs),
use INFORMATION_SCHEMA.COLUMNS (column_default):

IF NOT EXISTS(
    SELECT * FROM INFORMATION_SCHEMA.COLUMNS
    WHERE (1=1) 
    AND TABLE_SCHEMA = 'dbo' 
    AND TABLE_NAME = 'T_VWS_PdfBibliothek' 
    AND COLUMN_NAME = 'PB_Text'
    AND COLUMN_DEFAULT IS NOT NULL  
)
BEGIN 
    EXECUTE('ALTER TABLE dbo.T_VWS_PdfBibliothek 
                ADD CONSTRAINT DF_T_VWS_PdfBibliothek_PB_Text DEFAULT (N''image'') FOR PB_Text; 
    '); 
END 

If you want to check by the constraint-name only:

-- Alternative way: 
IF OBJECT_ID('DF_CONSTRAINT_NAME', 'D') IS NOT NULL 
BEGIN
    -- constraint exists, deal with it.
END 

And last but not least, you can just create a view called
INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS:

CREATE VIEW INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS 
AS 
SELECT 
     DB_NAME() AS CONSTRAINT_CATALOG 
    ,csch.name AS CONSTRAINT_SCHEMA
    ,dc.name AS CONSTRAINT_NAME 
    ,DB_NAME() AS TABLE_CATALOG 
    ,sch.name AS TABLE_SCHEMA 
    ,syst.name AS TABLE_NAME 
    ,sysc.name AS COLUMN_NAME 
    ,COLUMNPROPERTY(sysc.object_id, sysc.name, 'ordinal') AS ORDINAL_POSITION 
    ,dc.type_desc AS CONSTRAINT_TYPE 
    ,dc.definition AS COLUMN_DEFAULT 

    -- ,dc.create_date 
    -- ,dc.modify_date 
FROM sys.columns AS sysc -- 46918 / 3892 with inner joins + where 
-- FROM sys.all_columns AS sysc -- 55429 / 3892 with inner joins + where 

INNER JOIN sys.tables AS syst 
    ON syst.object_id = sysc.object_id 

INNER JOIN sys.schemas AS sch
    ON sch.schema_id = syst.schema_id 

INNER JOIN sys.default_constraints AS dc 
    ON sysc.default_object_id = dc.object_id

INNER JOIN sys.schemas AS csch
    ON csch.schema_id = dc.schema_id 

WHERE (1=1) 
AND dc.is_ms_shipped = 0 

/*
WHERE (1=1) 
AND sch.name = 'dbo'
AND syst.name = 'tablename'
AND sysc.name = 'columnname'
*/

How can I echo a newline in a batch file?

There is a standard feature echo: in cmd/bat-files to write blank line, which emulates a new line in your cmd-output:

@echo off
@echo line1
@echo:
@echo line2

Output of cited above cmd-file:

line1

line2

An example of how to use getopts in bash

"getops" and "getopt" are very limited. While "getopt" is suggested not to be used at all, it does offer long options. Where as "getopts" does only allow single character options such as "-a" "-b". There are a few more disadvantages when using either one.

So i've written a small script that replaces "getopts" and "getopt". It's a start, it could probably be improved a lot.

Update 08-04-2020: I've added support for hyphens e.g. "--package-name".

Usage: "./script.sh package install --package "name with space" --build --archive"

# Example:
# parseArguments "${@}"
# echo "${ARG_0}" -> package
# echo "${ARG_1}" -> install
# echo "${ARG_PACKAGE}" -> "name with space"
# echo "${ARG_BUILD}" -> 1 (true)
# echo "${ARG_ARCHIVE}" -> 1 (true)
function parseArguments() {
  PREVIOUS_ITEM=''
  COUNT=0
  for CURRENT_ITEM in "${@}"
  do
    if [[ ${CURRENT_ITEM} == "--"* ]]; then
      printf -v "ARG_$(formatArgument "${CURRENT_ITEM}")" "%s" "1" # could set this to empty string and check with [ -z "${ARG_ITEM-x}" ] if it's set, but empty.
    else
      if [[ $PREVIOUS_ITEM == "--"* ]]; then
        printf -v "ARG_$(formatArgument "${PREVIOUS_ITEM}")" "%s" "${CURRENT_ITEM}"
      else
        printf -v "ARG_${COUNT}" "%s" "${CURRENT_ITEM}"
      fi
    fi

    PREVIOUS_ITEM="${CURRENT_ITEM}"
    (( COUNT++ ))
  done
}

# Format argument.
function formatArgument() {
  ARGUMENT="${1^^}" # Capitalize.
  ARGUMENT="${ARGUMENT/--/}" # Remove "--".
  ARGUMENT="${ARGUMENT//-/_}" # Replace "-" with "_".
  echo "${ARGUMENT}"
}

Create a new workspace in Eclipse

In Window->Preferences->General->Startup and Shutdown->Workspaces, make sure that 'Prompt for Workspace on startup' is checked.

Then close eclipse and reopen.

Then you'll be prompted for a workspace to open. You can create a new workspace from that dialogue.

Or File->Switch Workspace->Other...

PHP - Check if the page run on Mobile or Desktop browser

There is a very nice PHP library for detecting mobile clients here: http://mobiledetect.net

Using that it's quite easy to only display content for a mobile:

include 'Mobile_Detect.php';
$detect = new Mobile_Detect();

// Check for any mobile device.
if ($detect->isMobile()){
   // mobile content
}
else {
   // other content for desktops
}

Inserting a value into all possible locations in a list

If l is your list and X is your value:

for i in range(len(l) + 1):
    print l[:i] + [X] + l[i:]

How can I call a function using a function pointer?

Initially define a function pointer array which takes a void and returns a void.

Assuming that your function is taking a void and returning a void.

typedef void (*func_ptr)(void);

Now you can use this to create function pointer variables of such functions.

Like below:

func_ptr array_of_fun_ptr[3];

Now store the address of your functions in the three variables.

array_of_fun_ptr[0]= &A;
array_of_fun_ptr[1]= &B;
array_of_fun_ptr[2]= &C;

Now you can call these functions using function pointers as below:

some_a=(*(array_of_fun_ptr[0]))();
some_b=(*(array_of_fun_ptr[1]))();
some_c=(*(array_of_fun_ptr[2]))();

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

Reformat affects the whole source code and may rebreak your lines, while Correct Indentation only affects the whitespace at the beginning of the lines.

Using media breakpoints in Bootstrap 4-alpha

Use breakpoint mixins like this:

.something {
    padding: 5px;
    @include media-breakpoint-up(sm) { 
        padding: 20px;
    }
    @include media-breakpoint-up(md) { 
        padding: 40px;
    }
}

v4 breakpoints reference

v4 alpha6 breakpoints reference


Below full options and values.

Breakpoint & up (toggle on value and above):

@include media-breakpoint-up(xs) { ... }
@include media-breakpoint-up(sm) { ... }
@include media-breakpoint-up(md) { ... }
@include media-breakpoint-up(lg) { ... }
@include media-breakpoint-up(xl) { ... }

breakpoint & up values:

// Extra small devices (portrait phones, less than 576px)
// No media query since this is the default in Bootstrap

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

breakpoint & down (toggle on value and down):

@include media-breakpoint-down(xs) { ... }
@include media-breakpoint-down(sm) { ... }
@include media-breakpoint-down(md) { ... }
@include media-breakpoint-down(lg) { ... }

breakpoint & down values:

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, less than 768px)
@media (max-width: 767px) { ... }

// Medium devices (tablets, less than 992px)
@media (max-width: 991px) { ... }

// Large devices (desktops, less than 1200px)
@media (max-width: 1199px) { ... }

// Extra large devices (large desktops)
// No media query since the extra-large breakpoint has no upper bound on its width

breakpoint only:

@include media-breakpoint-only(xs) { ... }
@include media-breakpoint-only(sm) { ... }
@include media-breakpoint-only(md) { ... }
@include media-breakpoint-only(lg) { ... }
@include media-breakpoint-only(xl) { ... }

breakpoint only values (toggle in between values only):

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) and (max-width: 767px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) and (max-width: 991px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) and (max-width: 1199px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

Display/Print one column from a DataFrame of Series in Pandas

Not sure what you are really after but if you want to print exactly what you have you can do:

Option 1

print(df['Item'].to_csv(index=False))

Sweet
Candy
Chocolate

Option 2

for v in df['Item']:
    print(v)

Sweet
Candy
Chocolate

Remove lines that contain certain string

I have used this to remove unwanted words from text files:

bad_words = ['abc', 'def', 'ghi', 'jkl']

with open('List of words.txt') as badfile, open('Clean list of words.txt', 'w') as cleanfile:
    for line in badfile:
        clean = True
        for word in bad_words:
            if word in line:
                clean = False
        if clean == True:
            cleanfile.write(line)

Or to do the same for all files in a directory:

import os

bad_words = ['abc', 'def', 'ghi', 'jkl']

for root, dirs, files in os.walk(".", topdown = True):
    for file in files:
        if '.txt' in file:
            with open(file) as filename, open('clean '+file, 'w') as cleanfile:
                for line in filename:
                    clean = True
                    for word in bad_words:
                        if word in line:
                            clean = False
                    if clean == True:
                        cleanfile.write(line)

I'm sure there must be a more elegant way to do it, but this did what I wanted it to.

Rails: Using greater than/less than with a where statement

Update

Rails core team decided to revert this change for a while, in order to discuss it in more detail. See this comment and this PR for more info.

I am leaving my answer only for educational purposes.


new 'syntax' for comparison in Rails 6.1 (Reverted)

Rails 6.1 added a new 'syntax' for comparison operators in where conditions, for example:

Post.where('id >': 9)
Post.where('id >=': 9)
Post.where('id <': 3)
Post.where('id <=': 3)

So your query can be rewritten as follows:

User.where('id >': 200) 

Here is a link to PR where you can find more examples.

Calling a Sub and returning a value

You should be using a Property:

Private _myValue As String
Public Property MyValue As String
    Get
        Return _myValue
    End Get
    Set(value As String)
        _myValue = value
     End Set
End Property

Then use it like so:

MyValue = "Hello"
Console.write(MyValue)

How to round a floating point number up to a certain decimal place?

Here is my solution for the round up/down problem

< .5  round down

> = .5  round up

import math

def _should_round_down(val: float):
    if val < 0:
        return ((val * -1) % 1) < 0.5
    return (val % 1) < 0.5

def _round(val: float, ndigits=0):
    if ndigits > 0:
        val *= 10 ** (ndigits - 1)
    is_positive = val > 0
    tmp_val = val
    if not is_positive:
        tmp_val *= -1
    rounded_value = math.floor(tmp_val) if _should_round_down(val) else math.ceil(tmp_val)
    if not is_positive:
        rounded_value *= -1
    if ndigits > 0:
        rounded_value /= 10 ** (ndigits - 1)
    return rounded_value

# test
# nr = 12.2548
# for digit in range(0, 4):
#     print("{} decimals : {} -> {}".format(digit, nr, _round(nr, digit)))

# output
# 0 decimals : 12.2548 -> 12
# 1 decimals : 12.2548 -> 12.0
# 2 decimals : 12.2548 -> 12.3
# 3 decimals : 12.2548 -> 12.25

Git Ignores and Maven targets

As already pointed out in comments by Abhijeet you can just add line like:

/target/**

to exclude file in \.git\info\ folder.

Then if you want to get rid of that target folder in your remote repo you will need to first manually delete this folder from your local repository, commit and then push it. Thats because git will show you content of a target folder as modified at first.

How to set zoom level in google map

For zooming your map two level then just add this small code of line map.setZoom(map.getZoom() + 2);

Installing Apache Maven Plugin for Eclipse

For Eclipse (Helios) the following procedure works - I've tried it:

  1. Go to Help -> Install New software
  2. Add the following link: http://download.eclipse.org/technology/m2e/releases/1.3
  3. After results found unselect "sl4j... (optional)"
  4. Next

How to Sort Date in descending order From Arraylist Date in android?

Date is Comparable so just create list of List<Date> and sort it using Collections.sort(). And use Collections.reverseOrder() to get comparator in reverse ordering.

From Java Doc

Returns a comparator that imposes the reverse ordering of the specified comparator. If the specified comparator is null, this method is equivalent to reverseOrder() (in other words, it returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface).

What is the difference between dim and set in vba

There's no reason to use set unless referring to an object reference. It's good practice to only use it in that context. For all other simple data types, just use an assignment operator. It's a good idea to dim (dimension) ALL variables however:

Examples of simple data types would be integer, long, boolean, string. These are just data types and do not have their own methods and properties.

Dim i as Integer
i = 5

Dim myWord as String
myWord = "Whatever I want"

An example of an object would be a Range, a Worksheet, or a Workbook. These have their own methods and properties.

Dim myRange as Range
Set myRange = Sheet1.Range("A1")

If you try to use the last line without Set, VB will throw an error. Now that you have an object declared you can access its properties and methods.

myString = myRange.Value

WCF service startup error "This collection already contains an address with scheme http"

I had this problem, and the cause was rather silly. I was trying out Microsoft's demo regarding running a ServiceHost from w/in a Command Line executable. I followed the instructions, including where it says to add the appropriate Service (and interface). But I got the above error.

Turns out when I added the service class, VS automatically added the configuration to the app.config. And the demo was trying to add that info too. Since it was already in the config, I removed the demo part, and it worked.

Pinging servers in Python

Programmatic ICMP ping is complicated due to the elevated privileges required to send raw ICMP packets, and calling ping binary is ugly. For server monitoring, you can achieve the same result using a technique called TCP ping:

# pip3 install tcping
>>> from tcping import Ping
# Ping(host, port, timeout)
>>> ping = Ping('212.69.63.54', 22, 60)
>>> ping.ping(3)
Connected to 212.69.63.54[:22]: seq=1 time=23.71 ms
Connected to 212.69.63.54[:22]: seq=2 time=24.38 ms
Connected to 212.69.63.54[:22]: seq=3 time=24.00 ms

Internally, this simply establishes a TCP connection to the target server and drops it immediately, measuring time elapsed. This particular implementation is a bit limited in that it doesn't handle closed ports but for your own servers it works pretty well.

How do I clone into a non-empty directory?

I liked Dale's answer, and I also added

git clone --depth 2 --no-checkout repo-to-clone existing-dir/existing-dir.tmp
git branch dev_new214
git checkout dev_new214
git add .
git commit
git checkout dev
git merge dev_new214

The shallow depth avoided a lot of extra early dev commits. The new branch gave us a good visual history that there was some new code from this server that was placed in. That is the perfect use branches in my opinion. My thanks to the great insight of all the people who posted here.

AngularJS - get element attributes values

You just can use doStuff($event) in your markup and get the data-attribute values via currentTarget.getAttribute("data-id")) in angular. HTML:

<div ng-controller="TestCtrl">
    <button data-id="345" ng-click="doStuff($event)">Button</button>
</div>

JS:

var app = angular.module("app", []);
app.controller("TestCtrl", function ($scope) {
    $scope.doStuff = function (item) {
        console.log(item.currentTarget);
        console.log(item.currentTarget.getAttribute("data-id"));
    };
});

Forked your initial jsfiddle: http://jsfiddle.net/9mmd1zht/116/

Is there a way to create interfaces in ES6 / Node 4?

Flow allows interface specification, without having to convert your whole code base to TypeScript.

Interfaces are a way of breaking dependencies, while stepping cautiously within existing code.

Code for download video from Youtube on Java, Android

Ref : Youtube Video Download (Android/Java)

private static final HashMap<String, Meta> typeMap = new HashMap<String, Meta>();

initTypeMap(); call first

class Meta {
    public String num;
    public String type;
    public String ext;

    Meta(String num, String ext, String type) {
        this.num = num;
        this.ext = ext;
        this.type = type;
    }
}

class Video {
    public String ext = "";
    public String type = "";
    public String url = "";

    Video(String ext, String type, String url) {
        this.ext = ext;
        this.type = type;
        this.url = url;
    }
}

public ArrayList<Video> getStreamingUrisFromYouTubePage(String ytUrl)
        throws IOException {
    if (ytUrl == null) {
        return null;
    }

    // Remove any query params in query string after the watch?v=<vid> in
    // e.g.
    // http://www.youtube.com/watch?v=0RUPACpf8Vs&feature=youtube_gdata_player
    int andIdx = ytUrl.indexOf('&');
    if (andIdx >= 0) {
        ytUrl = ytUrl.substring(0, andIdx);
    }

    // Get the HTML response
    /* String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)";*/
   /* HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            userAgent);
    HttpGet request = new HttpGet(ytUrl);
    HttpResponse response = client.execute(request);*/
    String html = "";
    HttpsURLConnection c = (HttpsURLConnection) new URL(ytUrl).openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    InputStream in = c.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder str = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        str.append(line.replace("\\u0026", "&"));
    }
    in.close();
    html = str.toString();

    // Parse the HTML response and extract the streaming URIs
    if (html.contains("verify-age-thumb")) {
        Log.e("Downloader", "YouTube is asking for age verification. We can't handle that sorry.");
        return null;
    }

    if (html.contains("das_captcha")) {
        Log.e("Downloader", "Captcha found, please try with different IP address.");
        return null;
    }

    Pattern p = Pattern.compile("stream_map\":\"(.*?)?\"");
    // Pattern p = Pattern.compile("/stream_map=(.[^&]*?)\"/");
    Matcher m = p.matcher(html);
    List<String> matches = new ArrayList<String>();
    while (m.find()) {
        matches.add(m.group());
    }

    if (matches.size() != 1) {
        Log.e("Downloader", "Found zero or too many stream maps.");
        return null;
    }

    String urls[] = matches.get(0).split(",");
    HashMap<String, String> foundArray = new HashMap<String, String>();
    for (String ppUrl : urls) {
        String url = URLDecoder.decode(ppUrl, "UTF-8");
        Log.e("URL","URL : "+url);

        Pattern p1 = Pattern.compile("itag=([0-9]+?)[&]");
        Matcher m1 = p1.matcher(url);
        String itag = null;
        if (m1.find()) {
            itag = m1.group(1);
        }

        Pattern p2 = Pattern.compile("signature=(.*?)[&]");
        Matcher m2 = p2.matcher(url);
        String sig = null;
        if (m2.find()) {
            sig = m2.group(1);
        } else {
            Pattern p23 = Pattern.compile("signature&s=(.*?)[&]");
            Matcher m23 = p23.matcher(url);
            if (m23.find()) {
                sig = m23.group(1);
            }
        }

        Pattern p3 = Pattern.compile("url=(.*?)[&]");
        Matcher m3 = p3.matcher(ppUrl);
        String um = null;
        if (m3.find()) {
            um = m3.group(1);
        }

        if (itag != null && sig != null && um != null) {
            Log.e("foundArray","Adding Value");
            foundArray.put(itag, URLDecoder.decode(um, "UTF-8") + "&"
                    + "signature=" + sig);
        }
    }
    Log.e("foundArray","Size : "+foundArray.size());
    if (foundArray.size() == 0) {
        Log.e("Downloader", "Couldn't find any URLs and corresponding signatures");
        return null;
    }


    ArrayList<Video> videos = new ArrayList<Video>();

    for (String format : typeMap.keySet()) {
        Meta meta = typeMap.get(format);

        if (foundArray.containsKey(format)) {
            Video newVideo = new Video(meta.ext, meta.type,
                    foundArray.get(format));
            videos.add(newVideo);
            Log.d("Downloader", "YouTube Video streaming details: ext:" + newVideo.ext
                    + ", type:" + newVideo.type + ", url:" + newVideo.url);
        }
    }

    return videos;
}

private class YouTubePageStreamUriGetter extends AsyncTask<String, String, ArrayList<Video>> {
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = ProgressDialog.show(webViewActivity.this, "",
                "Connecting to YouTube...", true);
    }

    @Override
    protected ArrayList<Video> doInBackground(String... params) {
        ArrayList<Video> fVideos = new ArrayList<>();
        String url = params[0];
        try {
            ArrayList<Video> videos = getStreamingUrisFromYouTubePage(url);
            /*                Log.e("Downloader","Size of Video : "+videos.size());*/
            if (videos != null && !videos.isEmpty()) {
                for (Video video : videos)
                {
                    Log.e("Downloader", "ext : " + video.ext);
                    if (video.ext.toLowerCase().contains("mp4") || video.ext.toLowerCase().contains("3gp") || video.ext.toLowerCase().contains("flv") || video.ext.toLowerCase().contains("webm")) {
                        ext = video.ext.toLowerCase();
                        fVideos.add(new Video(video.ext,video.type,video.url));
                    }
                }


                return fVideos;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Downloader", "Couldn't get YouTube streaming URL", e);
        }
        Log.e("Downloader", "Couldn't get stream URI for " + url);
        return null;
    }

    @Override
    protected void onPostExecute(ArrayList<Video> streamingUrl) {
        super.onPostExecute(streamingUrl);
        progressDialog.dismiss();
        if (streamingUrl != null) {
            if (!streamingUrl.isEmpty()) {
                //Log.e("Steaming Url", "Value : " + streamingUrl);

                for (int i = 0; i < streamingUrl.size(); i++) {
                    Video fX = streamingUrl.get(i);
                    Log.e("Founded Video", "URL : " + fX.url);
                    Log.e("Founded Video", "TYPE : " + fX.type);
                    Log.e("Founded Video", "EXT : " + fX.ext);
                }
                //new ProgressBack().execute(new String[]{streamingUrl, filename + "." + ext});
            }
        }
    }
}
public void initTypeMap()
{
    typeMap.put("13", new Meta("13", "3GP", "Low Quality - 176x144"));
    typeMap.put("17", new Meta("17", "3GP", "Medium Quality - 176x144"));
    typeMap.put("36", new Meta("36", "3GP", "High Quality - 320x240"));
    typeMap.put("5", new Meta("5", "FLV", "Low Quality - 400x226"));
    typeMap.put("6", new Meta("6", "FLV", "Medium Quality - 640x360"));
    typeMap.put("34", new Meta("34", "FLV", "Medium Quality - 640x360"));
    typeMap.put("35", new Meta("35", "FLV", "High Quality - 854x480"));
    typeMap.put("43", new Meta("43", "WEBM", "Low Quality - 640x360"));
    typeMap.put("44", new Meta("44", "WEBM", "Medium Quality - 854x480"));
    typeMap.put("45", new Meta("45", "WEBM", "High Quality - 1280x720"));
    typeMap.put("18", new Meta("18", "MP4", "Medium Quality - 480x360"));
    typeMap.put("22", new Meta("22", "MP4", "High Quality - 1280x720"));
    typeMap.put("37", new Meta("37", "MP4", "High Quality - 1920x1080"));
    typeMap.put("33", new Meta("38", "MP4", "High Quality - 4096x230"));
}

Edit 2:

Some time This Code Not worked proper

Same-origin policy

https://en.wikipedia.org/wiki/Same-origin_policy

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is [CORS][1]. 

Ref : https://superuser.com/questions/773719/how-do-all-of-these-save-video-from-youtube-services-work/773998#773998

url_encoded_fmt_stream_map // traditional: contains video and audio stream
adaptive_fmts              // DASH: contains video or audio stream

Each of these is a comma separated array of what I would call "stream objects". Each "stream object" will contain values like this

url  // direct HTTP link to a video
itag // code specifying the quality
s    // signature, security measure to counter downloading

Each URL will be encoded so you will need to decode them. Now the tricky part.

YouTube has at least 3 security levels for their videos

unsecured // as expected, you can download these with just the unencoded URL
s         // see below
RTMPE     // uses "rtmpe://" protocol, no known method for these

The RTMPE videos are typically used on official full length movies, and are protected with SWF Verification Type 2. This has been around since 2011 and has yet to be reverse engineered.

The type "s" videos are the most difficult that can actually be downloaded. You will typcially see these on VEVO videos and the like. They start with a signature such as

AA5D05FA7771AD4868BA4C977C3DEAAC620DE020E.0F421820F42978A1F8EAFCDAC4EF507DB5 Then the signature is scrambled with a function like this

function mo(a) {
  a = a.split("");
  a = lo.rw(a, 1);
  a = lo.rw(a, 32);
  a = lo.IC(a, 1);
  a = lo.wS(a, 77);
  a = lo.IC(a, 3);
  a = lo.wS(a, 77);
  a = lo.IC(a, 3);
  a = lo.wS(a, 44);
  return a.join("")
}

This function is dynamic, it typically changes every day. To make it more difficult the function is hosted at a URL such as

http://s.ytimg.com/yts/jsbin/html5player-en_US-vflycBCEX.js

this introduces the problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is CORS. With CORS, s.ytimg.com could add this header

Access-Control-Allow-Origin: http://www.youtube.com

and it would allow the JavaScript to download from www.youtube.com. Of course they do not do this. A workaround for this workaround is to use a CORS proxy. This is a proxy that responds with the following header to all requests

Access-Control-Allow-Origin: *

So, now that you have proxied your JS file, and used the function to scramble the signature, you can use that in the querystring to download a video.

How to use LINQ to select object with minimum or maximum property value

The following is the more generic solution. It essentially does the same thing (in O(N) order) but on any IEnumberable types and can mixed with types whose property selectors could return null.

public static class LinqExtensions
{
    public static T MinBy<T>(this IEnumerable<T> source, Func<T, IComparable> selector)
    {
        if (source == null)
        {
            throw new ArgumentNullException(nameof(source));
        }
        if (selector == null)
        {
            throw new ArgumentNullException(nameof(selector));
        }
        return source.Aggregate((min, cur) =>
        {
            if (min == null)
            {
                return cur;
            }
            var minComparer = selector(min);
            if (minComparer == null)
            {
                return cur;
            }
            var curComparer = selector(cur);
            if (curComparer == null)
            {
                return min;
            }
            return minComparer.CompareTo(curComparer) > 0 ? cur : min;
        });
    }
}

Tests:

var nullableInts = new int?[] {5, null, 1, 4, 0, 3, null, 1};
Assert.AreEqual(0, nullableInts.MinBy(i => i));//should pass

Simple pthread! C++

You should declare the thread main as:

void* print_message(void*) // takes one parameter, unnamed if you aren't using it

How to catch curl errors in PHP

Since you are interested in catching network related errors and HTTP errors, the following provides a better approach:

function curl_error_test($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $responseBody = curl_exec($ch);
    /*
     * if curl_exec failed then
     * $responseBody is false
     * curl_errno() returns non-zero number
     * curl_error() returns non-empty string
     * which one to use is up too you
     */
    if ($responseBody === false) {
        return "CURL Error: " . curl_error($ch);
    }

    $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    /*
     * 4xx status codes are client errors
     * 5xx status codes are server errors
     */
    if ($responseCode >= 400) {
        return "HTTP Error: " . $responseCode;
    }

    return "No CURL or HTTP Error";
}

Tests:

curl_error_test("http://expamle.com");          // CURL Error: Could not resolve host: expamle.com
curl_error_test("http://example.com/whatever"); // HTTP Error: 404
curl_error_test("http://example.com");          // No CURL or HTTP Error

How to synchronize a static variable among threads running different instances of a class in Java?

Yes it is true.

If you create two instance of your class

Test t1 = new Test();
Test t2 = new Test();

Then t1.foo and t2.foo both synchronize on the same static object and hence block each other.

jQuery ajax error function

Here is how you pull the asp error out.

              cache: false,
              url: "addInterview_Code.asp",
              type: "POST",
              datatype: "text",
              data: strData,
              success: function (html) {
                  alert('successful : ' + html);
                  $("#result").html("Successful");
              },
              error: function (jqXHR, textStatus, errorThrown) {
                  if (jqXHR.status == 500) {
                      alert('Internal error: ' + jqXHR.responseText);
                  } else {
                      alert('Unexpected error.');
                  }
              }

Call function with setInterval in jQuery?

jQuery is just a set of helpers/libraries written in Javascript. You can still use all Javascript features, so you can call whatever functions, also from inside jQuery callbacks. So both possibilities should be okay.

Disabling same-origin policy in Safari

There is an option to disable cross-origin restrictions in Safari 9, different from local file restrictions as mentioned above.

jQuery - setting the selected value of a select control via its text description

I haven't tested this, but this might work for you.

$("select#my-select option")
   .each(function() { this.selected = (this.text == myVal); });

How to use DISTINCT and ORDER BY in same SELECT statement?

If the output of MAX(CreationDate) is not wanted - like in the example of the original question - the only answer is the second statement of Prashant Gupta's answer:

SELECT [Category] FROM [MonitoringJob] 
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC

Explanation: you can't use the ORDER BY clause in an inline function, so the statement in the answer of Prutswonder is not useable in this case, you can't put an outer select around it and discard the MAX(CreationDate) part.

angularjs: ng-src equivalent for background-image:url(...)

This one works for me

<li ng-style="{'background-image':'url(/static/'+imgURL+')'}">...</li>

No newline after div?

div.noWrap {
    display: inline;
    }

Parenthesis/Brackets Matching using Stack algorithm

You're doing some extra checks that aren't needed. Doesn't make any diff to functionality, but a cleaner way to write your code would be:

public static boolean isParenthesisMatch(String str) {
    Stack<Character> stack = new Stack<Character>();
    char c;

    for (int i = 0; i < str.length(); i++) {
        c = str.charAt(i);
        if (c == '(' || c == '{')
            stack.push(c);
        else if (stack.empty())
            return false;
        else if (c == ')') {
            if (stack.pop() != '(')
                return false;
        } else if (c == '}') {
            if (stack.pop() != '{')
                return false;
        }
    }
    return stack.empty();
}

There is no reason to peek at a paranthesis before removing it from the stack. I'd also consider wrapping instruction blocks in parantheses to improve readability.

Ruby/Rails: converting a Date to a UNIX timestamp

I get the following when I try it:

>> Date.today.to_time.to_i
=> 1259244000
>> Time.now.to_i
=> 1259275709

The difference between these two numbers is due to the fact that Date does not store the hours, minutes or seconds of the current time. Converting a Date to a Time will result in that day, midnight.

PostgreSQL database service

you to restart services PostgreSQL from task manager click ctrl+alt+delete then chose services the postgresql-[version] chose the option to run automatically then start and apply ->ok

Why am I getting the error "connection refused" in Python? (Sockets)

try this command in terminal:

sudo ufw enable
ufw allow 12397

jQuery Validate - Enable validation for hidden fields

Just added ignore: [] in the specific page for the specific form, this solution worked for me.

$("#form_name").validate({
        ignore: [],
        onkeyup: false,
        rules: {            
        },      
        highlight:false,
    });

How to upload file using Selenium WebDriver in Java

If you have a text box to type the file path, just use sendkeys to input the file path and click on submit button. If there is no text box to type the file path and only able to click on browse button and to select the file from windows popup, you can use AutoIt tool, see the step below to use AutoIt for the same,

  1. Download and Install Autoit tool from http://www.autoitscript.com/site/autoit/

  2. Open Programs -> Autoit tool -> SciTE Script Editor.

  3. Paste the following code in Autoit editor and save it as “filename.exe “(eg: new.exe)

    Then compile and build the file to make it exe. (Tools ? Compile)

Autoit Code:

WinWaitActive("File Upload"); Name of the file upload window (Windows Popup Name: File Upload)    
Send("logo.jpg"); File name    
Send("{ENTER}")

Then Compile and Build from Tools menu of the Autoit tool -> SciTE Script Editor.

Paste the below Java code in Eclipse editor and save

Java Code:

driver.findElement(By.id("uploadbutton")).click; // open the Upload window using selenium    
Thread.sleep("20000"); // wait for page load    
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "C:\\Documents and Settings\\new.exe"); // Give  path where the exe is saved.

How can I get key's value from dictionary in Swift?

From Apple Docs

You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:

https://developer.apple.com/documentation/swift/dictionary

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."

default value for struct member in C

You can use combination of C preprocessor functions with varargs, compound literals and designated initializers for maximum convenience:

typedef struct {
    int id;
    char* name;
} employee;

#define EMPLOYEE(...) ((employee) { .id = 0, .name = "none", ##__VA_ARGS__ })

employee john = EMPLOYEE(.name="John");  // no id initialization
employee jane = EMPLOYEE(.id=5);         // no name initialization

How to export the Html Tables data into PDF using Jspdf

There is a tablePlugin for jspdf it expects array of objects and displays that data as a table. You can style the text and headers with little changes in the code. It is open source and also has examples for you to get started with.

Save the console.log in Chrome to a file

If you're running an Apache server on your localhost (don't do this on a production server), you can also post the results to a script instead of writing it to console.

So instead of console.log, you can write:

JSONP('http://localhost/save.php', {fn: 'filename.txt', data: json});

Then save.php can do this

<?php

 $fn = $_REQUEST['fn'];
 $data = $_REQUEST['data'];

 file_put_contents("path/$fn", $data);

AND/OR in Python?

or is not exclusive (e.g. xor) so or is the same thing as and/or.

'was not declared in this scope' error

Here's a simplified example based on of your problem:

if (test) 
{//begin scope 1
    int y = 1; 
}//end scope 1
else 
{//begin scope 2
    int y = 2;//error, y is not in scope
}//end scope 2
int x = y;//error, y is not in scope

In the above version you have a variable called y that is confined to scope 1, and another different variable called y that is confined to scope 2. You then try to refer to a variable named y after the end of the if, and not such variable y can be seen because no such variable exists in that scope.

You solve the problem by placing y in the outermost scope which contains all references to it:

int y;
if (test) 
{
    y = 1; 
}
else 
{
    y = 2;
}
int x = y;

I've written the example with simplified made up code to make it clearer for you to understand the issue. You should now be able to apply the principle to your code.

unsigned APK can not be installed

You can test the unsigned-apk only on Emulator. And as its step of application deployment and distribution, you should read this article atleast once, i suggest: http://developer.android.com/guide/publishing/app-signing.html.

For your question, you can find the below line in above article:

All applications must be signed. The system will not install an application that is not signed.

so you have to have signed-apk before the distribution of your application.

To generate Signed-apk of your application, there is a simple wizard procedure, click on File -> Export -> Android -> Export Android application.

enter image description here

How do I write a "tab" in Python?

Here are some more exotic Python 3 ways to get "hello" TAB "alex" (tested with Python 3.6.10):

"hello\N{TAB}alex"

"hello\N{tab}alex"

"hello\N{TaB}alex"

"hello\N{HT}alex"

"hello\N{CHARACTER TABULATION}alex"

"hello\N{HORIZONTAL TABULATION}alex"

"hello\x09alex"

"hello\u0009alex"

"hello\U00000009alex"

Actually, instead of using an escape sequence, it is possible to insert tab symbol directly into the string literal. Here is the code with a tabulation character to copy and try:

"hello alex"

If the tab in the string above won't be lost anywhere during copying the string then "print(repr(< string from above >)" should print 'hello\talex'.

See respective Python documentation for reference.

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

Execute bash script from URL

Use:

curl -s -L URL_TO_SCRIPT_HERE | bash

For example:

curl -s -L http://bitly/10hA8iC | bash

insert password into database in md5 format?

use MD5,

$query="INSERT INTO ptb_users (id,
user_id,
first_name,
last_name,
email )
VALUES('NULL',
'NULL',
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('".$password."')
)";

but MD5 is insecure. Use SHA2.

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

Read file data without saving it in Flask

We simply did:

import io
from pathlib import Path

    def test_my_upload(self, accept_json):
        """Test my uploads endpoint for POST."""
        data = {
            "filePath[]": "/tmp/bin",
            "manifest[]": (io.StringIO(str(Path(__file__).parent /
                                           "path_to_file/npmlist.json")).read(),
                           'npmlist.json'),
        }
        headers = {
            'a': 'A',
            'b': 'B'
        }
        res = self.client.post(api_route_for('/test'),
                               data=data,
                               content_type='multipart/form-data',
                               headers=headers,
                               )
        assert res.status_code == 200

Adding a tooltip to an input box

I know this is a question regarding the CSS.Tooltips library. However, for anyone else came here resulting from google search "tooltip for input box" like I did, here is the simplest way:

<input title="This is the text of the tooltip" value="44"/>

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

How do you uninstall all dependencies listed in package.json (NPM)?

This worked for me:

command prompt or gitbash into the node_modules folder in your project then execute:

npm uninstall *

Removed all of the local packages for that project.

How to handle Pop-up in Selenium WebDriver using Java

You can handle popup window or alert box:

Alert alert = driver.switchTo().alert();
alert.accept();

You can also decline the alert box:

Alert alert = driver.switchTo().alert();
alert().dismiss();

Error: The type exists in both directories

I tried pretty much every suggestion on this page, but had to delete visual studio 2017 completely off my machine. I reinstalled the latest version (2019) and it magically worked. I hope this helps someone in the future.

How to write a unit test for a Spring Boot Controller endpoint

Let assume i am having a RestController with GET/POST/PUT/DELETE operations and i have to write unit test using spring boot.I will just share code of RestController class and respective unit test.Wont be sharing any other related code to the controller ,can have assumption on that.

@RestController
@RequestMapping(value = “/myapi/myApp” , produces = {"application/json"})
public class AppController {


    @Autowired
    private AppService service;

    @GetMapping
    public MyAppResponse<AppEntity> get() throws Exception {

        MyAppResponse<AppEntity> response = new MyAppResponse<AppEntity>();
        service.getApp().stream().forEach(x -> response.addData(x));    
        return response;
    }


    @PostMapping
    public ResponseEntity<HttpStatus> create(@RequestBody AppRequest request) throws Exception {
        //Validation code       
        service.createApp(request);

        return ResponseEntity.ok(HttpStatus.OK);
    }

    @PutMapping
    public ResponseEntity<HttpStatus> update(@RequestBody IDMSRequest request) throws Exception {

        //Validation code
        service.updateApp(request);

        return ResponseEntity.ok(HttpStatus.OK);
    }

    @DeleteMapping
    public ResponseEntity<HttpStatus> delete(@RequestBody AppRequest request) throws Exception {

        //Validation        
        service.deleteApp(request.id);

        return ResponseEntity.ok(HttpStatus.OK);
    }

}

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public abstract class BaseTest {
   protected MockMvc mvc;
   @Autowired
   WebApplicationContext webApplicationContext;

   protected void setUp() {
      mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
   }
   protected String mapToJson(Object obj) throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(obj);
   }
   protected <T> T mapFromJson(String json, Class<T> clazz)
      throws JsonParseException, JsonMappingException, IOException {

      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(json, clazz);
   }
}

public class AppControllerTest extends BaseTest {

    @MockBean
    private IIdmsService service;

    private static final String URI = "/myapi/myApp";


   @Override
   @Before
   public void setUp() {
      super.setUp();
   }

   @Test
   public void testGet() throws Exception {
       AppEntity entity = new AppEntity();
      List<AppEntity> dataList = new ArrayList<AppEntity>();
      AppResponse<AppEntity> dataResponse = new AppResponse<AppEntity>();
      entity.setId(1);
      entity.setCreated_at("2020-02-21 17:01:38.717863");
      entity.setCreated_by(“Abhinav Kr”);
      entity.setModified_at("2020-02-24 17:01:38.717863");
      entity.setModified_by(“Jyoti”);
            dataList.add(entity);

      dataResponse.setData(dataList);

      Mockito.when(service.getApp()).thenReturn(dataList);

      RequestBuilder requestBuilder =  MockMvcRequestBuilders.get(URI)
                 .accept(MediaType.APPLICATION_JSON);

        MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
        MockHttpServletResponse response = mvcResult.getResponse();

        String expectedJson = this.mapToJson(dataResponse);
        String outputInJson = mvcResult.getResponse().getContentAsString();

        assertEquals(HttpStatus.OK.value(), response.getStatus());
        assertEquals(expectedJson, outputInJson);
   }

   @Test
   public void testCreate() throws Exception {

       AppRequest request = new AppRequest();
       request.createdBy = 1;
       request.AppFullName = “My App”;
       request.appTimezone = “India”;

       String inputInJson = this.mapToJson(request);
       Mockito.doNothing().when(service).createApp(Mockito.any(AppRequest.class));
       service.createApp(request);
       Mockito.verify(service, Mockito.times(1)).createApp(request);

       RequestBuilder requestBuilder =  MockMvcRequestBuilders.post(URI)
                                                             .accept(MediaType.APPLICATION_JSON).content(inputInJson)
                                                             .contentType(MediaType.APPLICATION_JSON);

       MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
       MockHttpServletResponse response = mvcResult.getResponse();
       assertEquals(HttpStatus.OK.value(), response.getStatus());

   }

   @Test
   public void testUpdate() throws Exception {

       AppRequest request = new AppRequest();
       request.id = 1;
       request.modifiedBy = 1;
        request.AppFullName = “My App”;
       request.appTimezone = “Bharat”;

       String inputInJson = this.mapToJson(request);
       Mockito.doNothing().when(service).updateApp(Mockito.any(AppRequest.class));
       service.updateApp(request);
       Mockito.verify(service, Mockito.times(1)).updateApp(request);

       RequestBuilder requestBuilder =  MockMvcRequestBuilders.put(URI)
                                                             .accept(MediaType.APPLICATION_JSON).content(inputInJson)
                                                             .contentType(MediaType.APPLICATION_JSON);

       MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
       MockHttpServletResponse response = mvcResult.getResponse();
       assertEquals(HttpStatus.OK.value(), response.getStatus());

   }

   @Test
   public void testDelete() throws Exception {

       AppRequest request = new AppRequest();
       request.id = 1;

       String inputInJson = this.mapToJson(request);
       Mockito.doNothing().when(service).deleteApp(Mockito.any(Integer.class));
       service.deleteApp(request.id);
       Mockito.verify(service, Mockito.times(1)).deleteApp(request.id);

       RequestBuilder requestBuilder =  MockMvcRequestBuilders.delete(URI)
                                                             .accept(MediaType.APPLICATION_JSON).content(inputInJson)
                                                             .contentType(MediaType.APPLICATION_JSON);

       MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
       MockHttpServletResponse response = mvcResult.getResponse();
       assertEquals(HttpStatus.OK.value(), response.getStatus());

   }

}

How to copy files from host to Docker container?

If using Windows as host, you can use WinSCP to connect to Docker and transfer files through the GUI.

If on Linux, the scp command would also work through the terminal.

How to display length of filtered ng-repeat data

ngRepeat creates a copy of the array when it applies a filter, so you can't use the source array to reference only the filtered elements.

In your case, in may be better to apply the filter inside of your controller using the $filter service:

function MainCtrl( $scope, filterFilter ) {
  // ...

  $scope.filteredData = myNormalData;

  $scope.$watch( 'myInputModel', function ( val ) {
    $scope.filteredData = filterFilter( myNormalData, val );
  });

  // ...
}

And then you use the filteredData property in your view instead. Here is a working Plunker: http://plnkr.co/edit/7c1l24rPkuKPOS5o2qtx?p=preview

What is the best/safest way to reinstall Homebrew?

The way to reinstall Homebrew is completely remove it and start over. The Homebrew FAQ has a link to a shell script to uninstall homebrew.

If the only thing you've installed in /usr/local is homebrew itself, you can just rm -rf /usr/local/* /usr/local/.git to clear it out. But /usr/local/ is the standard Unix directory for all extra binaries, not just Homebrew, so you may have other things installed there. In that case uninstall_homebrew.sh is a better bet. It is careful to only remove homebrew's files and leave the rest alone.

Passing variable number of arguments around

Short answer

/// logs all messages below this level, level 0 turns off LOG 
#ifndef LOG_LEVEL
#define LOG_LEVEL 5  // 0:off, 1:error, 2:warning, 3: info, 4: debug, 5:verbose
#endif
#define _LOG_FORMAT_SHORT(letter, format) "[" #letter "]: " format "\n"

/// short log
#define log_s(level, format, ...)     \                                                                                  
    if (level <= LOG_LEVEL)            \                                                                                     
    printf(_LOG_FORMAT_SHORT(level, format), ##__VA_ARGS__)

usage

log_s(1, "fatal error occurred");
log_s(3, "x=%d and name=%s",2, "ali");

output

[1]: fatal error occurred
[3]: x=2 and name=ali

log with file and line number

const char* _getFileName(const char* path)
{
    size_t i = 0;
    size_t pos = 0;
    char* p = (char*)path;
    while (*p) {
        i++;
        if (*p == '/' || *p == '\\') {
            pos = i;
        }
        p++;
    }
    return path + pos;
}

#define _LOG_FORMAT(letter, format)      \                                                                        
    "[" #letter "][%s:%u] %s(): " format "\n", _getFileName(__FILE__), __LINE__, __FUNCTION__

#ifndef LOG_LEVEL
#define LOG_LEVEL 5 // 0:off, 1:error, 2:warning, 3: info, 4: debug, 5:verbose
#endif

/// long log
#define log_l(level, format, ...)     \                                                                               
    if (level <= LOG_LEVEL)            \                                                                                         
    printf(_LOG_FORMAT(level, format), ##__VA_ARGS__)

usage

log_s(1, "fatal error occurred");
log_s(3, "x=%d and name=%s",2, "ali");

output

[1][test.cpp:97] main(): fatal error occurred
[3][test.cpp:98] main(): x=2 and name=ali

custom print function

you can write custom print function and pass ... args to it and it is also possible to combine this with methods above. source from here

int print_custom(const char* format, ...)
{
    static char loc_buf[64];
    char* temp = loc_buf;
    int len;
    va_list arg;
    va_list copy;
    va_start(arg, format);
    va_copy(copy, arg);
    len = vsnprintf(NULL, 0, format, arg);
    va_end(copy);
    if (len >= sizeof(loc_buf)) {
        temp = (char*)malloc(len + 1);
        if (temp == NULL) {
            return 0;
        }
    }
    vsnprintf(temp, len + 1, format, arg);
    printf(temp); // replace with any print function you want
    va_end(arg);
    if (len >= sizeof(loc_buf)) {
        free(temp);
    }
    return len;
}

Fastest method to replace all instances of a character in a string

@Gumbo adding extra answer - user.email.replace(/foo/gi,"bar");

/foo/g - Refers to the all string to replace matching the case sensitive

/foo/gi - Refers to the without case sensitive and replace all For Eg: (Foo, foo, FoO, fOO)

DEMO

What's the best way to cancel event propagation between nested ng-click calls?

Sometimes, it may make most sense just to do this:

<widget ng-click="myClickHandler(); $event.stopPropagation()"/>

I chose to do it this way because I didn't want myClickHandler() to stop the event propagation in the many other places it was used.

Sure, I could've added a boolean parameter to the handler function, but stopPropagation() is much more meaningful than just true.

Understanding the order() function

To sort a 1D vector or a single column of data, just call the sort function and pass in your sequence.

On the other hand, the order function is necessary to sort data two-dimensional data--i.e., multiple columns of data collected in a matrix or dataframe.

Stadium Home Week Qtr Away Off Def Result       Kicker Dist
751     Out  PHI   14   4  NYG PHI NYG   Good      D.Akers   50
491     Out   KC    9   1  OAK OAK  KC   Good S.Janikowski   32
702     Out  OAK   15   4  CLE CLE OAK   Good     P.Dawson   37
571     Out   NE    1   2  OAK OAK  NE Missed S.Janikowski   43
654     Out  NYG   11   2  PHI NYG PHI   Good      J.Feely   26
307     Out  DEN   14   2  BAL DEN BAL   Good       J.Elam   48
492     Out   KC   13   3  DEN  KC DEN   Good      L.Tynes   34
691     Out  NYJ   17   3  BUF NYJ BUF   Good     M.Nugent   25
164     Out  CHI   13   2   GB CHI  GB   Good      R.Gould   25
80      Out  BAL    1   2  IND IND BAL   Good M.Vanderjagt   20

Here is an excerpt of data for field goal attempts in the 2008 NFL season, a dataframe i've called 'fg'. suppose that these 10 data points represent all of the field goals attempted in 2008; further suppose you want to know the the distance of the longest field goal attempted that year, who kicked it, and whether it was good or not; you also want to know the second-longest, as well as the third-longest, etc.; and finally you want the shortest field goal attempt.

Well, you could just do this:

sort(fg$Dist, decreasing=T)

which returns: 50 48 43 37 34 32 26 25 25 20

That is correct, but not very useful--it does tell us the distance of the longest field goal attempt, the second-longest,...as well as the shortest; however, but that's all we know--eg, we don't know who the kicker was, whether the attempt was successful, etc. Of course, we need the entire dataframe sorted on the "Dist" column (put another way, we want to sort all of the data rows on the single attribute Dist. that would look like this:

Stadium Home Week Qtr Away Off Def Result       Kicker Dist
751     Out  PHI   14   4  NYG PHI NYG   Good      D.Akers   50
307     Out  DEN   14   2  BAL DEN BAL   Good       J.Elam   48
571     Out   NE    1   2  OAK OAK  NE Missed S.Janikowski   43
702     Out  OAK   15   4  CLE CLE OAK   Good     P.Dawson   37
492     Out   KC   13   3  DEN  KC DEN   Good      L.Tynes   34
491     Out   KC    9   1  OAK OAK  KC   Good S.Janikowski   32
654     Out  NYG   11   2  PHI NYG PHI   Good      J.Feely   26
691     Out  NYJ   17   3  BUF NYJ BUF   Good     M.Nugent   25
164     Out  CHI   13   2   GB CHI  GB   Good      R.Gould   25
80      Out  BAL    1   2  IND IND BAL   Good M.Vanderjagt   20

This is what order does. It is 'sort' for two-dimensional data; put another way, it returns a 1D integer index comprised of the row numbers such that sorting the rows according to that vector, would give you a correct row-oriented sort on the column, Dist

Here's how it works. Above, sort was used to sort the Dist column; to sort the entire dataframe on the Dist column, we use 'order' exactly the same way as 'sort' is used above:

ndx = order(fg$Dist, decreasing=T)

(i usually bind the array returned from 'order' to the variable 'ndx', which stands for 'index', because i am going to use it as an index array to sort.)

that was step 1, here's step 2:

'ndx', what is returned by 'sort' is then used as an index array to re-order the dataframe, 'fg':

fg_sorted = fg[ndx,]

fg_sorted is the re-ordered dataframe immediately above.

In sum, 'sort' is used to create an index array (which specifies the sort order of the column you want sorted), which then is used as an index array to re-order the dataframe (or matrix).

m2e lifecycle-mapping not found

I was having the same issue, where:

No marketplace entries found to handle build-helper-maven-plugin:1.8:add-source in Eclipse. Please see Help for more information.

and clicking the Window > Preferences > Maven > Discovery > open catalog button would report no connection.

Updating from 7u40 to 7u45 on Centos 6.4 and OSX fixes the issue.

How to do select from where x is equal to multiple values?

You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:

SELECT ads.*, location.county 
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1 
AND ads.type = 13
AND ads.county_id IN (2,5,7,9)

PHP date yesterday

strtotime(), as in date("F j, Y", strtotime("yesterday"));

Remove the first character of a string

deleting a char:

def del_char(string, indexes):

    'deletes all the indexes from the string and returns the new one'

    return ''.join((char for idx, char in enumerate(string) if idx not in indexes))

it deletes all the chars that are in indexes; you can use it in your case with del_char(your_string, [0])

After installing with pip, "jupyter: command not found"

Anyone looking for running jupyter as sudo, when jupyter installed with virtualenv (without sudo) - this worked for me:

First verify this is a PATH issue:

Check if the path returned by which jupyter is covered by the sudo user:

sudo env | grep ^PATH

(As opposed to the current user: env | grep ^PATH)

If its not covered - add a soft link from it to one of the covered paths. For ex:

sudo ln -s /home/user/venv/bin/jupyter /usr/local/bin

Now you sould be able to run:

sudo jupyter notebook

Remove characters except digits from string using Python?

s=''.join(i for i in s if i.isdigit())

Another generator variant.

SQL - select distinct only on one column

A very typical approach to this type of problem is to use row_number():

select t.*
from (select t.*,
             row_number() over (partition by number order by id) as seqnum
      from t
     ) t
where seqnum = 1;

This is more generalizable than using a comparison to the minimum id. For instance, you can get a random row by using order by newid(). You can select 2 rows by using where seqnum <= 2.

An established connection was aborted by the software in your host machine

follow this two step 1) adb kill-server 2) adb start-server

this is work for me

How to echo xml file in php

This works:

<?php
$XML = "<?xml version='1.0' encoding='UTF-8'?>
<!-- Your XML -->
";

header('Content-Type: application/xml; charset=utf-8');
echo ($XML);
?>

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

The command build in pipeline is there to trigger other jobs in jenkins.

Example on github

The job must exist in Jenkins and can be parametrized. As for the branch, I guess you can read it from git

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

What does value & 0xff do in Java?

In 32 bit format system the hexadecimal value 0xff represents 00000000000000000000000011111111 that is 255(15*16^1+15*16^0) in decimal. and the bitwise & operator masks the same 8 right most bits as in first operand.

Importing .py files in Google Colab

We can do so.

import sys
import os

py_file_location = "/content/drive/My Drive"
sys.path.append(os.path.abspath(py_file_location))

Now you can import it as module in notebook for that location.

import whatever

How to remove the querystring and get only the url?

Assuming you still want to get the URL without the query args (if they are not set), just use a shorthand if statement to check with strpos:

$request_uri = strpos( $_SERVER['REQUEST_URI'], '?' ) !== false ? strtok( $_SERVER["REQUEST_URI"], '?' ) : $_SERVER['REQUEST_URI'];

How to clear cache of Eclipse Indigo

It's very simple. Right click inside the internal browser and click "refresh".

How to filter by string in JSONPath?

I didn't find find the correct jsonpath filter syntax to extract a value from a name-value pair in json.

Here's the syntax and an abbreviated sample twitter document below.

This site was useful for testing:

The jsonpath filter expression:

.events[0].attributes[?(@.name=='screen_name')].value

Test document:

{
  "title" : "test twitter",
  "priority" : 5,
  "events" : [ {
    "eventId" : "150d3939-1bc4-4bcb-8f88-6153053a2c3e",
    "eventDate" : "2015-03-27T09:07:48-0500",
    "publisher" : "twitter",
    "type" : "tweet",
    "attributes" : [ {
      "name" : "filter_level",
      "value" : "low"
    }, {
      "name" : "screen_name",
      "value" : "_ziadin"
    }, {
      "name" : "followers_count",
      "value" : "406"
    } ]
  } ]
}

Running SSH Agent when starting Git Bash on Windows

I wrote a script and created a git repository, which solves this issue here: https://github.com/Cazaimi/boot-github-shell-win .

The readme contains instructions on how to set the script up, so that each time you open a new window/tab the private key is added to ssh-agent automatically, and you don't have to worry about this, if you're working with remote git repositories.

When to use IMG vs. CSS background-image?

Also, i have a gallery section which has inconsistent picture sizes so even though those images are obviously considered content, I use background images and center them in divs with a set size. This is similar to what facebook does in their albums..

How to easily import multiple sql files into a MySQL database?

in windows open windows powershell and go to the folder where sql files are then run this command

cat *.sql |  C:\xampp\mysql\bin\mysql.exe -u username -p databasename

SQL Server: how to create a stored procedure

In T-SQL stored procedures for input parameters explicit 'in' keyword is not required and for output parameters an explicit 'Output' keyword is required. The query in question can be written as:

CREATE PROCEDURE dept_count 
    (
    -- Add input and output parameters for the stored procedure here
    @dept_name varchar(20), --Input parameter 
    @d_count int OUTPUT     -- Output parameter declared with the help of OUTPUT/OUT keyword
    ) 
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

     -- Statements for procedure here
    SELECT @d_count = count(*)
    from instructor
      where instructor.dept_name=@dept_name

END
GO

and to execute above procedure we can write as:

Declare @dept_name varchar(20), -- Declaring the variable to collect the dept_name
        @d_count int            -- Declaring the variable to collect the d_count 
SET @dept_name = 'Test'

Execute  dept_count @dept_name,@d_count output
SELECT   @d_count               -- "Select" Statement is used to show the output 

Reading JSON POST using PHP

You have empty $_POST. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.

You need something like that:

$json = file_get_contents('php://input');
$obj = json_decode($json);

Also you have wrong code for testing JSON-communication...

CURLOPT_POSTFIELDS tells curl to encode your parameters as application/x-www-form-urlencoded. You need JSON-string here.

UPDATE

Your php code for test page should be like that:

$data_string = json_encode($data);

$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);

Also on your web-service page you should remove one of the lines header('Content-type: application/json');. It must be called only once.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are the same. Numeric is functionally equivalent to decimal.

MSDN: decimal and numeric

Are 2 dimensional Lists possible in c#?

Here's a little something that I made a while ago for a game engine I was working on. It was used as a local object variable holder. Basically, you use it as a normal list, but it holds the value at the position of what ever the string name is(or ID). A bit of modification, and you will have your 2D list.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameEngineInterpreter
{
    public class VariableList<T>
    {
        private List<string> list1;
        private List<T> list2;

        /// <summary>
        /// Initialize a new Variable List
        /// </summary>
        public VariableList()
        {
            list1 = new List<string>();
            list2 = new List<T>();
        }

        /// <summary>
        /// Set the value of a variable. If the variable does not exist, then it is created
        /// </summary>
        /// <param name="variable">Name or ID of the variable</param>
        /// <param name="value">The value of the variable</param>
        public void Set(string variable, T value)
        {
            if (!list1.Contains(variable))
            {
                list1.Add(variable);
                list2.Add(value);
            }
            else
            {
                list2[list1.IndexOf(variable)] = value;
            }
        }

        /// <summary>
        /// Remove the variable if it exists
        /// </summary>
        /// <param name="variable">Name or ID of the variable</param>
        public void Remove(string variable)
        {
            if (list1.Contains(variable))
            {
                list2.RemoveAt(list1.IndexOf(variable));
                list1.RemoveAt(list1.IndexOf(variable));
            }
        }

        /// <summary>
        /// Clears the variable list
        /// </summary>
        public void Clear()
        {
            list1.Clear();
            list2.Clear();
        }

        /// <summary>
        /// Get the value of the variable if it exists
        /// </summary>
        /// <param name="variable">Name or ID of the variable</param>
        /// <returns>Value</returns>
        public T Get(string variable)
        {
            if (list1.Contains(variable))
            {
                return (list2[list1.IndexOf(variable)]);
            }
            else
            {
                return default(T);
            }
        }

        /// <summary>
        /// Get a string list of all the variables 
        /// </summary>
        /// <returns>List string</string></returns>
        public List<string> GetList()
        {
            return (list1);
        }
    }
}

list.clear() vs list = new ArrayList<Integer>();

It's hard to know without a benchmark, but if you have lots of items in your ArrayList and the average size is lower, it might be faster to make a new ArrayList.

http://www.docjar.com/html/api/java/util/ArrayList.java.html

public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

jquery get all input from specific form

_x000D_
_x000D_
$(document).on("submit","form",function(e){
        //e.preventDefault();
        $form = $(this);
        $i = 0;
        $("form input[required],form select[required]").each(function(){
            if ($(this).val().trim() == ''){
                $(this).css('border-color', 'red');
                $i++;
            }else{
                $(this).css('border-color', '');    
            }               
        })
        if($i != 0) e.preventDefault();
    });
    $(document).on("change","input[required]",function(e){
        if ($(this).val().trim() == '')
            $(this).css('border-color', 'red');
        else
            $(this).css('border-color', '');    
    });
    $(document).on("change","select[required]",function(e){
        if ($(this).val().trim() == '')
            $(this).css('border-color', 'red');
        else
            $(this).css('border-color', '');
    });
_x000D_
_x000D_
_x000D_

How to loop through each and every row, column and cells in a GridView and get its value

As it's said by "Tim Schmelter" this is the best way : just change in it's code the seconde loop ( GridView2.Columns[i].Count by row.Cells.Count ) so it looks seem's that:

foreach(GridViewRow row in GridView2.Rows)
{
    for(int i = 0; i < GridView2.Columns.Count; i++)
    {
        String header = GridView2.Columns[i].HeaderText;
        String cellText = row.Cells[i].Text;
    }
}

thank you.

How to declare a constant map in Golang?

As stated above to define a map as constant is not possible. But you can declare a global variable which is a struct that contains a map.

The Initialization would look like this:

var romanNumeralDict = struct {
    m map[int]string
}{m: map[int]string {
    1000: "M",
    900: "CM",
    //YOUR VALUES HERE
}}

func main() {
    d := 1000
    fmt.Printf("Value of Key (%d): %s", d, romanNumeralDict.m[1000])
}

What is FCM token in Firebase?

I have an update about "Firebase Cloud Messaging token" which I could get an information.

I really wanted to know about that change so just sent a mail to Support team. The Firebase Cloud Messaging token will get back to Server key soon again. There will be nothing to change. We can see Server key again after soon.

How to format numbers?

On browsers that support the ECMAScript® 2016 Internationalization API Specification (ECMA-402), you can use an Intl.NumberFormat instance:

var nf = Intl.NumberFormat();
var x = 42000000;
console.log(nf.format(x)); // 42,000,000 in many locales
                           // 42.000.000 in many other locales

_x000D_
_x000D_
if (typeof Intl === "undefined" || !Intl.NumberFormat) {_x000D_
  console.log("This browser doesn't support Intl.NumberFormat");_x000D_
} else {_x000D_
  var nf = Intl.NumberFormat();_x000D_
  var x = 42000000;_x000D_
  console.log(nf.format(x)); // 42,000,000 in many locales_x000D_
                             // 42.000.000 in many other locales_x000D_
}
_x000D_
_x000D_
_x000D_

Using a custom (ttf) font in CSS

You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/

Example:

@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"),
       local("HelveticaNeue-Bold"),
       url(MgOpenModernaBold.ttf);
  font-weight: bold;
}

See also: MDN @font-face

How do you clear the console screen in C?

In Windows I have made the mistake of using

system("clear")

but that is actually for Linux

The Windows type is

system("cls")

without #include conio.h

Service has zero application (non-infrastructure) endpoints

I just worked through this issue on my service. Here is the error I was receiving:

Service 'EmailSender.Wcf.EmailService' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.

Here are the two steps I used to fix it:

  1. Use the correct fully-qualified class name:

    <service behaviorConfiguration="DefaultBehavior" name="EmailSender.Wcf.EmailService">
    
  2. Enable an endpoint with mexHttpBinding, and most importantly, use the IMetadataExchange contract:

    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    

Is there a Social Security Number reserved for testing/examples?

I used this 457-55-5462 as testing SSN and it worked for me. I used it at paypal sandbox account. Hope it helps somebody

How should I remove all the leading spaces from a string? - swift

This String extension removes all whitespace from a string, not just trailing whitespace ...

 extension String {
    func replace(string:String, replacement:String) -> String {
        return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
    }

    func removeWhitespace() -> String {
        return self.replace(string: " ", replacement: "")
    }
  }

Example:

let string = "The quick brown dog jumps over the foxy lady."
let result = string.removeWhitespace() // Thequickbrowndogjumpsoverthefoxylady.

Text border using css (border around text)

Use multiple text shadows:

text-shadow: 2px 0 0 #fff, -2px 0 0 #fff, 0 2px 0 #fff, 0 -2px 0 #fff, 1px 1px #fff, -1px -1px 0 #fff, 1px -1px 0 #fff, -1px 1px 0 #fff;

enter image description here

_x000D_
_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  background: #222;_x000D_
  color: darkred;_x000D_
  }_x000D_
h1 {_x000D_
  text-shadow: 2px 0 0 #fff, -2px 0 0 #fff, 0 2px 0 #fff, 0 -2px 0 #fff, 1px 1px #fff, -1px -1px 0 #fff, 1px -1px 0 #fff, -1px 1px 0 #fff;_x000D_
}
_x000D_
<h1>test</h1>
_x000D_
_x000D_
_x000D_

Alternatively, you could use text stroke, which only works in webkit:

-webkit-text-stroke-width: 2px;
-webkit-text-stroke-color: #fff;

enter image description here

_x000D_
_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  background: #222;_x000D_
  color: darkred;_x000D_
  }_x000D_
h1 {_x000D_
  -webkit-text-stroke-width: 2px;_x000D_
-webkit-text-stroke-color: #fff;_x000D_
}
_x000D_
<h1>test</h1>
_x000D_
_x000D_
_x000D_

Also read more as CSS-Tricks.

Python - List of unique dictionaries

In python 3.6+ (what I've tested), just use:

import json

#Toy example, but will also work for your case 
myListOfDicts = [{'a':1,'b':2},{'a':1,'b':2},{'a':1,'b':3}]
#Start by sorting each dictionary by keys
myListOfDictsSorted = [sorted(d.items()) for d in myListOfDicts]

#Using json methods with set() to get unique dict
myListOfUniqueDicts = list(map(json.loads,set(map(json.dumps, myListOfDictsSorted))))

print(myListOfUniqueDicts)

Explanation: we're mapping the json.dumps to encode the dictionaries as json objects, which are immutable. set can then be used to produce an iterable of unique immutables. Finally, we convert back to our dictionary representation using json.loads. Note that initially, one must sort by keys to arrange the dictionaries in a unique form. This is valid for Python 3.6+ since dictionaries are ordered by default.

How can I edit a view using phpMyAdmin 3.2.4?

In your database table list it should show View in Type column. To edit View:

  1. Click on your View in table list
  2. Click on Structure tab
  3. Click on Edit View under Check All

enter image description here

Hope this help

update: in PHPMyAdmin 4.x, it doesn't show View in Type, but you can still recognize it:

  1. In Row column: It had zero Row
  2. In Action column: It had greyed empty button

Of course it may be just an empty table, but when you open the structure, you will know whether it's a table or a view.

How to get a enum value from string in C#?

baseKey choice;
if (Enum.TryParse("HKEY_LOCAL_MACHINE", out choice)) {
     uint value = (uint)choice;

     // `value` is what you're looking for

} else { /* error: the string was not an enum member */ }

Before .NET 4.5, you had to do the following, which is more error-prone and throws an exception when an invalid string is passed:

(uint)Enum.Parse(typeof(baseKey), "HKEY_LOCAL_MACHINE")

How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"

adb -d shell (or adb -e shell).

This command will help you in most of the cases, if you are too lazy to type the full ID.

From http://developer.android.com/tools/help/adb.html#commandsummary:

-d - Direct an adb command to the only attached USB device. Returns an error when more than one USB device is attached.

-e - Direct an adb command to the only running emulator. Returns an error when more than one emulator is running.

SQL: how to select a single id ("row") that meets multiple criteria from a single column

First way: JOIN:

get people with multiple countries:

SELECT u1.user_id 
FROM users u1
JOIN users u2
on u1.user_id  = u2.user_id 
AND u1.ancestry <> u2.ancestry

Get people from 2 specific countries:

SELECT u1.user_id 
FROM users u1
JOIN users u2
on u1.user_id  = u2.user_id 
WHERE u1.ancestry = 'Germany'
AND u2.ancestry = 'France'

For 3 countries... join three times. To only get the result(s) once, distinct.

Second way: GROUP BY

This will get users which have 3 lines (having...count) and then you specify which lines are permitted. Note that if you don't have a UNIQUE KEY on (user_id, ancestry), a user with 'id, england' that appears 3 times will also match... so it depends on your table structure and/or data.

SELECT user_id 
FROM users u1
WHERE ancestry = 'Germany'
OR ancestry = 'France'
OR ancestry = 'England'
GROUP BY user_id
HAVING count(DISTINCT ancestry) = 3

Clearing content of text file using php

file_put_contents("filelist.txt", "");

You can redirect by using the header() function to modify the Location header.

How to remove a branch locally?

you need switch into another branch and try the same.

git branch -d

Display an image with Python

In a much simpler way, you can do the same using

from PIL import Image

image = Image.open('image.jpg')
image.show()

Escape single quote character for use in an SQLite query

In C# you can use the following to replace the single quote with a double quote:

 string sample = "St. Mary's";
 string escapedSample = sample.Replace("'", "''");

And the output will be:

"St. Mary''s"

And, if you are working with Sqlite directly; you can work with object instead of string and catch special things like DBNull:

private static string MySqlEscape(Object usString)
{
    if (usString is DBNull)
    {
        return "";
    }
    string sample = Convert.ToString(usString);
    return sample.Replace("'", "''");
}

How to get text with Selenium WebDriver in Python

I've found this absolutely invaluable when unable to grab something in a custom class or changing id's:

driver.find_element_by_xpath("//*[contains(text(), 'Show Next Date Available')]").click()
driver.find_element_by_xpath("//*[contains(text(), 'Show Next Date Available')]").text
driver.find_element_by_xpath("//*[contains(text(), 'Available')]").text
driver.find_element_by_xpath("//*[contains(text(), 'Avail')]").text

Is it possible to get all arguments of a function as single object inside that function?

Use arguments. You can access it like an array. Use arguments.length for the number of arguments.

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

ngOnInit() is called after ngOnChanges() was called the first time. ngOnChanges() is called every time inputs are updated by change detection.

ngAfterViewInit() is called after the view is initially rendered. This is why @ViewChild() depends on it. You can't access view members before they are rendered.

convert json ipython notebook(.ipynb) to .py file

well first of all you need to install this packege below:

sudo apt install ipython
jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb

two option is avaliable either --to python or --to=python mine was like this works fine: jupyter nbconvert --to python while.ipynb

jupyter nbconvert --to python while.ipynb 

[NbConvertApp] Converting notebook while.ipynb to python [NbConvertApp] Writing 758 bytes to while.py

pip3 install ipython

if it does not work for you try, by pip3.

pip3 install ipython

Print string to text file

In case you want to pass multiple arguments you can use a tuple

price = 33.3
with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))

More: Print multiple arguments in python

Arduino error: does not name a type?

The only thing you have to do is adding this line to your sketch

#include <SPI.h>

before #include <Adafruit_MAX31855.h>.

Removing all script tags from html with JS Regular Expression

You can try

$("your_div_id").remove();  

or

 $("your_div_id").html("");