Programs & Examples On #Cancellation

How to cancel an $http request in AngularJS?

This enhances the accepted answer by decorating the $http service with an abort method as follows ...

'use strict';
angular.module('admin')
  .config(["$provide", function ($provide) {

$provide.decorator('$http', ["$delegate", "$q", function ($delegate, $q) {
  var getFn = $delegate.get;
  var cancelerMap = {};

  function getCancelerKey(method, url) {
    var formattedMethod = method.toLowerCase();
    var formattedUrl = encodeURI(url).toLowerCase().split("?")[0];
    return formattedMethod + "~" + formattedUrl;
  }

  $delegate.get = function () {
    var cancelerKey, canceler, method;
    var args = [].slice.call(arguments);
    var url = args[0];
    var config = args[1] || {};
    if (config.timeout == null) {
      method = "GET";
      cancelerKey = getCancelerKey(method, url);
      canceler = $q.defer();
      cancelerMap[cancelerKey] = canceler;
      config.timeout = canceler.promise;
      args[1] = config;
    }
    return getFn.apply(null, args);
  };

  $delegate.abort = function (request) {
    console.log("aborting");
    var cancelerKey, canceler;
    cancelerKey = getCancelerKey(request.method, request.url);
    canceler = cancelerMap[cancelerKey];

    if (canceler != null) {
      console.log("aborting", cancelerKey);

      if (request.timeout != null && typeof request.timeout !== "number") {

        canceler.resolve();
        delete cancelerMap[cancelerKey];
      }
    }
  };

  return $delegate;
}]);
  }]);

WHAT IS THIS CODE DOING?

To cancel a request a "promise" timeout must be set. If no timeout is set on the HTTP request then the code adds a "promise" timeout. (If a timeout is set already then nothing is changed).

However, to resolve the promise we need a handle on the "deferred". We thus use a map so we can retrieve the "deferred" later. When we call the abort method, the "deferred" is retrieved from the map and then we call the resolve method to cancel the http request.

Hope this helps someone.

LIMITATIONS

Currently this only works for $http.get but you can add code for $http.post and so on

HOW TO USE ...

You can then use it, for example, on state change, as follows ...

rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
  angular.forEach($http.pendingRequests, function (request) {
        $http.abort(request);
    });
  });

Cancel a vanilla ECMAScript 6 Promise chain

I'm really surprised that no-one mentions Promise.race as a candidate for this:

const actualPromise = new Promise((resolve, reject) => { setTimeout(resolve, 10000) });
let cancel;
const cancelPromise = new Promise((resolve, reject) => {
    cancel = reject.bind(null, { canceled: true })
})

const cancelablePromise = Object.assign(Promise.race([actualPromise, cancelPromise]), { cancel });

Python pandas: fill a dataframe row by row

If your input rows are lists rather than dictionaries, then the following is a simple solution:

import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])

pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
#    A  B  C
# 0  1  2  3
# 1  4  5  6

How to stop a JavaScript for loop?

To stop a for loop early in JavaScript, you use break:

var remSize = [], 
    szString,
    remData,
    remIndex,
    i;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {      
     // I'm looking for the index i, when the condition is true
     if (remSize[i].size === remData.size) {
          remIndex = i;
          break;       // <=== breaks out of the loop early
     }
}

If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array#findIndex (to find the entry's index) or Array#find (to find the entry itself), both of which can be shimmed/polyfilled:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = remSize.findIndex(function(entry) {
     return entry.size === remData.size;
});

Array#find:

var remSize = [], 
    szString,
    remData,
    remEntry;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remEntry = remSize.find(function(entry) {
     return entry.size === remData.size;
});

Array#findIndex stops the first time the callback returns a truthy value, returning the index for that call to the callback; it returns -1 if the callback never returns a truthy value. Array#find also stops when it finds what you're looking for, but it returns the entry, not its index (or undefined if the callback never returns a truthy value).

If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some function on arrays, which calls a callback until the callback returns a truthy value:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
    if (entry.size === remData.size) {
        remIndex = index;
        return true; // <== Equivalent of break for `Array#some`
    }
});

If you're using jQuery, you can use jQuery.each to loop through an array; that would look like this:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
    if (entry.size === remData.size) {
        remIndex = index;
        return false; // <== Equivalent of break for jQuery.each
    }
});

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

You are encoding to UTF-8, then re-encoding to UTF-8. Python can only do this if it first decodes again to Unicode, but it has to use the default ASCII codec:

>>> u'ñ'
u'\xf1'
>>> u'ñ'.encode('utf8')
'\xc3\xb1'
>>> u'ñ'.encode('utf8').encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Don't keep encoding; leave encoding to UTF-8 to the last possible moment instead. Concatenate Unicode values instead.

You can use str.join() (or, rather, unicode.join()) here to concatenate the three values with dashes in between:

nombre = u'-'.join(fabrica, sector, unidad)
return nombre.encode('utf-8')

but even encoding here might be too early.

Rule of thumb: decode the moment you receive the value (if not Unicode values supplied by an API already), encode only when you have to (if the destination API does not handle Unicode values directly).

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

Java String to JSON conversion

The name is present inside the data. You need to parse a JSON hierarchically to be able to fetch the data properly.

JSONObject jObject  = new JSONObject(output); // json
JSONObject data = jObject.getJSONObject("data"); // get data object
String projectname = data.getString("name"); // get the name from data.

Note: This example uses the org.json.JSONObject class and not org.json.simple.JSONObject.


As "Matthew" mentioned in the comments that he is using org.json.simple.JSONObject, I'm adding my comment details in the answer.

Try to use the org.json.JSONObject instead. But then if you can't change your JSON library, you can refer to this example which uses the same library as yours and check the how to read a json part from it.

Sample from the link provided:

JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");

Excel "External table is not in the expected format."

the file might be locked by another process, you need to copy it then load it as it says in this post

How to properly exit a C# application?

Environment.Exit(exitCode); //exit code 0 is a proper exit and 1 is an error

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

In SQL Developer ..Go to Preferences-->NLS-->and change your date format accordingly

Curl command line for consuming webServices?

Wrong. That doesn't work for me.

For me this one works:

curl 
-H 'SOAPACTION: "urn:samsung.com:service:MainTVAgent2:1#CheckPIN"'   
-X POST 
-H 'Content-type: text/xml'   
-d @/tmp/pinrequest.xml 
192.168.1.5:52235/MainTVServer2/control/MainTVAgent2

Xcode 6 Bug: Unknown class in Interface Builder file

For me, I'm using Xcode7 + Swift2

Solved this problem by checking my code, I have this line in my viewController:

 self?.navigationController?.pushViewController(vc, animated: true)

Then I realized that I haven't get navigationController connected to the detail page. So if you're pushing a new ViewController with customized ID, better to check that.

Android: remove notification from notification bar

A short one Liner of this is:

NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)

Or to cancel all notifications is:

NotificationManagerCompat.from(context).cancelAll()

Made for AndroidX or Support Libraries.

How to read multiple text files into a single RDD?

you can use

JavaRDD<String , String> records = sc.wholeTextFiles("path of your directory")

here you will get the path of your file and content of that file. so you can perform any action of a whole file at a time that saves the overhead

Visual Studio debugging/loading very slow

For me it was that I was debugging in Managed Compatibility Mode. In Tools -> Options -> Debugging -> General at the bottom, un-check 'Use Managed Compatibility Mode'. Debugging became instantaneous where it used to take up to a minute to step through one line. I suspect that's what the 'Managed' means in OP's snippets above.

More on that here: https://blogs.msdn.microsoft.com/visualstudioalm/2013/10/16/switching-to-managed-compatibility-mode-in-visual-studio-2013/

Using iFrames In ASP.NET

How about:

<asp:HtmlIframe ID="yourIframe" runat="server" />

Is supported since .Net Framework 4.5

If you have Problems using this control, you might take a look here.

HttpContext.Current.Request.Url.Host what it returns?

The Host property will return the domain name you used when accessing the site. So, in your development environment, since you're requesting

http://localhost:950/m/pages/Searchresults.aspx?search=knife&filter=kitchen

It's returning localhost. You can break apart your URL like so:

Protocol: http
Host: localhost
Port: 950
PathAndQuery: /m/pages/SearchResults.aspx?search=knight&filter=kitchen

Python syntax for "if a or b or c but not all of them"

What about: (unique condition)

if (bool(a) + bool(b) + bool(c) == 1):

Notice, if you allow two conditions too you could do that

if (bool(a) + bool(b) + bool(c) in [1,2]):

How to unzip a file in Powershell?

Use Expand-Archive cmdlet with one of parameter set:

Expand-Archive -LiteralPath C:\source\file.Zip -DestinationPath C:\destination
Expand-Archive -Path file.Zip -DestinationPath C:\destination

How do I add a ToolTip to a control?

ToolTip in C# is very easy to add to almost all UI controls. You don't need to add any MouseHover event for this.

This is how to do it-

  1. Add a ToolTip object to your form. One object is enough for the entire form. ToolTip toolTip = new ToolTip();

  2. Add the control to the tooltip with the desired text.

    toolTip.SetToolTip(Button1,"Click here");

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

C# string does not contain possible?

You should put all your words into some kind of Collection or List and then call it like this:

var searchFor = new List<string>();
searchFor.Add("pineapple");
searchFor.Add("mango");

bool containsAnySearchString = searchFor.Any(word => compareString.Contains(word));

If you need to make a case or culture independent search you should call it like this:

bool containsAnySearchString = 
   searchFor.Any(word => compareString.IndexOf
     (word, StringComparison.InvariantCultureIgnoreCase >= 0);

Git: can't undo local changes (error: path ... is unmerged)

You did it the wrong way around. You are meant to reset first, to unstage the file, then checkout, to revert local changes.

Try this:

$ git reset foo/bar.txt
$ git checkout foo/bar.txt

AngularJS open modal on button click

You should take a look at Batarang for AngularJS debugging

As for your issue:

Your scope variable is not directly attached to the modal correctly. Below is the adjusted code. You need to specify when the modal shows using ng-show

<!-- Confirmation Dialog -->
<div class="modal" modal="showModal" ng-show="showModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Delete confirmation</h4>
      </div>
      <div class="modal-body">
        <p>Are you sure?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="cancel()">No</button>
        <button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
      </div>
    </div>
  </div>
</div>
<!-- End of Confirmation Dialog -->

How to generate XML file dynamically using PHP?

To create an XMLdocument in PHP you should instance a DOMDocument class, create child nodes and append these nodes in the correct branch of the document tree.

For reference you can read http://it.php.net/manual/en/book.dom.php

Now we will take a quick tour of the code below.

  • at line 2 we create an empty xml document (just specify xml version (1.0) and encoding (utf8))
  • now we need to populate the xml tree:
    • We have to create an xmlnode (line 5)
    • and we have to append this in the correct position. We are creating the root so we append this directly to the domdocument.
    • Note create element append the element to the node and return the node inserted, we save this reference to append the track nodes to the root node (incidentally called xml).

These are the basics, you can create and append a node in just a line (13th, for example), you can do a lot of other things with the dom api. It is up to you.

<?php    
    /* create a dom document with encoding utf8 */
    $domtree = new DOMDocument('1.0', 'UTF-8');

    /* create the root element of the xml tree */
    $xmlRoot = $domtree->createElement("xml");
    /* append it to the document created */
    $xmlRoot = $domtree->appendChild($xmlRoot);

    $currentTrack = $domtree->createElement("track");
    $currentTrack = $xmlRoot->appendChild($currentTrack);

    /* you should enclose the following two lines in a cicle */
    $currentTrack->appendChild($domtree->createElement('path','song1.mp3'));
    $currentTrack->appendChild($domtree->createElement('title','title of song1.mp3'));

    $currentTrack->appendChild($domtree->createElement('path','song2.mp3'));
    $currentTrack->appendChild($domtree->createElement('title','title of song2.mp3'));

    /* get the xml printed */
    echo $domtree->saveXML();
?>

Edit: Just one other hint: The main advantage of using an xmldocument (the dom document one or the simplexml one) instead of printing the xml,is that the xmltree is searchable with xpath query

How to bind 'touchstart' and 'click' events but not respond to both?

Just adding return false; at the end of the on("click touchstart") event function can solve this problem.

$(this).on("click touchstart", function() {
  // Do things
  return false;
});

From the jQuery documentation on .on()

Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault(). A false value can also be passed for the handler as a shorthand for function(){ return false; }.

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

The solution is definitely "spring-security-config" not in your WEB-INF/lib.

For my project in Eclipse using Maven, it turned out not all of the maven dependencies were being copied to WEB-INF/lib. Looking at Project -> Properties -> Deployment Assembly, only some of the jars were being copied.

To fix this, I clicked "Add", then "Java Build Path Entires" and finally "Maven Dependencies".

I have been searching SO and the web for the last hour looking for this, so hopefully this helps someone else.

Signed versus Unsigned Integers

Just a few points for completeness:

  • this answer is discussing only integer representations. There may be other answers for floating point;

  • the representation of a negative number can vary. The most common (by far - it's nearly universal today) in use today is two's complement. Other representations include one's complement (quite rare) and signed magnitude (vanishingly rare - probably only used on museum pieces) which is simply using the high bit as a sign indicator with the remain bits representing the absolute value of the number.

  • When using two's complement, the variable can represent a larger range (by one) of negative numbers than positive numbers. This is because zero is included in the 'positive' numbers (since the sign bit is not set for zero), but not the negative numbers. This means that the absolute value of the smallest negative number cannot be represented.

  • when using one's complement or signed magnitude you can have zero represented as either a positive or negative number (which is one of a couple of reasons these representations aren't typically used).

Python SQLite: database is locked

I also had this problem. I was trying to enter data into the database without saving changes I had made in it. after i saved the changes worked

Expected block end YAML error

I would like to make this answer for meaningful, so the same kind of erroneous user can enjoy without feel any hassle.

Actually, i was getting the same error but for the different reason, in my case I didn't used any kind of quoted, still getting the same error like expected <block end>, but found BlockMappingStart.

I have solved it by fixing, the Alignment issue inside the same .yml file.

If we don't manage the proper 'tab-space(Keyboard key)' for maintaining successor or ancestor then we have to phase such kind of things.

Now i am doing well.

How to prevent scanf causing a buffer overflow in C?

In their book The Practice of Programming (which is well worth reading), Kernighan and Pike discuss this problem, and they solve it by using snprintf() to create the string with the correct buffer size for passing to the scanf() family of functions. In effect:

int scanner(const char *data, char *buffer, size_t buflen)
{
    char format[32];
    if (buflen == 0)
        return 0;
    snprintf(format, sizeof(format), "%%%ds", (int)(buflen-1));
    return sscanf(data, format, buffer);
}

Note, this still limits the input to the size provided as 'buffer'. If you need more space, then you have to do memory allocation, or use a non-standard library function that does the memory allocation for you.


Note that the POSIX 2008 (2013) version of the scanf() family of functions supports a format modifier m (an assignment-allocation character) for string inputs (%s, %c, %[). Instead of taking a char * argument, it takes a char ** argument, and it allocates the necessary space for the value it reads:

char *buffer = 0;
if (sscanf(data, "%ms", &buffer) == 1)
{
    printf("String is: <<%s>>\n", buffer);
    free(buffer);
}

If the sscanf() function fails to satisfy all the conversion specifications, then all the memory it allocated for %ms-like conversions is freed before the function returns.

Error handling in getJSON calls

I was faced with this same issue, but rather than creating callbacks for a failed request, I simply returned an error with the json data object.

If possible, this seems like the easiest solution. Here's a sample of the Python code I used. (Using Flask, Flask's jsonify f and SQLAlchemy)

try:
    snip = Snip.query.filter_by(user_id=current_user.get_id(), id=snip_id).first()
    db.session.delete(snip)
    db.session.commit()
    return jsonify(success=True)
except Exception, e:
    logging.debug(e)
    return jsonify(error="Sorry, we couldn't delete that clip.")

Then you can check on Javascript like this;

$.getJSON('/ajax/deleteSnip/' + data_id,
    function(data){
    console.log(data);
    if (data.success === true) {
       console.log("successfully deleted snip");
       $('.snippet[data-id="' + data_id + '"]').slideUp();
    }
    else {
       //only shows if the data object was returned
    }
});

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

I thought my issue was due to my machine.config per answers I found online but the culprit turned out to be in the project's web.config that was clearing out the DbProviderFactories.

<system.data>
  <DbProviderFactories>
    <clear />
       ...
  </DbProviderFactories>
</system.data>

Select Specific Columns from Spark DataFrame

If you want to split you dataframe into two different ones, do two selects on it with the different columns you want.

 val sourceDf = spark.read.csv(...)
 val df1 = sourceDF.select("first column", "second column", "third column")
 val df2 = sourceDF.select("first column", "second column", "third column")

Note that this of course means that the sourceDf would be evaluated twice, so if it can fit into distributed memory and you use most of the columns across both dataframes it might be a good idea to cache it. It it has many extra columns that you don't need, then you can do a select on it first to select on the columns you will need so it would store all that extra data in memory.

Inserting a string into a list without getting split into characters

Another option is using the overloaded + operator:

>>> l = ['hello','world']
>>> l = ['foo'] + l
>>> l
['foo', 'hello', 'world']

How to stop/terminate a python script from running?

To stop a running program, use Ctrl+C to terminate the process.

To handle it programmatically in python, import the sys module and use sys.exit() where you want to terminate the program.

import sys
sys.exit()

MySQL select all rows from last month until (now() - 1 month), for comparative purposes

Simple code please check

SELECT * FROM table_name WHERE created <= (NOW() - INTERVAL 1 MONTH)

What is the difference between const and readonly in C#?

Here's another link demonstrating how const isn't version safe, or relevant for reference types.

Summary:

  • The value of your const property is set at compile time and can't change at runtime
  • Const can't be marked as static - the keyword denotes they are static, unlike readonly fields which can.
  • Const can't be anything except value (primitive) types
  • The readonly keyword marks the field as unchangeable. However the property can be changed inside the constructor of the class
  • The readonly only keyword can also be combined with static to make it act in the same way as a const (atleast on the surface). There is a marked difference when you look at the IL between the two
  • const fields are marked as "literal" in IL while readonly is "initonly"

How to loop through file names returned by find?

find <path> -xdev -type f -name *.txt -exec ls -l {} \;

This will list the files and give details about attributes.

How can a windows service programmatically restart itself?

I don't think it can. When a service is "stopped", it gets totally unloaded.

Well, OK, there's always a way I suppose. For instance, you could create a detached process to stop the service, then restart it, then exit.

How can I clear the Scanner buffer in Java?

You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.

Multiple Buttons' OnClickListener() android

You could set the property:

android:onClick="buttonClicked"

in the xml file for each of those buttons, and use this in the java code:

public void buttonClicked(View view) {

    if (view.getId() == R.id.button1) {
        // button1 action
    } else if (view.getId() == R.id.button2) {
        //button2 action
    } else if (view.getId() == R.id.button3) {
        //button3 action
    }

}

Checking if an object is a given type in Swift

If you don't know that you will get an array of dictionaries or single dictionary in the response from server you need to check whether the result contains an array or not.
In my case always receiving an array of dictionaries except once. So, to handle that I used the below code for swift 3.

if let str = strDict["item"] as? Array<Any>

Here as? Array checks whether the obtained value is array (of dictionary items). In else case you can handle if it is single dictionary item which is not kept inside an array.

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

How to reset AUTO_INCREMENT in MySQL?

The best solution that worked for me:

ALTER TABLE my_table MODIFY COLUMN ID INT(10) UNSIGNED;
COMMIT;
ALTER TABLE my_table MODIFY COLUMN ID INT(10) UNSIGNED AUTO_INCREMENT;
COMMIT;

Its fast, works with innoDB, and I don't need to know the current maximum value! This way the auto increment counter will reset and it will start automatically from the maximum value exists.

Detecting installed programs via registry

Seems like looking for something specific to the installed program would work better, but HKCU\Software and HKLM\Software are the spots to look.

How to install plugin for Eclipse from .zip

It depends on what the zip contains. Take a look to see if it got content.jar and artifacts.jar. If it does, it is an archived updated site. Install from it the same way as you install from a remote site.

If the zip doesn't contain content.jar and artifacts.jar, go to your Eclipse install's dropins directory, create a subfolder (name doesn't matter) and expand your zip into that folder. Restart Eclipse.

Linear regression with matplotlib / numpy

from pylab import * 

import numpy as np
x1 = arange(data) #for example this is a list
y1 = arange(data) #for example this is a list 
x=np.array(x) #this will convert a list in to an array
y=np.array(y)
m,b = polyfit(x, y, 1) 

plot(x, y, 'yo', x, m*x+b, '--k') 
show()

Get top n records for each group of grouped results

Try this:

SELECT a.person, a.group, a.age FROM person AS a WHERE 
(SELECT COUNT(*) FROM person AS b 
WHERE b.group = a.group AND b.age >= a.age) <= 2 
ORDER BY a.group ASC, a.age DESC

DEMO

Parse strings to double with comma and point

Use this overload of double.TryParse to specify allowed formats:

Double.TryParse Method (String, NumberStyles, IFormatProvider, Double%)

By default, double.TryParse will parse based on current culture specific formats.

Display fullscreen mode on Tkinter

This creates a fullscreen window. Pressing Escape resizes the window to '200x200+0+0' by default. If you move or resize the window, Escape toggles between the current geometry and the previous geometry.

import Tkinter as tk

class FullScreenApp(object):
    def __init__(self, master, **kwargs):
        self.master=master
        pad=3
        self._geom='200x200+0+0'
        master.geometry("{0}x{1}+0+0".format(
            master.winfo_screenwidth()-pad, master.winfo_screenheight()-pad))
        master.bind('<Escape>',self.toggle_geom)            
    def toggle_geom(self,event):
        geom=self.master.winfo_geometry()
        print(geom,self._geom)
        self.master.geometry(self._geom)
        self._geom=geom

root=tk.Tk()
app=FullScreenApp(root)
root.mainloop()

How do I protect javascript files?

Just off the top of my head, you could do something like this (if you can create server-side scripts, which it sounds like you can):

Instead of loading the script like normal, send an AJAX request to a PHP page (it could be anything; I just use it myself). Have the PHP locate the file (maybe on a non-public part of the server), open it with file_get_contents, and return (read: echo) the contents as a string.

When this string returns to the JavaScript, have it create a new script tag, populate its innerHTML with the code you just received, and attach the tag to the page. (You might have trouble with this; innerHTML may not be what you need, but you can experiment.)

If you do this a lot, you might even want to set up a PHP page that accepts a GET variable with the script's name, so that you can dynamically grab different scripts using the same PHP. (Maybe you could use POST instead, to make it just a little harder for other people to see what you're doing. I don't know.)

EDIT: I thought you were only trying to hide the location of the script. This obviously wouldn't help much if you're trying to hide the script itself.

Where can I find the error logs of nginx, using FastCGI and Django?

It is a good practice to set where the access log should be in nginx configuring file . Using acces_log /path/ Like this.

keyval $remote_addr:$http_user_agent $seen zone=clients;

server { listen 443 ssl;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers   HIGH:!aNULL:!MD5;

if ($seen = "") {
    set $seen  1;
    set $logme 1;
}
access_log  /tmp/sslparams.log sslparams if=$logme;
error_log  /pathtolog/error.log;
# ...
}

Setting selection to Nothing when programming Excel

Do statement as below:

ActiveSheet.Cells(ActiveWindow.SplitRow+1,ActiveWindow.SplitColumn+1).Select

adb command not found

In my case with Android Studio 1.1.0 path was this

/Users/wzbozon/Library/Android/sdk/platform-tools

Add the following to ~/.bash_profile

export PATH=~/Library/Android/sdk/tools:$PATH
export PATH=~/Library/Android/sdk/platform-tools:$PATH

What is the difference between npm install and npm run build?

NPM in 2019

npm build no longer exists. You must call npm run build now. More info below.

TLDR;

npm install: installs dependencies, then calls the install from the package.json scripts field.

npm run build: runs the build field from the package.json scripts field.


NPM Scripts Field

https://docs.npmjs.com/misc/scripts

There are many things you can put into the npm package.json scripts field. Check out the documentation link above more above the lifecycle of the scripts - most have pre and post hooks that you can run scripts before/after install, publish, uninstall, test, start, stop, shrinkwrap, version.


To Complicate Things

  • npm install is not the same as npm run install
  • npm install installs package.json dependencies, then runs the package.json scripts.install
    • (Essentially calls npm run install after dependencies are installed.
  • npm run install only runs the package.json scripts.install, it will not install dependencies.
  • npm build used to be a valid command (used to be the same as npm run build) but it no longer is; it is now an internal command. If you run it you'll get: npm WARN build npm build called with no arguments. Did you mean to npm run-script build? You can read more on the documentation: https://docs.npmjs.com/cli/build

Extra Notes

There are still two top level commands that will run scripts, they are:

  • npm start which is the same as npm run start
  • npm test ==> npm run test

Border Radius of Table is not working

To use border radius I have a border radius of 20px in the table, and then put the border radius on the first child of the table header (th) and the last child of the table header.

table {
  border-collapse: collapse;
  border-radius:20px;
  padding: 10px;
}

table th:first-child {
  /* border-radius = top left, top right, bottom right, bottom left */
    border-radius: 20px 0 0 0; /* curves the top left */
    padding-left: 15px;
}

table th:last-child {
    border-radius: 0 20px 0 0; /* curves the top right */
}

This however will not work if this is done with table data (td) because it will add a curve onto each table row. This is not a problem if you only have 2 rows in your table but any additional ones will add curves onto the inner rows too. You only want these curves on the outside of the table. So for this, add an id to your last row. Then you can apply the curves to them.

/* curves the first tableData in the last row */

#lastRow td:first-child {
    border-radius: 0 0 0 20px; /* bottom left curve */
}

/* curves the last tableData in the last row */

#lastRow td:last-child {
    border-radius: 0 0 20px 0; /* bottom right curve */
}

Importing PNG files into Numpy?

According to the doc, scipy.misc.imread is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread instead.

Example:

import imageio

im = imageio.imread('my_image.png')
print(im.shape)

You can also use imageio to load from fancy sources:

im = imageio.imread('http://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png')

Edit:

To load all of the *.png files in a specific folder, you could use the glob package:

import imageio
import glob

for im_path in glob.glob("path/to/folder/*.png"):
     im = imageio.imread(im_path)
     print(im.shape)
     # do whatever with the image here

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

There is a bug in Chrome (not in Safari at the time we checked) that gives unexpected results in Javascript's various width and height measurements when opening tabs in the background (bug details here) - we logged the bug in June and it's remained unresolved since.

It's possible you've encountered the bug in what you're attempting to do.

List of zeros in python

The easiest way to create a list where all values are the same is multiplying a one-element list by n.

>>> [0] * 4
[0, 0, 0, 0]

So for your loop:

for i in range(10):
    print [0] * i

Basic example for sharing text or image with UIActivityViewController in Swift

You may use the following functions which I wrote in one of my helper class in a project.

just call

showShareActivity(msg:"message", image: nil, url: nil, sourceRect: nil) 

and it will work for both iPhone and iPad. If you pass any view's CGRect value by sourceRect it will also shows a little arrow in iPad.

func topViewController()-> UIViewController{
    var topViewController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!

    while ((topViewController.presentedViewController) != nil) {
        topViewController = topViewController.presentedViewController!;
    }

    return topViewController
}

func showShareActivity(msg:String?, image:UIImage?, url:String?, sourceRect:CGRect?){
    var objectsToShare = [AnyObject]()

    if let url = url {
        objectsToShare = [url as AnyObject]
    }

    if let image = image {
        objectsToShare = [image as AnyObject]
    }

    if let msg = msg {
        objectsToShare = [msg as AnyObject]
    }

    let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
    activityVC.modalPresentationStyle = .popover
    activityVC.popoverPresentationController?.sourceView = topViewController().view
    if let sourceRect = sourceRect {
        activityVC.popoverPresentationController?.sourceRect = sourceRect
    }

    topViewController().present(activityVC, animated: true, completion: nil)
}

xcode-select active developer directory error

There are only two steps required, and the full XCode.app is not required at all:

sudo rm -rf /Library/Developer/CommandLineTools
xcode-select --install

At this point the "Installing Softwre" dialog pops up:

enter image description here

That's it!

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

I had the same problem and solved it with the following code. I'm not sure how it will behave on a phone with hardware keyboard.

// TextEdit
final EditText textEdit = new EditText(this);

// Builder
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter text");
alert.setView(textEdit);

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        String text = textEdit.getText().toString();
        finish();
    }
});

alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        finish();
    }
});

// Dialog
AlertDialog dialog = alert.create();
dialog.setOnShowListener(new OnShowListener() {

    @Override
    public void onShow(DialogInterface dialog) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(textEdit, InputMethodManager.SHOW_IMPLICIT);
    }
});

dialog.show();

An invalid form control with name='' is not focusable

I came here to answer that I had triggered this issue myself based on NOT closing the </form> tag AND having multiple forms on the same page. The first form will extend to include seeking validation on form inputs from elsewhere. Because THOSE forms are hidden, they triggered the error.

so for instance:

<form method="POST" name='register' action="#handler">


<input type="email" name="email"/>
<input type="text" name="message" />
<input type="date" name="date" />

<form method="POST" name='register' action="#register">
<input type="text" name="userId" />
<input type="password" name="password" />
<input type="password" name="confirm" />

</form>

Triggers

An invalid form control with name='userId' is not focusable.

An invalid form control with name='password' is not focusable.

An invalid form control with name='confirm' is not focusable.

Reading images in python

For the better answer, you can use these lines of code. Here is the example maybe help you :

image = cv2.imread('/home/pictures/1.jpg')
plt.imshow(image)
plt.show()

In imread() you can pass the directory .so you can also use str() and + to combine dynamic directories and fixed directory like this:

path = '/home/pictures/'
for i in range(2) :
    image = cv2.imread(str(path)+'1.jpg')
    plt.imshow(image)
    plt.show()

Both are the same.

In HTML5, should the main navigation be inside or outside the <header> element?

It's a little unclear whether you're asking for opinions, eg. "it's common to do xxx" or an actual rule, so I'm going to lean in the direction of rules.

The examples you cite seem based upon the examples in the spec for the nav element. Remember that the spec keeps getting tweaked and the rules are sometimes convoluted, so I'd venture many people might tend to just do what's given rather than interpret. You're showing two separate examples with different behavior, so there's only so much you can read into it. Do either of those sites also have the opposing sub/nav situation, and if so how do they handle it?

Most importantly, though, there's nothing in the spec saying either is the way to do it. One of the goals with HTML5 was to be very clear[this for comparison] about semantics, requirements, etc. so the omission is worth noting. As far as I can see, the examples are independent of each other and equally valid within their own context of layout requirements, etc.

Having the nav's source position be conditional is kind of silly(another red flag). Just pick a method and go with it.

Assert that a WebElement is not present using Selenium WebDriver with java

Try this -

private boolean verifyElementAbsent(String locator) throws Exception {
    try {
        driver.findElement(By.xpath(locator));
        System.out.println("Element Present");
        return false;

    } catch (NoSuchElementException e) {
        System.out.println("Element absent");
        return true;
    }
}

Import Android volley to Android Studio

it also available on repository mavenCentral() ...

dependencies {
    // https://mvnrepository.com/artifact/com.android.volley/volley
    api "com.android.volley:volley:1.1.0'
}

Javascript dynamic array of strings

Just initialize an array and push the element on the array. It will automatic scale the array.

var a = [ ];

a.push('Some string'); console.log(a); // ['Some string'] 
a.push('another string'); console.log(a); // ['Some string', 'another string'] 
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']

How can I get the username of the logged-in user in Django?

request.user.get_username() will return a string of the users email.

request.user.username will return a method.

Code for download video from Youtube on Java, Android

METHOD 1 ( Recommanded )

Library YouTubeExtractor

Add into your gradle file

 allprojects {
        repositories {
            maven { url "https://jitpack.io" }
        }
    }

And dependencies

 compile 'com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'

Add this small code and you done. Demo HERE

public class MainActivity extends AppCompatActivity {

    private static final String YOUTUBE_ID = "ea4-5mrpGfE";

    private final YouTubeExtractor mExtractor = YouTubeExtractor.create();


    private Callback<YouTubeExtractionResult> mExtractionCallback = new Callback<YouTubeExtractionResult>() {
        @Override
        public void onResponse(Call<YouTubeExtractionResult> call, Response<YouTubeExtractionResult> response) {
            bindVideoResult(response.body());
        }

        @Override
        public void onFailure(Call<YouTubeExtractionResult> call, Throwable t) {
            onError(t);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


//        For android youtube extractor library  com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'
        mExtractor.extract(YOUTUBE_ID).enqueue(mExtractionCallback);

    }


    private void onError(Throwable t) {
        t.printStackTrace();
        Toast.makeText(MainActivity.this, "It failed to extract. So sad", Toast.LENGTH_SHORT).show();
    }


    private void bindVideoResult(YouTubeExtractionResult result) {

//        Here you can get download url link
        Log.d("OnSuccess", "Got a result with the best url: " + result.getBestAvailableQualityVideoUri());

        Toast.makeText(this, "result : " + result.getSd360VideoUri(), Toast.LENGTH_SHORT).show();
    }
}

You can get download link in bindVideoResult() method.

METHOD 2

Using this library android-youtubeExtractor

Add into gradle file

repositories {
    maven { url "https://jitpack.io" }
}

compile 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT'

Here is the code for getting download url.

       String youtubeLink = "http://youtube.com/watch?v=xxxx";

    YouTubeUriExtractor ytEx = new YouTubeUriExtractor(this) {
        @Override
        public void onUrisAvailable(String videoId, String videoTitle, SparseArray<YtFile> ytFiles) {
            if (ytFiles != null) {
                int itag = 22;
// Here you can get download url
                String downloadUrl = ytFiles.get(itag).getUrl();
            }
        }
    };

    ytEx.execute(youtubeLink);

How to parse a JSON object to a TypeScript Object

let employee = <Employee>JSON.parse(employeeString);

Remember: Strong typings is compile time only since javascript doesn't support it.

How to make grep only match if the entire line matches?

This is with HPUX, if the content of the files has space between words, use this:

egrep "[[:space:]]ABC\.log[[:space:]]" a.tmp

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

You can use date to get time and date of a day:

[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013

Also hwclock would do:

[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST  -0.516080 seconds

For customized output, you can either redirect the output of date to something like awk, or write your own program to do that.

Remember to put your own executable scripts/binary into your PATH (e.g. /usr/bin) to make it invokable anywhere.

GitHub authentication failing over https, returning wrong email address

I do not have an @github.com address

You don't have to: the @ is the separator between the username:password and the domain.
It is not an email address.

A full GitHub https url would be:

https://username:[email protected]/username/reponame.git

Without the password (which would then be asked on the command line), that would gave:

https://[email protected]/username/reponame.git

But again, [email protected] isn't an email address, just the first part of the credentials.

Make sure the case of your username and reponame is correct: it is case sensitive.

Note that you can store and encrypt your credentials in a .netrc.gpg (or _netrc.gpg on Windows) if you don't want to put said credentials in clear in the url.
See "Is there a way to skip password typing when using https://github".

How do I increase the RAM and set up host-only networking in Vagrant?

I could not get any of these answers to work. Here's what I ended up putting at the very top of my Vagrantfile, before the Vagrant::Config.run do block:

Vagrant.configure("2") do |config|
  config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--memory", "1024"]
  end
end

I noticed that the shortcut accessor style, "vb.memory = 1024", didn't seem to work.

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

Check if a value is in an array (C#)

Note: The question is about arrays of strings. The mentioned routines are not to be mixed with the .Contains method of single strings.

I would like to add an extending answer referring to different C# versions and because of two reasons:

  • The accepted answer requires Linq which is perfectly idiomatic C# while it does not come without costs, and is not available in C# 2.0 or below. When an array is involved, performance may matter, so there are situations where you want to stay with Array methods.

  • No answer directly attends to the question where it was asked also to put this in a function (As some answers are also mixing strings with arrays of strings, this is not completely unimportant).

Array.Exists() is a C#/.NET 2.0 method and needs no Linq. Searching in arrays is O(n). For even faster access use HashSet or similar collections.

Since .NET 3.5 there also exists a generic method Array<T>.Exists() :

public void PrinterSetup(string[] printer)
{
   if (Array.Exists(printer, x => x == "jupiter"))
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
   }
}

You could write an own extension method (C# 3.0 and above) to add the syntactic sugar to get the same/similar ".Contains" as for strings for all arrays without including Linq:

// Using the generic extension method below as requested.
public void PrinterSetup(string[] printer)
{
   if (printer.ArrayContains("jupiter"))
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
   }
}

public static bool ArrayContains<T>(this T[] thisArray, T searchElement)
{
   // If you want this to find "null" values, you could change the code here
   return Array.Exists<T>(thisArray, x => x.Equals(searchElement));
}

In this case this ArrayContains() method is used and not the Contains method of Linq.

The elsewhere mentioned .Contains methods refer to List<T>.Contains (since C# 2.0) or ArrayList.Contains (since C# 1.1), but not to arrays itself directly.

How to create CSV Excel file C#?

I've added

public void ExportToFile(string path, DataTable tabela)
{

     DataColumnCollection colunas = tabela.Columns;

     foreach (DataRow linha in tabela.Rows)
     {

           this.AddRow();

           foreach (DataColumn coluna in colunas)

           {

               this[coluna.ColumnName] = linha[coluna];

           }

      }
      this.ExportToFile(path);

}

Previous code does not work with old .NET versions. For 3.5 version of framework use this other version:

        public void ExportToFile(string path)
    {
        bool abort = false;
        bool exists = false;
        do
        {
            exists = File.Exists(path);
            if (!exists)
            {
                if( !Convert.ToBoolean( File.CreateText(path) ) )
                        abort = true;
            }
        } while (!exists || abort);

        if (!abort)
        {
            //File.OpenWrite(path);
            using (StreamWriter w = File.AppendText(path))
            {
                w.WriteLine("hello");
            }

        }

        //File.WriteAllText(path, Export());
    }

Print a div content using Jquery

I tried all the non-plugin approaches here, but all caused blank pages to print after the content, or had other problems. Here's my solution:

Html:

<body>
<div id="page-content">        
    <div id="printme">Content To Print</div>
    <div>Don't print this.</div>
</div>
<div id="hidden-print-div"></div>
</body>

Jquery:

    $(document).ready(function () {
        $("#hidden-print-div").html($("#printme").html());
    });

Css:

    #hidden-print-div {
        display: none;
    }

    @media print {
        #hidden-print-div {
            display: block;
        }

        #page-content {
            display: none;
        }
    }

Converting an object to a string

As firefox does not stringify some object as screen object ; if you want to have the same result such as : JSON.stringify(obj) :

function objToString (obj) {
    var tabjson=[];
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            tabjson.push('"'+p +'"'+ ':' + obj[p]);
        }
    }  tabjson.push()
    return '{'+tabjson.join(',')+'}';
}

Android: converting String to int

It's already a string? Remove the getText() call.

int myNum = 0;

try {
    myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
  // Handle parse error.
}

Split string with JavaScript

Like this:

var myString = "19 51 2.108997";
var stringParts = myString.split(" ");
var html = "<span>" + stringParts[0] + " " + stringParts[1] + "</span> <span>" + stringParts[2] + "</span";

Vertically aligning text next to a radio button

This will give dead on alignment

input[type="radio"] {
  margin-top: 1px;
  vertical-align: top;
}

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

Try this, instead of selecting your websete's Application Pool to DefaultAppPool, select ASP.NET v4.0

Select your website in IIS => Basic Settings => Application Pool => Select ASP.NET v4.0

and you will be good to go. Hope it helps :)

How can I remove 3 characters at the end of a string in php?

<?php echo substr($string, 0, strlen($string) - 3); ?>

How to set <Text> text to upper case in react native

@Cherniv Thanks for the answer

<Text style={{}}> {'Test'.toUpperCase()} </Text>

How to diff a commit with its parent?

Use git show $COMMIT. It'll show you the log message for the commit, and the diff of that particular commit.

NodeJs : TypeError: require(...) is not a function

For me, I got similar error when switched between branches - one used newer ("typescriptish") version of @google-cloud/datastore packages which returns object with Datastore constructor as one of properties of exported object and I switched to other branch for a task, an older datastore version was used there, which exports Datastore constructor "directly" as module.exports value. I got the error because node_modules still had newer modules used by branch I switched from.

How to get last 7 days data from current datetime to last 7 days in sql server

Try something like:

 SELECT id, NewsHeadline as news_headline, NewsText as news_text, state CreatedDate as created_on
 FROM News 
 WHERE CreatedDate >= DATEADD(day,-7, GETDATE())

Matplotlib-Animation "No MovieWriters Available"

Had the same problem under Linux. By default the animate.save method is using ffmpeg but it seems to be deprecated. https://askubuntu.com/questions/432542/is-ffmpeg-missing-from-the-official-repositories-in-14-04

Solution: Install some coder, like avconv or mencoder. Provide the alternative coder in the call:

ani.save('the_movie.mp4', writer = 'mencoder', fps=15)

How to get jQuery to wait until an effect is finished?

With jQuery 1.6 version you can use the .promise() method.

$(selector).fadeOut('slow');
$(selector).promise().done(function(){
    // will be called when all the animations on the queue finish
});

Java: How can I compile an entire directory structure of code ?

You have to know all the directories, or be able to use wildcard ..

javac dir1/*.java dir2/*.java dir3/dir4/*.java dir3/dir5/*.java dir6/*src/*.java

How to enable PHP's openssl extension to install Composer?

I faced the same problem, but when i was lokking for php.ini and php.exe i found php.exe at C:\UwAmp\bin\php\php-5.4.15 when php.ini at C:\UwAmp\bin\apache. I just copy php.ini at C:\UwAmp\bin\php\php-5.4.15 and Uncomment the line extension=php_openssl.dll and it fixed.

Regular expression for extracting tag attributes

I'd reconsider the strategy to use only a single regular expression. Sure it's a nice game to come up with one single regular expression that does it all. But in terms of maintainabilty you are about to shoot yourself in both feet.

SQL - Update multiple records in one query

INSERT INTO tablename
    (name, salary)
    VALUES 
        ('Bob', 1125),
        ('Jane', 1200),
        ('Frank', 1100),
        ('Susan', 1175),
        ('John', 1150)
        ON DUPLICATE KEY UPDATE salary = VALUES(salary);

In Powershell what is the idiomatic way of converting a string to an int?

A quick true/false test of whether it will cast to [int]

[bool]($var -as [int] -is [int])

Make a div into a link

This work for me:

<div onclick="location.href='page.html';"  style="cursor:pointer;">...</div>

How to break lines in PowerShell?

You can also just use:

Write-Host "";

Or, to put it in terms of your specific question:

$str = ""
foreach($line in $file){
  if($line -Match $review){ #Special condition
    $str += Write-Host ""
    $str += ANSWER #looking for ANSWER
  }
  #code.....
}

Single-threaded apartment - cannot instantiate ActiveX control

If you used [STAThread] to the main entry of your application and still get the error you may need to make a Thread-Safe call to the control... something like below. In my case with the same problem the following solution worked!

Private void YourFunc(..)
{
    if (this.InvokeRequired)
    {
        Invoke(new MethodInvoker(delegate()
        {
           // Call your method YourFunc(..);
        }));
    }
    else
    {
        ///
    }

Execute a shell script in current shell with sudo permission

Even the first answer is absolutely brilliant, you probably want to only run script under sudo.

You have to specify the absolute path like:

sudo /home/user/example.sh
sudo ~/example.sh

(both are working)

THIS WONT WORK!

sudo /bin/sh example.sh
sudo example.sh

It will always return

sudo: bin/sh: command not found
sudo: example.sh: command not found

How do I store and retrieve a blob from sqlite?

Here's how you can do it in C#:

class Program
{
    static void Main(string[] args)
    {
        if (File.Exists("test.db3"))
        {
            File.Delete("test.db3");
        }
        using (var connection = new SQLiteConnection("Data Source=test.db3;Version=3"))
        using (var command = new SQLiteCommand("CREATE TABLE PHOTOS(ID INTEGER PRIMARY KEY AUTOINCREMENT, PHOTO BLOB)", connection))
        {
            connection.Open();
            command.ExecuteNonQuery();

            byte[] photo = new byte[] { 1, 2, 3, 4, 5 };

            command.CommandText = "INSERT INTO PHOTOS (PHOTO) VALUES (@photo)";
            command.Parameters.Add("@photo", DbType.Binary, 20).Value = photo;
            command.ExecuteNonQuery();

            command.CommandText = "SELECT PHOTO FROM PHOTOS WHERE ID = 1";
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    byte[] buffer = GetBytes(reader);
                }
            }

        }
    }

    static byte[] GetBytes(SQLiteDataReader reader)
    {
        const int CHUNK_SIZE = 2 * 1024;
        byte[] buffer = new byte[CHUNK_SIZE];
        long bytesRead;
        long fieldOffset = 0;
        using (MemoryStream stream = new MemoryStream())
        {
            while ((bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length)) > 0)
            {
                stream.Write(buffer, 0, (int)bytesRead);
                fieldOffset += bytesRead;
            }
            return stream.ToArray();
        }
    }
}

What is the difference between state and props in React?

In answer to the initial question about props being immutable, they are said to be immutable as far as the child component is concerned but are changeable in the parent.

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

You can also try using the one-jar maven plugin which fixed the problem for us. Simply follow the instructions from here.

How does one extract each folder name from a path?

public static IEnumerable<string> Split(this DirectoryInfo path)
{
    if (path == null) 
        throw new ArgumentNullException("path");
    if (path.Parent != null)
        foreach(var d in Split(path.Parent))
            yield return d;
    yield return path.Name;
}

How to create a .NET DateTime from ISO 8601 format

This solution makes use of the DateTimeStyles enumeration, and it also works with Z.

DateTime d2 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);

This prints the solution perfectly.

What is the function of FormulaR1C1?

Here's some info from my blog on how I like to use formular1c1 outside of vba:

You’ve just finished writing a formula, copied it to the whole spreadsheet, formatted everything and you realize that you forgot to make a reference absolute: every formula needed to reference Cell B2 but now, they all reference different cells.

How are you going to do a Find/Replace on the cells, considering that one has B5, the other C12, the third D25, etc., etc.?

The easy way is to update your Reference Style to R1C1. The R1C1 reference works with relative positioning: R marks the Row, C the Column and the numbers that follow R and C are either relative positions (between [ ]) or absolute positions (no [ ]).

Examples:

  • R[2]C refers to the cell two rows below the cell in which the formula’s in
  • RC[-1] refers to the cell one column to the left
  • R1C1 refers the cell in the first row and first cell ($A$1)

What does it matter? Well, When you wrote your first formula back in the beginning of this post, B2 was the cell 4 rows above the cell you wrote it in, i.e. R[-4]C. When you copy it across and down, while the A1 reference changes, the R1C1 reference doesn’t. Throughout the whole spreadsheet, it’s R[-4]C. If you switch to R1C1 Reference Style, you can replace R[-4]C by R2C2 ($B$2) with a simple Find / Replace and be done in one fell swoop.

Making the iPhone vibrate

A simple way to do so is with Audio Services:

#import <AudioToolbox/AudioToolbox.h> 
...    
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

jQuery: outer html()

No siblings solution:

var x = $('#xxx').parent().html();
alert(x);

Universal solution:

// no cloning necessary    
var x = $('#xxx').wrapAll('<div>').parent().html(); 
alert(x);

Fiddle here: http://jsfiddle.net/ezmilhouse/Mv76a/

Python non-greedy regexes

As the others have said using the ? modifier on the * quantifier will solve your immediate problem, but be careful, you are starting to stray into areas where regexes stop working and you need a parser instead. For instance, the string "(foo (bar)) baz" will cause you problems.

How to split a string after specific character in SQL Server and update this value to specific column

Try this:

UPDATE YourTable
SET Col2 = RIGHT(Col1,LEN(Col1)-CHARINDEX('/',Col1))

Method to find string inside of the text file. Then getting the following lines up to a certain limit

Here is the code of TextScanner

public class TextScanner {

        private static void readFile(String fileName) {
            try {
              File file = new File("/opt/pol/data22/ds_data118/0001/0025090290/2014/12/12/0029057983.ds");
              Scanner scanner = new Scanner(file);
              while (scanner.hasNext()) {
                System.out.println(scanner.next());
              }
              scanner.close();
            } catch (FileNotFoundException e) {
              e.printStackTrace();
            }
          }

          public static void main(String[] args) {
            if (args.length != 1) {
              System.err.println("usage: java TextScanner1"
                + "file location");
              System.exit(0);
            }
            readFile(args[0]);
      }
}

It will print text with delimeters

Setting Camera Parameters in OpenCV/Python

I had the same problem with openCV on Raspberry Pi... don't know if this can solve your problem, but what worked for me was

import time
import cv2


cap = cv2.VideoCapture(0)

cap.set(3,1280)

cap.set(4,1024)

time.sleep(2)

cap.set(15, -8.0)

the time you have to use can be different

Read the package name of an Android APK

Since its mentioned in Android documentation that AAPT has been deprecated, getting the package name using AAPT2 command in Linux is as follows:

./aapt2 dump packagename <path_to_apk>

Since I am using an older version of Gradle build, I had to download a newer version of AAPT2 as mentioned here :

Download AAPT2 from Google Maven

Using the build-tools in my sdk - 25.0.3, 26.0.1 and 27.0.3, executing the aapt2 command shows an error: Unable to open 'packagename': No such file or directory. That's why I went for the newer versions of AAPT2.

I used 3.3.0-5013011 for linux.

Python Linked List

Here is some list functions based on Martin v. Löwis's representation:

cons   = lambda el, lst: (el, lst)
mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None)
car = lambda lst: lst[0] if lst else lst
cdr = lambda lst: lst[1] if lst else lst
nth = lambda n, lst: nth(n-1, cdr(lst)) if n > 0 else car(lst)
length  = lambda lst, count=0: length(cdr(lst), count+1) if lst else count
begin   = lambda *args: args[-1]
display = lambda lst: begin(w("%s " % car(lst)), display(cdr(lst))) if lst else w("nil\n")

where w = sys.stdout.write

Although doubly linked lists are famously used in Raymond Hettinger's ordered set recipe, singly linked lists have no practical value in Python.

I've never used a singly linked list in Python for any problem except educational.

Thomas Watnedal suggested a good educational resource How to Think Like a Computer Scientist, Chapter 17: Linked lists:

A linked list is either:

  • the empty list, represented by None, or
  • a node that contains a cargo object and a reference to a linked list.

    class Node: 
      def __init__(self, cargo=None, next=None): 
        self.car = cargo 
        self.cdr = next    
      def __str__(self): 
        return str(self.car)
    
    def display(lst):
      if lst:
        w("%s " % lst)
        display(lst.cdr)
      else:
        w("nil\n")
    

How to convert seconds to HH:mm:ss in moment.js

From this post I would try this to avoid leap issues

moment("2015-01-01").startOf('day')
    .seconds(s)
    .format('H:mm:ss');

I did not run jsPerf, but I would think this is faster than creating new date objects a million times

function pad(num) {
    return ("0"+num).slice(-2);
}
function hhmmss(secs) {
  var minutes = Math.floor(secs / 60);
  secs = secs%60;
  var hours = Math.floor(minutes/60)
  minutes = minutes%60;
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}

_x000D_
_x000D_
function pad(num) {_x000D_
    return ("0"+num).slice(-2);_x000D_
}_x000D_
function hhmmss(secs) {_x000D_
  var minutes = Math.floor(secs / 60);_x000D_
  secs = secs%60;_x000D_
  var hours = Math.floor(minutes/60)_x000D_
  minutes = minutes%60;_x000D_
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;_x000D_
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers_x000D_
}_x000D_
_x000D_
for (var i=60;i<=60*60*5;i++) {_x000D_
 document.write(hhmmss(i)+'<br/>');_x000D_
}_x000D_
_x000D_
_x000D_
/* _x000D_
function show(s) {_x000D_
  var d = new Date();_x000D_
  var d1 = new Date(d.getTime()+s*1000);_x000D_
  var  hms = hhmmss(s);_x000D_
  return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);_x000D_
}    _x000D_
*/
_x000D_
_x000D_
_x000D_

Log all requests from the python-requests module

I'm using python 3.4, requests 2.19.1:

'urllib3' is the logger to get now (no longer 'requests.packages.urllib3'). Basic logging will still happen without setting http.client.HTTPConnection.debuglevel

Are string.Equals() and == operator really same?

C# has two "equals" concepts: Equals and ReferenceEquals. For most classes you will encounter, the == operator uses one or the other (or both), and generally only tests for ReferenceEquals when handling reference types (but the string Class is an instance where C# already knows how to test for value equality).

  • Equals compares values. (Even though two separate int variables don't exist in the same spot in memory, they can still contain the same value.)
  • ReferenceEquals compares the reference and returns whether the operands point to the same object in memory.

Example Code:

var s1 = new StringBuilder("str");
var s2 = new StringBuilder("str");
StringBuilder sNull = null;

s1.Equals(s2); // True
object.ReferenceEquals(s1, s2); // False
s1 == s2 // True - it calls Equals within operator overload
s1 == sNull // False
object.ReferenceEquals(s1, sNull); // False
s1.Equals(sNull); // Nono!  Explode (Exception)

Load RSA public key from file

Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/

   import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;

    public class Demo {

        public static final String PRIVATE_KEY="/home/user/private.der";
        public static final String PUBLIC_KEY="/home/user/public.der";

        public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
            //get the private key
            File file = new File(PRIVATE_KEY);
            FileInputStream fis = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(fis);

            byte[] keyBytes = new byte[(int) file.length()];
            dis.readFully(keyBytes);
            dis.close();

            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
            System.out.println("Exponent :" + privKey.getPrivateExponent());
            System.out.println("Modulus" + privKey.getModulus());

            //get the public key
            File file1 = new File(PUBLIC_KEY);
            FileInputStream fis1 = new FileInputStream(file1);
            DataInputStream dis1 = new DataInputStream(fis1);
            byte[] keyBytes1 = new byte[(int) file1.length()];
            dis1.readFully(keyBytes1);
            dis1.close();

            X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
            KeyFactory kf1 = KeyFactory.getInstance("RSA");
            RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);

            System.out.println("Exponent :" + pubKey.getPublicExponent());
            System.out.println("Modulus" + pubKey.getModulus());
        }
    }

How can I bring my application window to the front?

I use SwitchToThisWindow to bring the application to the forefront as in this example:

static class Program
{
    [DllImport("User32.dll", SetLastError = true)]
    static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);



    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        bool createdNew;
        int iP;
        Process currentProcess = Process.GetCurrentProcess();
        Mutex m = new Mutex(true, "XYZ", out createdNew);
        if (!createdNew)
        {
            // app is already running...
            Process[] proc = Process.GetProcessesByName("XYZ");

            // switch to other process
            for (iP = 0; iP < proc.Length; iP++)
            {
                if (proc[iP].Id != currentProcess.Id)
                    SwitchToThisWindow(proc[0].MainWindowHandle, true);
            }

            return;
        }

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new form());
        GC.KeepAlive(m);

    }

How to access cookies in AngularJS?

This answer has been updated to reflect latest stable angularjs version. One important note is that $cookieStore is a thin wrapper surrounding $cookies. They are pretty much the same in that they only work with session cookies. Although, this answers the original question, there are other solutions you may wish to consider such as using localstorage, or jquery.cookie plugin (which would give you more fine-grained control and do serverside cookies. Of course doing so in angularjs means you probably would want to wrap them in a service and use $scope.apply to notify angular of changes to models (in some cases).

One other note and that is that there is a slight difference between the two when pulling data out depending on if you used $cookie to store value or $cookieStore. Of course, you'd really want to use one or the other.

In addition to adding reference to the js file you need to inject ngCookies into your app definition such as:

angular.module('myApp', ['ngCookies']);

you should then be good to go.

Here is a functional minimal example, where I show that cookieStore is a thin wrapper around cookies:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
   <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-controller="MyController">

  <h3>Cookies</h3>
  <pre>{{usingCookies|json}}</pre>
  <h3>Cookie Store</h3>
  <pre>{{usingCookieStore|json}}</pre>

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-cookies.js"></script>
  <script>
    angular.module('myApp', ['ngCookies']);
    app.controller('MyController',['$scope','$cookies','$cookieStore', 
                       function($scope,$cookies,$cookieStore) {
      var someSessionObj = { 'innerObj' : 'somesessioncookievalue'};

    $cookies.dotobject = someSessionObj;
    $scope.usingCookies = { 'cookies.dotobject' : $cookies.dotobject, "cookieStore.get" : $cookieStore.get('dotobject') };

    $cookieStore.put('obj', someSessionObj);
    $scope.usingCookieStore = { "cookieStore.get" : $cookieStore.get('obj'), 'cookies.dotobject' : $cookies.obj, };
    }
  </script>

</body>
</html>

The steps are:

  1. include angular.js
  2. include angular-cookies.js
  3. inject ngCookies into your app module (and make sure you reference that module in the ng-app attribute)
  4. add a $cookies or $cookieStore parameter to the controller
  5. access the cookie as a member variable using the dot (.) operator -- OR --
  6. access cookieStore using put/get methods

Java 8 Distinct by property

The easiest way to implement this is to jump on the sort feature as it already provides an optional Comparator which can be created using an element’s property. Then you have to filter duplicates out which can be done using a statefull Predicate which uses the fact that for a sorted stream all equal elements are adjacent:

Comparator<Person> c=Comparator.comparing(Person::getName);
stream.sorted(c).filter(new Predicate<Person>() {
    Person previous;
    public boolean test(Person p) {
      if(previous!=null && c.compare(previous, p)==0)
        return false;
      previous=p;
      return true;
    }
})./* more stream operations here */;

Of course, a statefull Predicate is not thread-safe, however if that’s your need you can move this logic into a Collector and let the stream take care of the thread-safety when using your Collector. This depends on what you want to do with the stream of distinct elements which you didn’t tell us in your question.

Remove decimal values using SQL query

If it's a decimal data type and you know it will never contain decimal places you can consider setting the scale property to 0. For example to decimal(18, 0). This will save you from replacing the ".00" characters and the query will be faster. In such case, don't forget to to check if the "prevent saving option" is disabled (SSMS menu "Tools>Options>Designers>Table and database designer>prevent saving changes that require table re-creation").

Othewise, you of course remove it using SQL query:

select replace(cast([height] as varchar), '.00', '') from table

Apache: The requested URL / was not found on this server. Apache

I had the same problem, but believe it or not is was a case of case sensitivity.

This on localhost: http://localhost/.../getdata.php?id=3

Did not behave the same as this on the server: http://server/.../getdata.php?id=3

Changing the server url to this (notice the capital D in getData) solved my issue. http://localhost/.../getData.php?id=3

How to clear all input fields in bootstrap modal when clicking data-dismiss button?

This is helpfull, its work for me..

$('.bd-example-modal-sm').on('hidden.bs.modal', function () { 
      $(this).find("select").val('').end(); // Clear dropdown content
      $("ul").empty();   // Clear li content 
});

Hibernate-sequence doesn't exist

You can also put :

@GeneratedValue(strategy = GenerationType.IDENTITY)

And let the DateBase manage the incrementation of the primary key:

AUTO_INCREMENT PRIMARY KEY

How to find which version of Oracle is installed on a Linux server (In terminal)

Login as sys user in sql*plus. Then do this query:

select * from v$version; 

or

select * from product_component_version;

NotificationCompat.Builder deprecated in Android O

  1. Need to declare a Notification channel with Notification_Channel_ID
  2. Build notification with that channel ID. For example,

...
 public static final String NOTIFICATION_CHANNEL_ID = MyLocationService.class.getSimpleName();
...
...
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                NOTIFICATION_CHANNEL_ID+"_name",
                NotificationManager.IMPORTANCE_HIGH);

NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

notifManager.createNotificationChannel(channel);


NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.notification_text))
                .setOngoing(true)
                .setContentIntent(broadcastIntent)
                .setSmallIcon(R.drawable.ic_tracker)
                .setPriority(PRIORITY_HIGH)
                .setCategory(Notification.CATEGORY_SERVICE);

        startForeground(1, builder.build());
...

Constant pointer vs Pointer to constant

const int* ptr; here think like *ptr is constant and *ptr can't be change again

int * const ptr; while here think like ptr as a constant and that can't be change again

Use of the MANIFEST.MF file in Java

The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.

Manifest-Version: 1.0

All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers

Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions

Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:

Main-Class: classname

The value classname is to be replaced with the application's entry point.

Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:

Class-Path: servlet.jar infobus.jar acme/beans.jar

With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.

Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:

Name: myCompany/myPackage/
Sealed: true

The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.

Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:

Name: java/util/
Specification-Title: "Java Utility Classes" 
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util" 
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."

Mix Razor and Javascript code

A non conventional method to separate javascript from the view, but still use razor in it is to make a Scripts.cshtml file and place your mixed javascript/razor there.

Index.cshtml

<div id="Result">
</div>

<button id="btnLoad">Click me</button>

@section scripts
{
    @Html.Partial("Scripts")
}

Scripts.cshtml

<script type="text/javascript">
    var url = "@Url.Action("Index", "Home")";

    $(document).ready(function() {
        $("#btnLoad").click(function() {
            $.ajax({
                type: "POST",
                url: url ,
                data: {someParameter: "some value"},
                contentType: "application/json; charset=utf-8",
                dataType: "json",

                success: function(msg) {
                    $("#Result").text(msg.d);
                }
            });
        });
    });
</script>

Display a decimal in scientific notation

My decimals are too big for %E so I had to improvize:

def format_decimal(x, prec=2):
    tup = x.as_tuple()
    digits = list(tup.digits[:prec + 1])
    sign = '-' if tup.sign else ''
    dec = ''.join(str(i) for i in digits[1:])
    exp = x.adjusted()
    return '{sign}{int}.{dec}e{exp}'.format(sign=sign, int=digits[0], dec=dec, exp=exp)

Here's an example usage:

>>> n = decimal.Decimal(4.3) ** 12314
>>> print format_decimal(n)
3.39e7800
>>> print '%e' % n
inf

How to generate a create table script for an existing table in phpmyadmin?

Export whole database select format as SQL. Now, open that SQL file which you have downloaded using notepad, notepad++ or any editor. You will see all the tables and insert queries of your database. All scripts will be available there.

How to send email in ASP.NET C#

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Globalization;
    using System.Text.RegularExpressions;
    
    /// <summary>
    /// Summary description for RegexUtilities
    /// </summary>
    public class RegexUtilities
    {
        bool InValid = false;
    
        public bool IsValidEmail(string strIn)
        {
            InValid = false;
            if (String.IsNullOrEmpty(strIn))
                return false;
    
            // Use IdnMapping class to convert Unicode domain names.
            strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper);
            if (InValid)
                return false;
    
            // Return true if strIn is in valid e-mail format. 
            return Regex.IsMatch(strIn, @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
                   RegexOptions.IgnoreCase);
        }
    
        private string DomainMapper(Match match)
        {
            // IdnMapping class with default property values.
            IdnMapping idn = new IdnMapping();
    
            string domainName = match.Groups[2].Value;
            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException)
            {
                InValid = true;
            }
            return match.Groups[1].Value + domainName;
        }
    
    }



 private void GetSendEmInfo()
    {
        #region For Get All Type Email Informations..!!
        IPL.DoId = ddlName.SelectedValue;
        DataTable dt = IdBL.GetEmailS(IPL);
        if (dt.Rows.Count > 0)
        {
            hid_MailId.Value = dt.Rows[0]["MailId"].ToString();
            hid_UsedPName.Value = dt.Rows[0]["UName"].ToString();
            hid_EmailSubject.Value = dt.Rows[0]["EmailSubject"].ToString();
            hid_EmailBody.Value = dt.Rows[0]["EmailBody"].ToString();
            hid_EmailIdName.Value = dt.Rows[0]["EmailIdName"].ToString();
            hid_EmPass.Value = dt.Rows[0]["EPass"].ToString();
            hid_SeName.Value = dt.Rows[0]["SenName"].ToString();
            hid_TNo.Value = dt.Rows[0]["TeNo"].ToString();
            hid_EmaLimit.Value = dt.Rows[0]["EmailLimit"].ToString();
            hidlink.Value = dt.Rows[0][link"].ToString();
        }
        #endregion

        #region For Set Some Local Variables..!!
        int StartLmt, FinalLmt, SendCurrentMail;
        StartLmt = FinalLmt = SendCurrentMail = 0;
        bool Valid_LimitMail;
        Valid_LimitMail = true;
        /**For Get Finalize Limit For Send Mail**/
        FinalLmt = Convert.ToInt32(hid_EmailmaxLimit.Value);
        #region For Check Email Valid Limits..!!
        if (FinalLmt > 0)
        {
            Valid_LimitMail = true;
        }
        else
        {
            Valid_LimitMail = false;
        }
        #endregion
        /**For Get Finalize Limit For Send Mail**/
        #endregion

        if (Valid_LimitMail == true)
        {
            #region For Send Current Email Status..!!
            bool EmaiValid;
            string CreateFileName;
            string retmailflg = null;
            EmaiValid = false;
            #endregion

            #region For Set Start Limit And FinalLimit Send No Of Email..!!
            mPL.SendDate = DateTime.Now.ToString("dd-MMM-yyyy");
            DataTable dtsendEmail = m1BL.GetEmailSendLog(mPL);
            if (dtsendEmail.Rows.Count > 0)
            {
                StartLmt = Convert.ToInt32(dtsendEmail.Rows[0]["SendNo_Of_Email"].ToString());
            }
            else
            {
                StartLmt = 0;
            }
            #endregion

            #region For Find Grid View Controls..!!
            for (int i = 0; i < GrdEm.Rows.Count; i++)
            {
                #region For Find Grid view Controls..!!
                CheckBox Chk_SelectOne = (CheckBox)GrdEmp.Rows[i].FindControl("chkSingle");
                Label lbl_No = (Label)GrdEmAtt.Rows[i].FindControl("lblGrdCode");
                lblCode.Value = lbl_InNo.Text;

                Label lbl_EmailId = (Label)GrdEomAtt.Rows[i].FindControl("lblGrdEmpEmail");

                #endregion

                /**Region For If Check Box Checked Then**/
                if (Chk_SelectOne.Checked == true)
                {
                    if (!string.IsNullOrEmpty(lbl_EmailId.Text))
                    {
                        #region For When Check Box Checked..!!
                        /**If Start Limit Less Or Equal To Then Condition Performs**/
                        if (StartLmt < FinalLmt)
                        {
                            StartLmt = StartLmt + 1;
                        }
                        else
                        {
                            Valid_LimitMail = false;
                            EmaiValid = false;
                        }
                        /**End Region**/
                        string[] SplitClients_Email = lbl_EmailId.Text.Split(',');
                        string Send_Email, Hold_Email;
                        Send_Email = Hold_Email = "";

                        int CountEmail;/**Region For Count Total Email**/
                        CountEmail = 0;/**First Time Email Counts Zero**/

                        Hold_Email = SplitClients_Email[0].ToString().Trim().TrimEnd().TrimStart().ToString();
                        /**Region For If Clients Have One Email**/
                        #region For First Emails Send On Client..!!
                        if (SplitClients_Email[0].ToString() != "")
                        {
                            if (EmailRegex.IsValidEmail(Hold_Email))
                            {
                                Send_Email = Hold_Email;
                                CountEmail = 1;
                                EmaiValid = true;
                            }
                            else
                            {
                                EmaiValid = false;
                            }
                        }
                        #endregion
                        /**Region For If Clients Have One Email**/
                        /**Region For If Clients Have Two Email**/

                        /**Region For If Clients Have Two Email**/
                        if (EmaiValid == true)
                        {
                            #region For Create Email Body And Create File Name..!!
                            //fofile = Server.MapPath("PDFs");
                            fofile = Server.MapPath("~/vvv/vvvv/") + "/";
                            CreateFileName = lbl_INo.Text.ToString() + "_1" + ".Pdf";/**Create File Name**/
                            string[] orimail = Send_Email.Split(',');
                            string Billbody, TempInvoiceId;
                            // DateTime dtLstdate = new DateTime(Convert.ToInt32(txtYear.Text), Convert.ToInt32(ddlMonth.SelectedValue), 16);

                            //  DateTime IndtLmt = dtLstdate.AddMonths(1);
                            TempInvoiceId = "";

                            //byte[] Buffer = Encrypt.Encryptiondata(lbl_InvoiceNo.Text.ToString());
                            //TempInvoiceId = Convert.ToBase64String(Buffer);


                            #region Create Encrypted Path


                            byte[] EncCode = Encrypt.Encryptiondata(lbl_INo.Text);
                            hidEncrypteCode.Value = Convert.ToBase64String(EncECode);
                            #endregion

                        

                            //#region Create Email Body !!
                            //body = hid_EmailBody.Value.Replace("@greeting", lbl_CoName.Text).Replace("@free", hid_ToNo.Value).Replace("@llnk", "<a style='font-family: Tahoma; font-size: 10pt; color: #800000; font-weight: bold' href='http://1ccccc/ccc/ccc/ccc.aspx?EC=" + hidEncryptedCode.Value+ "' > C cccccccc </a>");
                          

                            body = hid_EmailBody.Value.Replace("@greeting", "Hii").Replace("@No", hid_No.Value);/*For Mail*/
                            //#endregion



                            #region For Email Sender Informations..!!
                            for (int j = 0; j < CountEmail; j++)
                            {
                                //if (File.Exists(fofile + "\\" + CreateFileName))
                                //{
                                #region
                                lbl_EmailId.Text = orimail[j];
                                retmailflg = "";

                                /**Region For Send Email For Clients**/
                                //retmailflg = SendPreMail("Wp From " + lbl_CName.Text + "", body, lbl_EmailId.Text, lbl_IeNo.Text, hid_EmailIdName.Value, hid_EmailPassword.Value);
                                retmailflg = SendPreMail(hid_EmailSubject.Value, Body, lbl_EmailId.Text, lbl_No.Text, hid_EmailIdName.Value, hid_EmailPassword.Value);
                                /**End Region**/

                                /**Region For Create Send Email Log  When Email Send Successfully**/
                                if (retmailflg == "True")
                                {
                                    SendCurrentMail = Convert.ToInt32(SendCurrentMail) + 1;
                                    StartLmt = Convert.ToInt32(StartLmt) + 1;

                                    if (SendCurrentMail > 0)
                                    {
                                        CreateEmailLog(lbl_InNo.Text, StartLmt, hid_EmailIdName.Value, lbl_EmailId.Text);
                                        
                                    }
                                }
                                

                                /**End Region**/
                                #endregion
                                //}
                            }
                            #endregion
                        }
                        #endregion
                    }
                }
                /**End Region**/
            }
            #endregion

        }
       
    }
    private void CreateEmailLog(string UniqueId, int StartLmt, string FromEmailId, string TotxtEmailId)
    {
        FPL.EmailId_From = FromEmailId;
        FPL.To_EmailId = TotxtEmailId;
        FPL.SendDate = DateTime.Now.ToString("dd-MMM-yyyy");
        FPL.EmailUniqueId = UniqueId;
        FPL.SendNo_Of_Email = StartLmt.ToString();
        FPL.LoginUserId = Session["LoginUserId"].ToString();
        int i = FBL.InsertEmaDoc(FPL);
    }

    public string SendPreMail(string emsub, string embody, string EmailId, string FileId, string EmailFromId, string Password)
    {
        string retval = "False";
        try
        {
            string emailBody, emailSubject, emailToList, emailFrom,
            accountPassword, smtpServer;
            bool enableSSL;
            int port;

            emailBody = embody;
            emailSubject = emsub;
            emailToList = EmailId;
            emailFrom = EmailFromId;
            accountPassword = Password;
            smtpServer = "smtp.gmail.com";
            enableSSL = true;
            port = 587;

            string crefilename;
            string fofile;
            fofile = Server.MapPath("PDF");
            crefilename = FileId + ".Pdf";

            string[] att = { crefilename };

            string retemail, insertqry;
            retemail = "";

            retemail = SendEmail(emailBody, emailSubject, emailFrom, emailToList, att, smtpServer, enableSSL, accountPassword, port);

            if (retemail == "True")
            {

                retval = retemail;
            }
        }
        catch
        {
            retval = "False";
        }
        finally
        {

        }
        return retval;
    }

    public string SendEmail(string emailBody, string emailSubject, string emailFrom, string emailToList, string[] attachedFiles, string smtpIPAddress, bool enableSSL, string accountPassword, int port)
    {
        MailMessage mail = new MailMessage();
        string retflg;
        retflg = "False";
        try
        {
            mail.From = new MailAddress(emailFrom);
            if (emailToList.Contains(";"))
            {
                emailToList = emailToList.Replace(";", ",");
            }
            mail.To.Add(emailToList);

            mail.Subject = emailSubject;
            mail.IsBodyHtml = true;
            mail.Body = emailBody;


            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            NetworkCredential NetworkCred = new NetworkCredential(emailFrom, accountPassword);
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mail);
            retflg = "True";

        }
        catch
        {
            retflg = "False";
        }
        finally
        {
            mail.Dispose();
        }
        return retflg;
    }

Determine if JavaScript value is an "integer"?

Use jQuery's IsNumeric method.

http://api.jquery.com/jQuery.isNumeric/

if ($.isNumeric(id)) {
   //it's numeric
}

CORRECTION: that would not ensure an integer. This would:

if ( (id+"").match(/^\d+$/) ) {
   //it's all digits
}

That, of course, doesn't use jQuery, but I assume jQuery isn't actually mandatory as long as the solution works

redirect while passing arguments

You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session (cookie) variable before redirecting and then get the variable before rendering the template. For example:

from flask import session, url_for

def do_baz():
    messages = json.dumps({"main":"Condition failed on page baz"})
    session['messages'] = messages
    return redirect(url_for('.do_foo', messages=messages))

@app.route('/foo')
def do_foo():
    messages = request.args['messages']  # counterpart for url_for()
    messages = session['messages']       # counterpart for session
    return render_template("foo.html", messages=json.loads(messages))

(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)

Or you could probably just use Flask Message Flashing if you just need to show simple messages.

href="file://" doesn't work

Share your folder for "everyone" or some specific group and try this:

_x000D_
_x000D_
<a href="file://YOURSERVERNAME/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf"> Download PDF </a> 
_x000D_
_x000D_
_x000D_

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

I have the exact same configuration. This answer pertains specifically to connecting to a raspberry pi from inside the local network (not outside). I have A raspberry pi ssh server, and a macbook pro, both connected to a a router. On a test router, my mac connects perfectly when I use ssh danran@mypiserver, however, when I use ssh danran@mypiserver on my main router, i get the error

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

Just as you have gotten. It seems, the solution for me at least, was to add a .local extension to the hostname when connecting from my mac via ssh.

So, to solve this, i used the command ssh [email protected] (remember to replace the "danran" with your username and the "mypiserver" with your hostname) instead of using ssh danran@mypiserver.

To anyone reading this, try adding a .local as the suffix to your hostname you are trying to connect to. That should solve the issue on a local network.

Reload browser window after POST without prompting user to resend POST data

This worked

<button onclick="window.location.href=window.location.href; return false;">Continue</button>

The reason it doesn't work without the return false; is that the button click would trigger a form submit. With an explicit return false on it, it doesn't do the form submit and just does the reload of the same page that was a result of a previous POST to that page.

SQL - How to select a row having a column with max value

Analytics! This avoids having to access the table twice:

SELECT DISTINCT
       FIRST_VALUE(date_col)  OVER (ORDER BY value_col DESC, date_col ASC),
       FIRST_VALUE(value_col) OVER (ORDER BY value_col DESC, date_col ASC)
FROM   mytable;

Difference between static STATIC_URL and STATIC_ROOT on Django

STATICFILES_DIRS: You can keep the static files for your project here e.g. the ones used by your templates.

STATIC_ROOT: leave this empty, when you do manage.py collectstatic, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.

--------Edit----------------

As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

or

STATIC_ROOT = '/opt/web/project/static_files'

--------End Edit -----------------

STATIC_URL: '/static/' is usually fine, it's just a prefix for static files.

Failed to resolve: com.google.firebase:firebase-core:9.0.0

Tried all the above, use the Firebase Assistant! It is the simplest way to solve this. First remove all the dependencies you added to the build.gradle (using the manual method) and then in Android Studio:

Click Tools > Firebase to open the Assistant window.

It really is as easy as that.

"Multiple definition", "first defined here" errors

I had a similar issue when not using inline for my global function that was included in two places.

How to add number of days in postgresql datetime

This will give you the deadline :

select id,  
       title,
       created_at + interval '1' day * claim_window as deadline
from projects

Alternatively the function make_interval can be used:

select id,  
       title,
       created_at + make_interval(days => claim_window) as deadline
from projects

To get all projects where the deadline is over, use:

select *
from (
  select id, 
         created_at + interval '1' day * claim_window as deadline
  from projects
) t
where localtimestamp at time zone 'UTC' > deadline

How to programmatically determine the current checked out Git branch

adapting the accepted answer to windows powershell:

Split-Path -Leaf (git symbolic-ref HEAD)

SQL Server 2008- Get table constraints

I tried to edit the answer provided by marc_s however it wasn't accepted for some reason. It formats the sql for easier reading, includes the schema and also names the Default name so that this can easily be pasted into other code.

  SELECT SchemaName = s.Name,
         TableName = t.Name,
         ColumnName = c.Name,
         DefaultName = dc.Name,
         DefaultDefinition = dc.Definition
    FROM sys.schemas                s
    JOIN sys.tables                 t   on  t.schema_id          = s.schema_id
    JOIN sys.default_constraints    dc  on  dc.parent_object_id  = t.object_id 
    JOIN sys.columns                c   on  c.object_id          = dc.parent_object_id
                                        and c.column_id          = dc.parent_column_id
ORDER BY s.Name, t.Name, c.name

How do I return the response from an asynchronous call?

This is one of the places which two ways data binding or store concept that's used in many new JavaScript frameworks will work great for you...

So if you are using Angular, React or any other frameworks which do two ways data binding or store concept this issue is simply fixed for you, so in easy word, your result is undefined at the first stage, so you have got result = undefined before you receive the data, then as soon as you get the result, it will be updated and get assigned to the new value which response of your Ajax call...

But how you can do it in pure javascript or jQuery for example as you asked in this question?

You can use a callback, promise and recently observable to handle it for you, for example in promises we have some function like success() or then() which will be executed when your data is ready for you, same with callback or subscribe function on observable.

For example in your case which you are using jQuery, you can do something like this:

$(document).ready(function(){
    function foo() {
        $.ajax({url: "api/data", success: function(data){
            fooDone(data); //after we have data, we pass it to fooDone
        }});
    };

    function fooDone(data) {
        console.log(data); //fooDone has the data and console.log it
    };

    foo(); //call happens here
});

For more information study about promises and observables which are newer ways to do this async stuffs.

apply drop shadow to border-top only?

I find using these interactive tools help visualize what's happening, and whats possible

http://css3gen.com/box-shadow/

http://www.cssmatic.com/box-shadow

http://css3generator.com/

Edit: Check out the other tools for experimenting with the other generators and combinations. I have to remind myself sometimes that just because you can, doesn't mean you should - its easy to get carried away!

How do I add more members to my ENUM-type column in MySQL?

ALTER TABLE
    `table_name`
MODIFY COLUMN
    `column_name2` enum(
        'existing_value1',
        'existing_value2',
        'new_value1',
        'new_value2'
    )
NOT NULL AFTER `column_name1`;

Remote Procedure call failed with sql server 2008 R2

I just had the same issue and was able to solve it by installing Service Pack 1.

How to plot multiple functions on the same figure, in Matplotlib?

Just use the function plot as follows

figure()
...
plot(t, a)
plot(t, b)
plot(t, c)

How to encrypt String in Java

Here are some links you can read what Java supports

Encrypting/decrypting a data stream.

This example demonstrates how to encrypt (using a symmetric encryption algorithm such as AES, Blowfish, RC2, 3DES, etc) a large amount of data. The data is passed in chunks to one of the encrypt methods: EncryptBytes, EncryptString, EncryptBytesENC, or EncryptStringENC. (The method name indicates the type of input (string or byte array) and the return type (encoded string or byte array). The FirstChunk and LastChunk properties are used to indicate whether a chunk is the first, middle, or last in a stream to be encrypted. By default, both FirstChunk and LastChunk equal true -- meaning that the data passed is the entire amount.

JCERefGuide

Java Encryption Examples

Datetime current year and month in Python

Use:

from datetime import datetime

current_month = datetime.now().strftime('%m') // 02 //This is 0 padded
current_month_text = datetime.now().strftime('%h') // Feb
current_month_text = datetime.now().strftime('%B') // February

current_day = datetime.now().strftime('%d')   // 23 //This is also padded
current_day_text = datetime.now().strftime('%a')  // Fri
current_day_full_text = datetime.now().strftime('%A')  // Friday

current_weekday_day_of_today = datetime.now().strftime('%w') //5  Where 0 is Sunday and 6 is Saturday.

current_year_full = datetime.now().strftime('%Y')  // 2018
current_year_short = datetime.now().strftime('%y')  // 18 without century

current_second= datetime.now().strftime('%S') //53
current_minute = datetime.now().strftime('%M') //38
current_hour = datetime.now().strftime('%H') //16 like 4pm
current_hour = datetime.now().strftime('%I') // 04 pm

current_hour_am_pm = datetime.now().strftime('%p') // 4 pm

current_microseconds = datetime.now().strftime('%f') // 623596 Rarely we need.

current_timzone = datetime.now().strftime('%Z') // UTC, EST, CST etc. (empty string if the object is naive).

Reference: 8.1.7. strftime() and strptime() Behavior

Reference: strftime() and strptime() Behavior

The above things are useful for any date parsing, not only now or today. It can be useful for any date parsing.

e.g.
my_date = "23-02-2018 00:00:00"

datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S+00:00')

datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%m')

And so on...

handling dbnull data in vb.net

For the rows containing strings, I can convert them to strings as in changing

tmpStr = nameItem("lastname") + " " + nameItem("initials")

to

tmpStr = myItem("lastname").toString + " " + myItem("intials").toString

For the comparison in the if statement myItem("sID")=sID, it needs to be change to

myItem("sID").Equals(sID)

Then the code will run without any runtime errors due to vbNull data.

Playing a MP3 file in a WinForm application

  1. first go to the properties of your project
  2. click on add references
  3. add the library under COM object for window media player then type your code where you want


    Source:

        WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
    
        wplayer.URL = @"C:\Users\Adil M\Documents\Visual Studio 2012\adil.mp3";
        wplayer.controls.play();
    

Regular Expression to get all characters before "-"

You could just use another non-regex based method. Someone gave the suggestion of using Substring, but you could also use Split:

string testString = "my-string";
string[] splitString = testString.Split("-");
string resultingString = splitString[0]; //my

See http://msdn.microsoft.com/en-US/library/ms228388%28v=VS.80%29.aspx for another good example.

Read lines from a file into a Bash array

Your first attempt was close. Here is the simplistic approach using your idea.

file="somefileondisk"
lines=`cat $file`
for line in $lines; do
        echo "$line"
done

eclipse won't start - no java virtual machine was found

Some time this happens when your Java folder get updated.

Open Eclipse folder and search file eclipse.ini. Open the eclipse.ini file and check whether jre version is same as jre available in your java folder.

I faced same problem when my jre got changed from jre1.8.0_101 to jre1.8.0_111.

C:\Program Files\Java\jre1.8.0_101\bin to C:\Program Files\Java\jre1.8.0_111\bin

Split array into two parts without for loop in java

copyOfRange

This does what you want without you having to create a new array as it returns a new array.

int[] original = new int[300000];
int[] firstHalf = Arrays.copyOfRange(original, 0, original.length/2);

Android disable screen timeout while app is running

1.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);is best solution for Native Android.
2. if you want to do with React android application then please use the below code.

@ReactMethod
    public void activate() {
        final Activity activity = getCurrentActivity();
        if (activity != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }
            });
        }

    }

How to iterate std::set?

One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth element normal way will not work. example:

std::vector<int > vec{1,2,3,4,5};
int k=3;
for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";

std::unordered_set<int > s{1,2,3,4,5};
int k=3;
int index=0;
auto itr=s.begin();
while(true){
   if(index==k) break;
   cout<<*itr++<<" ";
   index++;
}

Load json from local file with http.get() in angular 2

MY OWN SOLUTION

I created a new component called test in this folder:

enter image description here

I also created a mock called test.json in the assests folder created by angular cli (important):

enter image description here

This mock looks like this:

[
        {
            "id": 1,
            "name": "Item 1"
        },
        {
            "id": 2,
            "name": "Item 2"
        },
        {
            "id": 3,
            "name": "Item 3"
        }
]

In the controller of my component test import follow rxjs like this

import 'rxjs/add/operator/map'

This is important, because you have to map your response from the http get call, so you get a json and can loop it in your ngFor. Here is my code how I load the mock data. I used http get and called my path to the mock with this path this.http.get("/assets/mock/test/test.json"). After this i map the response and subscribe it. Then I assign it to my variable items and loop it with ngFor in my template. I also export the type. Here is my whole controller code:

import { Component, OnInit } from "@angular/core";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map'

export type Item = { id: number, name: string };

@Component({
  selector: "test",
  templateUrl: "./test.component.html",
  styleUrls: ["./test.component.scss"]
})
export class TestComponent implements OnInit {
  items: Array<Item>;

  constructor(private http: Http) {}

  ngOnInit() {
    this.http
      .get("/assets/mock/test/test.json")
      .map(data => data.json() as Array<Item>)
      .subscribe(data => {
        this.items = data;
        console.log(data);
      });
  }
}

And my loop in it's template:

<div *ngFor="let item of items">
  {{item.name}}
</div>

It works as expected! I can now add more mock files in the assests folder and just change the path to get it as json. Notice that you have also to import the HTTP and Response in your controller. The same in you app.module.ts (main) like this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule, JsonpModule } from '@angular/http';


import { AppComponent } from './app.component';
import { TestComponent } from './components/molecules/test/test.component';


@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    JsonpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

How to make <div> fill <td> height

If you give your TD a height of 1px, then the child div would have a heighted parent to calculate it's % from. Because your contents would be larger then 1px, the td would automatically grow, as would the div. Kinda a garbage hack, but I bet it would work.

How can I preview a merge in git?

I do not want to use the git merge command as the precursor to reviewing conflicting files. I don't want to do a merge, I want to identify potential problems before I merge - problems that auto-merge might hide from me. The solution I have been searching for is how to have git spit out a list of files that have been changed in both branches that will be merged together in the future, relative to some common ancestor. Once I have that list, I can use other file comparison tools to scout things out further. I have searched multiple times, and I still haven't found what I want in a native git command.

Here is my workaround, in case it helps anyone else out there:

In this scenario I have a branch called QA that has many changes in it since the last production release. Our last production release is tagged with "15.20.1". I have another development branch called new_stuff that I want to merge into the QA branch. Both QA and new_stuff point to commits that "follow" (as reported by gitk) the 15.20.1 tag.

git checkout QA
git pull
git diff 15.20.1 --name-only > QA_files
git checkout new_stuff
git pull
git diff 15.20.1 --name-only > new_stuff_files
comm -12 QA_files new_stuff_files

Here are some discussions that hit on why I'm interested in targeting these specific files:

How can I trust Git merge?

https://softwareengineering.stackexchange.com/questions/199780/how-far-do-you-trust-automerge

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

You are trying to get data from an https that does not have certificate. Change "https://" to "http://". Worked for me.

jquery $(window).height() is returning the document height

Its really working if we use Doctype on our web page jquery(window) will return the viewport height else it will return the complete document height.

Define the following tag on the top of your web page: <!DOCTYPE html>

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

check whether there is a comma at the end.

                            },
                            {
                                name: '???. ??????? ?? ?????. ?3/?',
                                data: graph_high3,
                                dataGrouping: {
                                    units: groupingUnits,
                                    groupPixelWidth: 40,
                                    approximation: "average",
                                    enabled: true,
                                    units: [[
                                            'minute',
                                            [1]
                                        ]]
                                }
                            }   // if , - SCRIPT5007

CSS customized scroll bar in div

Or use somthing like this:

var MiniScroll=function(a,b){function e(){c.scrollUpdate()}function f(){var a=new Date,b=Math.abs(a-c.animation.frame),d=c.countScrollHeight();c.animation.frame=a,c.render(b),d.height!=c.controls.height&&(e(),c.controls.height=d.height),requestAnimationFrame(f)}function g(){c.scrollUpdate()}function h(a){var b=c.target.scrollTop,d=Math.abs(a.wheelDeltaY/(10-c.speed));c.target.scrollTop=a.wheelDeltaY>0?b-d:b+d,c.scrollUpdate()}function i(a){if(a.target.classList.contains("scroll"))return a.preventDefault(),!1;var b=c.countScrollHeight();c.target.scrollTop=a.offsetY*b.mul-parseInt(b.height)/2,c.scrollUpdate()}b=b||{};var c=this,d={speed:"speed"in b?b.speed:7};this.target=document.querySelector(a),this.animation={frame:new Date,stack:[]},this.identity="scroll"+parseInt(1e5*Math.random()),this.controls={place:null,scroll:null,height:0},this.speed=d.speed,this.target.style.overflow="hidden",this.draw(),requestAnimationFrame(f),this.target.onscroll=g,this.target.addEventListener("wheel",h),this.controls.place.onclick=i};MiniScroll.prototype.scrollUpdate=function(){this.controls.place.style.height=this.target.offsetHeight+"px";var a=this.countScrollHeight();this.controls.scroll.style.height=a.height,this.controls.scroll.style.top=a.top},MiniScroll.prototype.countScrollHeight=function(){for(var a=this.target.childNodes,b=parseInt(this.target.offsetHeight),c=0,d=0;d<a.length;d++)a[d].id!=this.identity&&(c+=parseInt(a[d].offsetHeight)||0);var e=this.target.offsetHeight*parseFloat(1/(parseFloat(c)/this.target.offsetHeight)),f=this.controls.place.offsetHeight*(this.target.scrollTop/c)+"px";return{mul:c/this.target.offsetHeight,height:e>b?b+"px":e+"px",top:f}},MiniScroll.prototype.draw=function(){var a=document.createElement("div"),b=document.createElement("div");a.className="scroll-place",b.className="scroll",a.appendChild(b),a.id=this.identity,this.controls.place=a,this.controls.scroll=b,this.target.insertBefore(a,this.target.querySelector("*")),this.scrollUpdate()},MiniScroll.prototype.render=function(a){for(var b=0;b<this.animation.stack.length;b++){var c=this.animation.stack[b],d=parseInt(c.target);c.element.style[c.prop]=d+c.points}};

And initialize:

<body onload="new MiniScroll(this);"></body>

And customize:

.scroll-place { // ... // }
.scroll { // ... // }

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

You may get ORA-01031: insufficient privileges instead of ORA-00942: table or view does not exist when you have at least one privilege on the table, but not the necessary privilege.

Create schemas

SQL> create user schemaA identified by schemaA;

User created.

SQL> create user schemaB identified by schemaB;

User created.

SQL> create user test_user identified by test_user;

User created.

SQL> grant connect to test_user;

Grant succeeded.

Create objects and privileges

It is unusual, but possible, to grant a schema a privilege like DELETE without granting SELECT.

SQL> create table schemaA.table1(a number);

Table created.

SQL> create table schemaB.table2(a number);

Table created.

SQL> grant delete on schemaB.table2 to test_user;

Grant succeeded.

Connect as TEST_USER and try to query the tables

This shows that having some privilege on the table changes the error message.

SQL> select * from schemaA.table1;
select * from schemaA.table1
                      *
ERROR at line 1:
ORA-00942: table or view does not exist


SQL> select * from schemaB.table2;
select * from schemaB.table2
                      *
ERROR at line 1:
ORA-01031: insufficient privileges


SQL>

Can the Android layout folder contain subfolders?

You CAN do this with gradle. I've made a demo project showing how.

The trick is to use gradle's ability to merge multiple resource folders, and set the res folder as well as the nested subfolders in the sourceSets block.

The quirk is that you can't declare a container resource folder before you declare that folder's child resource folders.

Below is the sourceSets block from the build.gradle file from the demo. Notice that the subfolders are declared first.

sourceSets {
    main {
        res.srcDirs =
        [
                'src/main/res/layouts/layouts_category2',
                'src/main/res/layouts',
                'src/main/res'
        ]
    }
}

nested resources picture

Also, the direct parent of your actual resource files (pngs, xml layouts, etc..) does still need to correspond with the specification.

Regular expressions inside SQL Server

In order to match a digit, you can use [0-9].

So you could use 5[0-9][0-9][0-9][0-9][0-9][0-9] and [0-9][0-9][0-9][0-9]7[0-9][0-9][0-9]. I do this a lot for zip codes.

Converting dict to OrderedDict

Use dict.items(); it can be as simple as following:

ship = collections.OrderedDict(ship.items())

cancelling a handler.postdelayed process

Another way is to handle the Runnable itself:

Runnable r = new Runnable {
    public void run() {
        if (booleanCancelMember != false) {
            //do what you need
        }
    }
}

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Technically redirect should be used either if we need to transfer control to different domain or to achieve separation of task.

For example in the payment application we do the PaymentProcess first and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PaymentProcess will not be repeated. But if we use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.

For other scenarios, forward is efficient to use since as it is faster than sendRedirect

How to remove application from app listings on Android Developer Console

you can remove an App from the store or "Unpublish" by clicking a tiny label bellow your app's title, right side of the "PUBLISHED" green status label.

enter image description here

Works even if your app was live (published) for long time, mine was.

Regards.

While variable is not defined - wait

You could have Flash call the function when it's done. I'm not sure what you mean by web services. I assume you have JavaScript code calling web services via Ajax, in which case you would know when they terminate. In the worst case, you could do a looping setTimeout that would check every 100 ms or so.

And the check for whether or not a variable is defined can be just if (myVariable) or safer: if(typeof myVariable == "undefined")

Hibernate Union alternatives

I have to agree with Vladimir. I too looked into using UNION in HQL and couldn't find a way around it. The odd thing was that I could find (in the Hibernate FAQ) that UNION is unsupported, bug reports pertaining to UNION marked 'fixed', newsgroups of people saying that the statements would be truncated at UNION, and other newsgroups of people reporting it works fine... After a day of mucking with it, I ended up porting my HQL back to plain SQL, but doing it in a View in the database would be a good option. In my case, parts of the query were dynamically generated, so I had to build the SQL in the code instead.

How to return a result (startActivityForResult) from a TabHost Activity?

Intent.FLAG_ACTIVITY_FORWARD_RESULT?

If set and this intent is being used to launch a new activity from an existing one, then the reply target of the existing activity will be transfered to the new activity.

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

In C++, there is no difference in main() and main(void).

But in C, main() will be called with any number of parameters.

Example:

main ( ){
    main(10,"abc",12.28);
    //Works fine !
    //It won't give the error. The code will compile successfully.
    //(May cause Segmentation fault when run)
}

main(void) will be called without any parameters. If we try to pass then this end up leading to a compiler error.

Example:

main (void) {
     main(10,"abc",12.13);
     //This throws "error: too many arguments to function ‘main’ "
}

How to attach a process in gdb

Try one of these:

gdb -p 12271
gdb /path/to/exe 12271

gdb /path/to/exe
(gdb) attach 12271

What are .iml files in Android Studio?

Add .idea and *.iml to .gitignore, you don't need those files to successfully import and compile the project.

scp with port number specified

One additional hint. Place the '-P' option after the scp command, no matter whether the machine you are ssh-ing into is the second one (aka destination). Example:

scp -P 2222 /absolute_path/source-folder/some-file [email protected]:/absolute_path/destination-folder

Equivalent of LIMIT and OFFSET for SQL Server?

The equivalent of LIMIT is SET ROWCOUNT, but if you want generic pagination it's better to write a query like this:

;WITH Results_CTE AS
(
    SELECT
        Col1, Col2, ...,
        ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
    FROM Table
    WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit

The advantage here is the parameterization of the offset and limit in case you decide to change your paging options (or allow the user to do so).

Note: the @Offset parameter should use one-based indexing for this rather than the normal zero-based indexing.

What is %2C in a URL?

Simple & Easy answer,

The %2C means , comma in URL. when you add the String "abc,defg" in the url as parameter then that comma in the string which is abc , defg is changed to abc%2Cdefg .There is no need to worry about it.

How to read data From *.CSV file using javascript?

I am using d3.js for parsing csv file. Very easy to use. Here is the docs.

Steps:

  • npm install d3-request

Using Es6;

import { csv } from 'd3-request';
import url from 'path/to/data.csv';

csv(url, function(err, data) {
 console.log(data);
})

Please see docs for more.

Update - d3-request is deprecated. you can use d3-fetch

How to grant "grant create session" privilege?

You can grant system privileges with or without the admin option. The default being without admin option.

GRANT CREATE SESSION TO username

or with admin option:

GRANT CREATE SESSION TO username WITH ADMIN OPTION

The Grantee with the ADMIN OPTION can grant and revoke privileges to other users

Using PowerShell to remove lines from a text file if it contains a string

The pipe character | has a special meaning in regular expressions. a|b means "match either a or b". If you want to match a literal | character, you need to escape it:

... | Select-String -Pattern 'H\|159' -NotMatch | ...

Fake "click" to activate an onclick method

You can also try getting the element's onclick attribute and then passing into eval. This should work despite the big taboo over eval. I put a sample below

eval(document.getElementById('elementId').getAttribute('onclick'));

How to use XPath contains() here?

You are only looking at the first li child in the query you have instead of looking for any li child element that may contain the text, 'Model'. What you need is a query like the following:

//ul[@class='featureList' and ./li[contains(.,'Model')]]

This query will give you the elements that have a class of featureList with one or more li children that contain the text, 'Model'.

How do I use IValidatableObject?

The thing i don't like about iValidate is it seems to only run AFTER all other validation.
Additionally, at least in our site, it would run again during a save attempt. I would suggest you simply create a function and place all your validation code in that. Alternately for websites, you could have your "special" validation in the controller after the model is created. Example:

 public ActionResult Update([DataSourceRequest] DataSourceRequest request, [Bind(Exclude = "Terminal")] Driver driver)
    {

        if (db.Drivers.Where(m => m.IDNumber == driver.IDNumber && m.ID != driver.ID).Any())
        {
            ModelState.AddModelError("Update", string.Format("ID # '{0}' is already in use", driver.IDNumber));
        }
        if (db.Drivers.Where(d => d.CarrierID == driver.CarrierID
                                && d.FirstName.Equals(driver.FirstName, StringComparison.CurrentCultureIgnoreCase)
                                && d.LastName.Equals(driver.LastName, StringComparison.CurrentCultureIgnoreCase)
                                && (driver.ID == 0 || d.ID != driver.ID)).Any())
        {
            ModelState.AddModelError("Update", "Driver already exists for this carrier");
        }

        if (ModelState.IsValid)
        {
            try
            {

How can I reuse a navigation bar on multiple pages?

This is what helped me. My navigation bar is in the body tag. Entire code for navigation bar is in nav.html file (without any html or body tag, only the code for navigation bar). In the target page, this goes in the head tag:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

Then in the body tag, a container is made with an unique id and a javascript block to load the nav.html into the container, as follows:

<!--Navigation bar-->
<div id="nav-placeholder">

</div>

<script>
$(function(){
  $("#nav-placeholder").load("nav.html");
});
</script>
<!--end of Navigation bar-->

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

If you want to style the output of a data frame in a jupyter notebook cell, you can set the display style on a per-dataframe basis:

df = pd.DataFrame({'A': np.random.randn(4)*1e7})
df.style.format("{:.1f}")

enter image description here

See the documentation here.

JSON Post with Customized HTTPHeader Field

if one wants to use .post() then this will set headers for all future request made with jquery

$.ajaxSetup({
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
});

then make your .post() calls as normal.

How do you fadeIn and animate at the same time?

Another way to do simultaneous animations if you want to call them separately (eg. from different code) is to use queue. Again, as with Tinister's answer you would have to use animate for this and not fadeIn:

$('.tooltip').css('opacity', 0);
$('.tooltip').show();
...

$('.tooltip').animate({opacity: 1}, {queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

Apple's Technical Q&A QA1509 shows the following simple approach:

CFDataRef CopyImagePixels(CGImageRef inImage)
{
    return CGDataProviderCopyData(CGImageGetDataProvider(inImage));
}

Use CFDataGetBytePtr to get to the actual bytes (and various CGImageGet* methods to understand how to interpret them).