Programs & Examples On #Weakhashmap

A special data structure in Java, a WeakHashMap is a hashtable-based Map with weak keys, meaning when a key has been discarded its entry is effectively removed from the map.

Java time-based map/cache with expiring keys

Yes. Google Collections, or Guava as it is named now has something called MapMaker which can do exactly that.

ConcurrentMap<Key, Graph> graphs = new MapMaker()
   .concurrencyLevel(4)
   .softKeys()
   .weakValues()
   .maximumSize(10000)
   .expiration(10, TimeUnit.MINUTES)
   .makeComputingMap(
       new Function<Key, Graph>() {
         public Graph apply(Key key) {
           return createExpensiveGraph(key);
         }
       });

Update:

As of guava 10.0 (released September 28, 2011) many of these MapMaker methods have been deprecated in favour of the new CacheBuilder:

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
    .maximumSize(10000)
    .expireAfterWrite(10, TimeUnit.MINUTES)
    .build(
        new CacheLoader<Key, Graph>() {
          public Graph load(Key key) throws AnyException {
            return createExpensiveGraph(key);
          }
        });

Open application after clicking on Notification

public void addNotification()
{
    NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(MainActivity.this);
    mBuilder.setSmallIcon(R.drawable.email);
    mBuilder.setContentTitle("Notification Alert, Click Me!");
    mBuilder.setContentText("Hi,This notification for you let me check");
    Intent notificationIntent = new Intent(this,MainActivity.class);
    PendingIntent conPendingIntent = PendingIntent.getActivity(this,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(conPendingIntent);

    NotificationManager manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(0,mBuilder.build());
    Toast.makeText(MainActivity.this, "Notification", Toast.LENGTH_SHORT).show();

}

Extracting hours from a DateTime (SQL Server 2005)

The DATEPART() function is used to return a single part of a date/time, such as year, month, day, hour, minute, etc.

datepart    ***Abbreviation

year        ***yy, yyyy 
quarter     ***qq, q 
month       ***mm, m 
dayofyear   ***dy, y 
day         ***dd, d 
week        ***wk, ww 
weekday     ***dw, w 
hour        ***hh 
minute      ***mi, n 
second      ***ss, s 
millisecond ***ms 
microsecond ***mcs 
nanosecond  ***ns 

Example

select * 
from table001
where datepart(hh,datetime) like 23

How do I run a command on an already existing Docker container?

I would like to note that the top answer is a little misleading.

The issue with executing docker run is that a new container is created every time. However, there are cases where we would like to revisit old containers or not take up space with new containers.

(Given clever_bardeen is the name of the container created...)

In OP's case, make sure the docker image is first running by executing the following command:

docker start clever_bardeen

Then, execute the docker container using the following command:

docker exec -it clever_bardeen /bin/bash

How do I evenly add space between a label and the input field regardless of length of text?

You can also used below code

<html>
<head>
    <style>
        .labelClass{
            float: left;
            width: 113px;
        }
    </style>
</head>
<body>
  <form action="yourclassName.jsp">
    <span class="labelClass">First name: </span><input type="text" name="fname"><br>
    <span class="labelClass">Last name: </span><input type="text" name="lname"><br>
    <input type="submit" value="Submit">
  </form>
</body>
</html>

Environment variables for java installation

For deployment better to set up classpath exactly and keep environment clear. Or at *.bat (the same for linux, but with correct variables symbols):

CLASSPATH="c:\lib;d:\temp\test.jar;<long classpath>"
CLASSPATH=%CLASSPATH%;"<another_logical_droup_of_classpath" 
java -cp %CLASSPATH% com.test.MainCLass

Or at command line or *.bat (for *.sh too) if classpath id not very long:

java -cp "c:\lib;d:\temp\test.jar;<short classpath>"

How to add dll in c# project

The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.

I usually create a libs folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.

(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)

PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...

Call a child class method from a parent class object

Why don't you just write an empty method in Person and override it in the children classes? And call it, when it needs to be:

void caluculate(Person p){
  p.dotheCalculate();
}

This would mean you have to have the same method in both children classes, but i don't see why this would be a problem at all.

CSS3 transition doesn't work with display property

You cannot use height: 0 and height: auto to transition the height. auto is always relative and cannot be transitioned towards. You could however use max-height: 0 and transition that to max-height: 9999px for example.

Sorry I couldn't comment, my rep isn't high enough...

Mathematical functions in Swift

For the Swift way of doing things, you can try and make use of the tools available in the Swift Standard Library. These should work on any platform that is able to run Swift.

Instead of floor(), round() and the rest of the rounding routines you can use rounded(_:):

let x = 6.5

// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"

// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"

// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"

// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"

These are currently available on Float and Double and it should be easy enough to convert to a CGFloat for example.

Instead of sqrt() there's the squareRoot() method on the FloatingPoint protocol. Again, both Float and Double conform to the FloatingPoint protocol:

let x = 4.0
let y = x.squareRoot()

For the trigonometric functions, the standard library can't help, so you're best off importing Darwin on the Apple platforms or Glibc on Linux. Fingers-crossed they'll be a neater way in the future.

#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif

let x = 1.571
print(sin(x))
// Prints "~1.0"

What is aria-label and how should I use it?

Prerequisite:

Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control

Aria does not change anything visually. (Aria is scared of designers too).

aria-label

aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users

How To Use:

<input type="edit" aria-label="search" placeholder="search">

There is no visual change in application. But screen readers can understand the purpose of control

aria-labelledby

Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually

Approach 1:

<span id="sd">Search</span>

<input type="text" aria-labelledby="sd">

Approach 2:

aria-labelledby can also be used to combine two labels for screen reader users

<span id="de">Billing Address</span>

<span id="sd">First Name</span>

<input type="text" aria-labelledby="de sd">

CSS scale height to match width - possibly with a formfactor

For this, you will need to utilise JavaScript, or rely on the somewhat supported calc() CSS expression.

window.addEventListener("resize", function(e) {
    var mapElement = document.getElementById("map");
    mapElement.style.height = mapElement.offsetWidth * 1.72;
});

Or using CSS calc (see support here: http://caniuse.com/calc)

#map {
    width: 100%;
    height: calc(100vw * 1.72)
}

Annotation-specified bean name conflicts with existing, non-compatible bean def

I had a similar problem, and it was because one of my beans had been moved to another directory recently. I needed to do a "build clean" by deleting the build/classes/java directory and the problem went away. (The error message had the two different file paths conflicting with each other, although I knew one should not actually exist anymore.)

How can I show a hidden div when a select option is selected?

Check this code. It awesome code for hide div using select item.

HTML

<select name="name" id="cboOptions" onchange="showDiv('div',this)" class="form-control" >
    <option value="1">YES</option>
    <option value="2">NO</option>
</select>

<div id="div1" style="display:block;">
    <input type="text" id="customerName" class="form-control" placeholder="Type Customer Name...">
    <input type="text" style="margin-top: 3px;" id="customerAddress" class="form-control" placeholder="Type Customer Address...">
    <input type="text" style="margin-top: 3px;" id="customerMobile" class="form-control" placeholder="Type Customer Mobile...">
</div>
<div id="div2" style="display:none;">
    <input type="text" list="cars" id="customerID" class="form-control" placeholder="Type Customer Name...">
    <datalist id="cars">
        <option>Value 1</option>
        <option>Value 2</option>
        <option>Value 3</option>
        <option>Value 4</option>
    </datalist>
</div>

JS

<script>
    function showDiv(prefix,chooser) 
    {
            for(var i=0;i<chooser.options.length;i++) 
            {
                var div = document.getElementById(prefix+chooser.options[i].value);
                div.style.display = 'none';
            }

            var selectedOption = (chooser.options[chooser.selectedIndex].value);

            if(selectedOption == "1")
            {
                displayDiv(prefix,"1");
            }
            if(selectedOption == "2")
            {
                displayDiv(prefix,"2");
            }
    }

    function displayDiv(prefix,suffix) 
    {
            var div = document.getElementById(prefix+suffix);
            div.style.display = 'block';
    }
</script>

What is the total amount of public IPv4 addresses?

Public IP Addresses

https://github.com/stephenlb/geo-ip will generate a list of Valid IP Public Addresses including Localities.

'1.0.0.0/8' to '191.0.0.0/8' are the valid public IP Address range exclusive of the reserved Private IP Addresses as follows:

import iptools
## Private IP Addresses
private_ips = iptools.IpRangeList(
    '0.0.0.0/8',      '10.0.0.0/8',     '100.64.0.0/10', '127.0.0.0/8',
    '169.254.0.0/16', '172.16.0.0/12',  '192.0.0.0/24',  '192.0.2.0/24',
    '192.88.99.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24',
    '203.0.113.0/24', '224.0.0.0/4',    '240.0.0.0/4',   '255.255.255.255/32'
)

IP Generator

Generates a JSON dump of IP Addresses and associated Geo information. Note that the valid public IP Address range is from '1.0.0.0/8' to '191.0.0.0/8' excluding the reserved Private IP Address ranges shown lower down in this readme.

docker build -t geo-ip .
docker run -e IPRANGE='54.0.0.0/30' geo-ip               ## a few IPs
docker run -e IPRANGE='54.0.0.0/26' geo-ip               ## a few more IPs
docker run -e IPRANGE='54.0.0.0/16' geo-ip               ## a lot more IPs
docker run -e IPRANGE='0.0.0.0/0'   geo-ip               ## ALL IPs ( slooooowwwwww )
docker run -e IPRANGE='0.0.0.0/0'   geo-ip > geo-ip.json ## ALL IPs saved to JSON File
docker run geo-ip 

A little faster option for scanning all valid public addresses:

for i in $(seq 1 191); do \
    docker run -e IPRANGE="$i.0.0.0/8" geo-ip; \
    sleep 1; \ 
done

This prints less than 4,228,250,625 JSON lines to STDOUT. Here is an example of one of the lines:

{"city": "Palo Alto", "ip": "0.0.0.0", "longitude": -122.1274,
 "continent": "North America", "continent_code": "NA",
 "state": "California", "country": "United States", "latitude": 37.418,
 "iso_code": "US", "state_code": "CA", "aso": "PubNub",
 "asn": "11404", "zip_code": "94107"}

Private and Reserved IP Range

The dockerfile in the repo above will exclude non-usable IP addresses following the guide from the wikipedia article: https://en.wikipedia.org/wiki/Reserved_IP_addresses

MaxMind Geo IP

The dockerfile imports a free public Database provided by https://www.maxmind.com/en/home

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

Convert datatable to JSON in C#

Convert datatable to JSON using C#.net

 public static object DataTableToJSON(DataTable table)
    {
        var list = new List<Dictionary<string, object>>();

        foreach (DataRow row in table.Rows)
        {
            var dict = new Dictionary<string, object>();

            foreach (DataColumn col in table.Columns)
            {
                dict[col.ColumnName] = (Convert.ToString(row[col]));
            }
            list.Add(dict);
        }
        JavaScriptSerializer serializer = new JavaScriptSerializer();

        return serializer.Serialize(list);
    }

Set value of textarea in jQuery

Just use this code and you will always have the value:

var t = $(this); var v = t.val() || t.html() || t.text();

So it will check val() and set its value. If val() gets an empty string, NULL, NaN o.s. it will check for html() and then for text()...

How to read a large file line by line?

This how I manage with very big file (tested with up to 100G). And it's faster than fgets()

$block =1024*1024;//1MB or counld be any higher than HDD block_size*2
if ($fh = fopen("file.txt", "r")) { 
    $left='';
    while (!feof($fh)) {// read the file
       $temp = fread($fh, $block);  
       $fgetslines = explode("\n",$temp);
       $fgetslines[0]=$left.$fgetslines[0];
       if(!feof($fh) )$left = array_pop($lines);           
       foreach ($fgetslines as $k => $line) {
           //do smth with $line
        }
     }
}
fclose($fh);

Declaring a boolean in JavaScript using just var

Variables in Javascript don't have a type. Non-zero, non-null, non-empty and true are "true". Zero, null, undefined, empty string and false are "false".

There's a Boolean type though, as are literals true and false.

How to take a screenshot programmatically on iOS

See this post it looks like you can use UIGetScreenImage() for now.

How to set up java logging using a properties file? (java.util.logging)

Okay, first intuition is here:

handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler
.level = ALL

The Java prop file parser isn't all that smart, I'm not sure it'll handle this. But I'll go look at the docs again....

In the mean time, try:

handlers = java.util.logging.FileHandler
java.util.logging.ConsoleHandler.level = ALL

Update

No, duh, needed more coffee. Nevermind.

While I think more, note that you can use the methods in Properties to load and print a prop-file: it might be worth writing a minimal program to see what java thinks it reads in that file.


Another update

This line:

    FileInputStream configFile = new FileInputStream("/path/to/app.properties"));

has an extra end-paren. It won't compile. Make sure you're working with the class file you think you are.

How can I print using JQuery

Hey If you want to print selected area or div ,Try This.

<style type="text/css">
@media print
{
body * { visibility: hidden; }
.div2 * { visibility: visible; }
.div2 { position: absolute; top: 40px; left: 30px; }
}
</style>

Hope it helps you

how to avoid a new line with p tag?

something like:

p
{
    display:inline;
}

in your stylesheet would do it for all p tags.

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Yes, it's possible, the syntax is curl [protocol://]<host>[:port], for example:

curl example.com:1234

If you're using Bash, you can also use pseudo-device /dev files to open a TCP connection, e.g.:

exec 5<>/dev/tcp/127.0.0.1/1234
echo "send some stuff" >&5
cat <&5 # Receive some stuff.

See also: More on Using Bash's Built-in /dev/tcp File (TCP/IP).

Convert Xml to DataTable

Maybe this could be a little older article. but must of the above answers don´t help me as I need. Then I wrote a little snippet for that.

This accepts any XML that hast at least 3 levels (Like this sample):

<XmlData>
    <XmlRow>
        <XmlField1>Data 1</XmlField1>  
        <XmlField2>Data 2</XmlField2>  
        <XmlField3>Data 3</XmlField3>  
        .......
    </XmlRow>
</XmlData>

public static class XmlParser
{
    /// <summary>
    /// Converts XML string to DataTable
    /// </summary>
    /// <param name="Name">DataTable name</param>
    /// <param name="XMLString">XML string</param>
    /// <returns></returns>
    public static DataTable BuildDataTableFromXml(string Name, string XMLString)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(new StringReader(XMLString));
        DataTable Dt = new DataTable(Name);
        try
        {

            XmlNode NodoEstructura = doc.FirstChild.FirstChild;
            //  Table structure (columns definition) 
            foreach (XmlNode columna in NodoEstructura.ChildNodes)
            {
                Dt.Columns.Add(columna.Name, typeof(String));
            }

            XmlNode Filas = doc.FirstChild;
            //  Data Rows 
            foreach (XmlNode Fila in Filas.ChildNodes)
            {
                List<string> Valores = new List<string>();
                foreach (XmlNode Columna in Fila.ChildNodes)
                {
                    Valores.Add(Columna.InnerText);
                }
                Dt.Rows.Add(Valores.ToArray());
            }
        } catch(Exception)
        {

        }

        return Dt;
    }
}

This solve my problem

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

They key thing to remember is 'origin' is not the value you may need to be using... it worked for me when I replaced 'origin' with repo's name.

How do I format axis number format to thousands with a comma in matplotlib?

Short answer without importing matplotlib as mpl

plt.gca().yaxis.set_major_formatter(plt.matplotlib.ticker.StrMethodFormatter('{x:,.0f}'))

Modified from @AlexG's answer

What is the OR operator in an IF statement

Just for completeness, the || and && are the conditional version of the | and & operators.

A reference to the ECMA C# Language specification is here.

From the specification:

3 The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is false.

In the | version both sides are evaluated.

The conditional version short circuits evaluation and so allows for code like:

if (x == null || x.Value == 5)
    // Do something 

Or (no pun intended) using your example:

if (title == "User greeting" || title == "User name") 
    // {do stuff} 

How do you make an element "flash" in jQuery

Like fadein / fadeout you could use animate css / delay

$(this).stop(true, true).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100);

Simple and flexible

How to check if Receiver is registered in Android?

i put this code in my parent activity

List registeredReceivers = new ArrayList<>();

@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
    registeredReceivers.add(System.identityHashCode(receiver));
    return super.registerReceiver(receiver, filter);
}

@Override
public void unregisterReceiver(BroadcastReceiver receiver) {
    if(registeredReceivers.contains(System.identityHashCode(receiver)))
    super.unregisterReceiver(receiver);
}

How to use Bootstrap in an Angular project?

just check your package.json file and add dependencies for bootstrap

"dependencies": {

   "bootstrap": "^3.3.7",
}

then add below code on .angular-cli.json file

 "styles": [
    "styles.css",
    "../node_modules/bootstrap/dist/css/bootstrap.css"
  ],

Finally you just update your npm locally by using terminal

$ npm update

How do I convert speech to text?

.NET can do it with its System.Speech namespace.

You would have to convert to .wav first or capture the audio live from the mic.

Details on implementation can be found here: Transcribing Audio with .NET

Change the spacing of tick marks on the axis of a plot?

I have a data set with Time as the x-axis, and Intensity as y-axis. I'd need to first delete all the default axes except the axes' labels with:

plot(Time,Intensity,axes=F)

Then I rebuild the plot's elements with:

box() # create a wrap around the points plotted
axis(labels=NA,side=1,tck=-0.015,at=c(seq(from=0,to=1000,by=100))) # labels = NA prevents the creation of the numbers and tick marks, tck is how long the tick mark is.
axis(labels=NA,side=2,tck=-0.015)
axis(lwd=0,side=1,line=-0.4,at=c(seq(from=0,to=1000,by=100))) # lwd option sets the tick mark to 0 length because tck already takes care of the mark
axis(lwd=0,line=-0.4,side=2,las=1) # las changes the direction of the number labels to horizontal instead of vertical.

So, at = c(...) specifies the collection of positions to put the tick marks. Here I'd like to put the marks at 0, 100, 200,..., 1000. seq(from =...,to =...,by =...) gives me the choice of limits and the increments.

Location of sqlite database on the device

Do not hardcode path like //data/data/<Your-Application-Package-Name>/databases/<your-database-name>. Well it does work in most cases, but this one is not working in devices where device can support multiple users. The path can be like //data/user/10/<Your-Application-Package-Name>/databases/<your-database-name>. Possible solution to this is using context.getDatabasePath(<your-database-name>).

Get root password for Google Cloud Engine VM

Figured it out. The VM's in cloud engine don't come with a root password setup by default so you'll first need to change the password using

sudo passwd

If you do everything correctly, it should do something like this:

user@server[~]# sudo passwd
Changing password for user root.
New password: 
Retype new password: 
passwd: all authentication tokens updated successfully.

What is special about /dev/tty?

/dev/tty is a synonym for the controlling terminal (if any) of the current process. As jtl999 says, it's a character special file; that's what the c in the ls -l output means.

man 4 tty or man -s 4 tty should give you more information, or you can read the man page online here.

Incidentally, pwd > /dev/tty doesn't necessarily print to the shell's stdout (though it is the pwd command's standard output). If the shell's standard output has been redirected to something other than the terminal, /dev/tty still refers to the terminal.

You can also read from /dev/tty, which will normally read from the keyboard.

Getting all documents from one collection in Firestore

I prefer to hide all code complexity in my services... so, I generally use something like this:

In my events.service.ts

    async getEvents() {
        const snapchot = await this.db.collection('events').ref.get();
        return new Promise <Event[]> (resolve => {
            const v = snapchot.docs.map(x => {
                const obj = x.data();
                obj.id = x.id;
                return obj as Event;
            });
            resolve(v);
        });
    }

In my sth.page.ts

   myList: Event[];

   construct(private service: EventsService){}

   async ngOnInit() {
      this.myList = await this.service.getEvents();
   }

Enjoy :)

Difference between 2 dates in SQLite

If you want time in 00:00 format: I solved it like that:

select strftime('%H:%M',CAST ((julianday(FinishTime) - julianday(StartTime)) AS REAL),'12:00') from something

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

I've updated com.google.gms:google-services from 3.2.0 to 3.2.1 and the warning stopped appearing.

 buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.1'
        classpath 'com.google.gms:google-services:3.2.1'

    }
}

Entity Framework change connection at runtime

string _connString = "metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=localhost;initial catalog=DATABASE;persist security info=True;user id=sa;password=YourPassword;multipleactiveresultsets=True;App=EntityFramework&quot;";

EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder(_connString);
ctx = new Entities(_connString);

You can get the connection string from the web.config, and just set that in the EntityConnectionStringBuilder constructor, and use the EntityConnectionStringBuilder as an argument in the constructor for the context.

Cache the connection string by username. Simple example using a couple of generic methods to handle adding/retrieving from cache.

private static readonly ObjectCache cache = MemoryCache.Default;

// add to cache
AddToCache<string>(username, value);

// get from cache

 string value = GetFromCache<string>(username);
 if (value != null)
 {
     // got item, do something with it.
 }
 else
 {
    // item does not exist in cache.
 }


public void AddToCache<T>(string token, T item)
    {
        cache.Add(token, item, DateTime.Now.AddMinutes(1));
    }

public T GetFromCache<T>(string cacheKey) where T : class
    {
        try
        {
            return (T)cache[cacheKey];
        }
        catch
        {
            return null;
        }
    }

How do I make Git ignore file mode (chmod) changes?

By definining the following alias (in ~/.gitconfig) you can easily temporarily disable the fileMode per git command:

[alias]
nfm = "!f(){ git -c core.fileMode=false $@; };f"

When this alias is prefixed to the git command, the file mode changes won't show up with commands that would otherwise show them. For example:

git nfm status

How to install packages offline?

The pip download command lets you download packages without installing them:

pip download -r requirements.txt

(In previous versions of pip, this was spelled pip install --download -r requirements.txt.)

Then you can use pip install --no-index --find-links /path/to/download/dir/ -r requirements.txt to install those downloaded sdists, without accessing the network.

How to send 100,000 emails weekly?

People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.

Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.

Here's a summary of what we found...

AuthSMTP

  • Cheapest around
  • No analysis/reporting
  • No tracking for opens/clicks
  • Had slight hesitation on some sends

Postmark

  • Very cheap, but not as cheap as AuthSMTP
  • Beautiful cpanel but no tracking on opens/clicks
  • Send-level activity tracking so you can open a single email that was sent and look at how it looked and the delivery data.
  • Have to use API. Sending by SMTP was recently introduced but it's buggy. For instance, we noticed that quotes (") in the subject line are stripped.
  • Cannot send any attachment you want. Must be on approved list of file types and under a certain size. (10 MB I think)
  • Requires a set list of from names/addresses.

JangoSMTP

  • Expensive in relation to the others – more than 10 times in some cases
  • Ugly cpanel but great tracking on opens/clicks with email-level detail
  • Had hesitation, at times, when sending. On two occasions, sends took an hour to be delivered
  • Requires a set list of from name/addresses.

SendGrid

  • Not quite a cheap as AuthSMTP but still very cheap. Many customers can exist on 200 free sends per day.
  • Decent cpanel but no in-depth detail on open/click tracking
  • Lots of API options. Options (open/click tracking, etc) can be custom defined on an email-by-email basis. Inbound (reply) email can be posted to our HTTP end point.
  • Absolutely zero hesitation on sends. Every email sent landed in the inbox almost immediately.
  • Can send from any from name/address.

Conclusion

SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.

Can't import Numpy in Python

Have you installed it?

On debian/ubuntu:

aptitude install python-numpy

On windows:

http://sourceforge.net/projects/numpy/files/NumPy/

On other systems:

http://sourceforge.net/projects/numpy/files/NumPy/

$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

How to convert an enum type variable to a string?

Another late to the party, using the preprocessor:

 1  #define MY_ENUM_LIST \
 2      DEFINE_ENUM_ELEMENT(First) \
 3      DEFINE_ENUM_ELEMENT(Second) \
 4      DEFINE_ENUM_ELEMENT(Third) \
 5  
 6  //--------------------------------------
 7  #define DEFINE_ENUM_ELEMENT(name) , name
 8  enum MyEnum {
 9      Zeroth = 0
10      MY_ENUM_LIST
11  };
12  #undef DEFINE_ENUM_ELEMENT
13 
14  #define DEFINE_ENUM_ELEMENT(name) , #name
15  const char* MyEnumToString[] = {
16      "Zeroth"
17      MY_ENUM_LIST
18  };
19  #undef DEFINE_ENUM_ELEMENT
20
21  #define DEFINE_ENUM_ELEMENT(name) else if (strcmp(s, #name)==0) return name;
22  enum MyEnum StringToMyEnum(const char* s){
23      if (strcmp(s, "Zeroth")==0) return Zeroth;
24      MY_ENUM_LIST
25      return NULL;
26  }
27  #undef DEFINE_ENUM_ELEMENT

(I just put in line numbers so it's easier to talk about.) Lines 1-4 are what you edit to define the elements of the enum. (I have called it a "list macro", because it's a macro that makes a list of things. @Lundin informs me these are a well-known technique called X-macros.)

Line 7 defines the inner macro so as to fill in the actual enum declaration in lines 8-11. Line 12 undefines the inner macro (just to silence the compiler warning).

Line 14 defines the inner macro so as to create a string version of the enum element name. Then lines 15-18 generate an array that can convert an enum value to the corresponding string.

Lines 21-27 generate a function that converts a string to the enum value, or returns NULL if the string doesn't match any.

This is a little cumbersome in the way it handles the 0th element. I've actually worked around that in the past.

I admit this technique bothers people who don't want to think the preprocessor itself can be programmed to write code for you. I think it strongly illustrates the difference between readability and maintainability. The code is difficult to read, but if the enum has a few hundred elements, you can add, remove, or rearrange elements and still be sure the generated code has no errors.

How to scroll the window using JQuery $.scrollTo() function

Looks like you've got the syntax slightly wrong... I'm assuming based on your code that you're trying to scroll down 100px in 800ms, if so then this works (using scrollTo 1.4.1):

$.scrollTo('+=100px', 800, { axis:'y' });

Move div to new line

I've found that you can move div elements to the next line simply by setting the property Display: block;

On each div.

error: Error parsing XML: not well-formed (invalid token) ...?

It means there is a compilation error in your XML file, something that shouldn't be there: a spelling mistake/a spurious character/an incorrect namespace.

Your issue is you've got a semicolon that shouldn't be there after this line:

  android:text="@string/hello";

Windows 7 environment variable not working in path

My issue turned out to be embarrassingly simple:

Restart command prompt and the new variables should update

Watching variables contents in Eclipse IDE

You can add a watchpoint for each variable you're interested in.

A watchpoint is a special breakpoint that stops the execution of an application whenever the value of a given expression changes, without specifying where it might occur. Unlike breakpoints (which are line-specific), watchpoints are associated with files. They take effect whenever a specified condition is true, regardless of when or where it occurred. You can set a watchpoint on a global variable by highlighting the variable in the editor, or by selecting it in the Outline view.

Getting a list of values from a list of dicts

I think as simple as below would give you what you are looking for.

In[5]: ll = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}]
In[6]: ld = [d.get('value', None) for d in ll]
In[7]: ld
Out[7]: ['apple', 'banana', 'cars']

You can do this with a combination of map and lambda as well but list comprehension looks more elegant and pythonic.

For a smaller input list comprehension is way to go but if the input is really big then i guess generators are the ideal way.

In[11]: gd = (d.get('value', None) for d in ll)
In[12]: gd
Out[12]: <generator object <genexpr> at 0x7f5774568b10>
In[13]: '-'.join(gd)
Out[13]: 'apple-banana-cars'

Here is a comparison of all possible solutions for bigger input

 In[2]: l = [{'value': 'apple', 'blah': 2}, {'value': 'banana', 'blah': 3} , {'value': 'cars', 'blah':4}] * 9000000
In[3]: def gen_version():
  ...:     for i in l:
  ...:         yield i.get('value', None)
  ...: 
In[4]: def list_comp_verison():
  ...:     return [i.get('value', None) for i in l]
  ...: 
In[5]: def list_verison():
  ...:     ll = []
  ...:     for i in l:
  ...:         ll.append(i.get('value', None))
  ...:     return ll
In[10]: def map_lambda_version():
   ...:      m = map(lambda i:i.get('value', None), l)
   ...:      return m
   ...: 
In[11]: %timeit gen_version()
172 ns ± 0.393 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
In[12]: %timeit map_lambda_version()
203 ns ± 2.31 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In[13]: %timeit list_comp_verison()
1.61 s ± 20.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In[14]: %timeit list_verison()
2.29 s ± 4.58 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

As you can see, generators are a better solution in comparison to the others, map is also slower compared to generator for reason I will leave up to OP to figure out.

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

Convert MySQL to SQlite

Here is a list of converters. (snapshot at archive.today)


An alternative method that would work even on windows but is rarely mentioned is: use an ORM class that abstracts specific database differences away for you. e.g. you get these in PHP (RedBean), Python (Django's ORM layer, Storm, SqlAlchemy), Ruby on Rails (ActiveRecord), Cocoa (CoreData) etc.

i.e. you could do this:

  1. Load data from source database using the ORM class.
  2. Store data in memory or serialize to disk.
  3. Store data into destination database using the ORM class.

Close Bootstrap Modal

In some circumstances typing error could be the culprit. For instance, make sure you have:

data-dismiss="modal"

and not

data-dissmiss="modal"

Notice the double "ss" in the second example that will cause the Close button that fail.

Getting rid of bullet points from <ul>

I had an identical problem.

The solution was that the bullet was added via a background image, NOT via list-style-type. A quick 'background: none' and Bob's your uncle!

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I in no way want to compete with Mark's answer, but just wanted to highlight the piece that finally made everything click as someone new to Javascript inheritance and its prototype chain.

Only property reads search the prototype chain, not writes. So when you set

myObject.prop = '123';

It doesn't look up the chain, but when you set

myObject.myThing.prop = '123';

there's a subtle read going on within that write operation that tries to look up myThing before writing to its prop. So that's why writing to object.properties from the child gets at the parent's objects.

How to calculate the median of an array?

I was looking at the same statistics problems. The approach you are thinking it is good and it will work. (Answer to the sorting has been given)

But in case you are interested in algorithm performance, I think there are a couple of algorithms that have better performance than just sorting the array, one (QuickSelect) is indicated by @bruce-feist's answer and is very well explained.

[Java implementation: https://discuss.leetcode.com/topic/14611/java-quick-select ]

But there is a variation of this algorithm named median of medians, you can find a good explanation on this link: http://austinrochford.com/posts/2013-10-28-median-of-medians.html

Java implementation of this: - https://stackoverflow.com/a/27719796/957979

Time complexity of nested for-loop

On the 1st iteration of the outer loop (i = 1), the inner loop will iterate 1 times On the 2nd iteration of the outer loop (i = 2), the inner loop will iterate 2 time On the 3rd iteration of the outer loop (i = 3), the inner loop will iterate 3 times
.
.
On the FINAL iteration of the outer loop (i = n), the inner loop will iterate n times

So, the total number of times the statements in the inner loop will be executed will be equal to the sum of the integers from 1 to n, which is:

((n)*n) / 2 = (n^2)/2 = O(n^2) times 

Update a submodule to the latest commit

None of the above answers worked for me.

This was the solution, from the parent directory run:

git submodule update --init;
cd submodule-directory;
git pull;
cd ..;
git add submodule-directory;

now you can git commit and git push

JavaScript naming conventions

You can follow this Google JavaScript Style Guide

In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.

EDIT: See nice collection of JavaScript Style Guides And Beautifiers.

Are members of a C++ struct initialized to 0 by default?

I believe the correct answer is that their values are undefined. Often, they are initialized to 0 when running debug versions of the code. This is usually not the case when running release versions.

Detecting when user scrolls to bottom of div with jQuery

not sure if it is any help but this is how I do it.

I have an index panel that is larger that the window and I let it scroll until the end this index is reached. Then I fix it in position. The process is reversed once you scroll toward the top of the page.

Regards.

<style type="text/css">
    .fixed_Bot {    
            position: fixed;     
            bottom: 24px;    
        }     
</style>

<script type="text/javascript">
    $(document).ready(function () {
        var sidebarheight = $('#index').height();
        var windowheight = $(window).height();


        $(window).scroll(function () {
            var scrollTop = $(window).scrollTop();

            if (scrollTop >= sidebarheight - windowheight){
                $('#index').addClass('fixed_Bot');
            }
            else {
                $('#index').removeClass('fixed_Bot');
            }                   
        });
    });

</script>

ElasticSearch - Return Unique Values

I am looking for this kind of solution for my self as well. I found reference in terms aggregation.

So, according to that following is the proper solution.

{
"aggs" : {
    "langs" : {
        "terms" : { "field" : "language",  
                    "size" : 500 }
    }
}}

But if you ran into following error:

"error": {
        "root_cause": [
            {
                "type": "illegal_argument_exception",
                "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [fastest_method] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead."
            }
        ]}

In that case, you have to add "KEYWORD" in the request, like following:

   {
    "aggs" : {
        "langs" : {
            "terms" : { "field" : "language.keyword",  
                        "size" : 500 }
        }
    }}

is the + operator less performant than StringBuffer.append()

Your example is not a good one in that it is very unlikely that the performance will be signficantly different. In your example readability should trump performance because the performance gain of one vs the other is negligable. The benefits of an array (StringBuffer) are only apparent when you are doing many concatentations. Even then your mileage can very depending on your browser.

Here is a detailed performance analysis that shows performance using all the different JavaScript concatenation methods across many different browsers; String Performance an Analysis

join() once, concat() once, join() for, += for, concat() for

More:
Ajaxian >> String Performance in IE: Array.join vs += continued

Should I use <i> tag for icons instead of <span>?

I thought this looked pretty bad - because I was working on a Joomla template recently and I kept getting the template failing W3C because it was using the <i> tag and that had deprecated, as it's original use was to italicize something, which is now done through CSS not HTML any more.

It does make really bad practice because when I saw it I went through the template and changed all the <i> tags to <span style="font-style:italic"> instead and then wondered why the entire template looked strange.

This is the main reason it is a bad idea to use the <i> tag in this way - you never know who is going to look at your work afterwards and "assume" that what you were really trying to do is italicize the text rather than display an icon. I've just put some icons in a website and I did it with the following code

<img class="icon" src="electricity.jpg" alt="Electricity" title="Electricity">

that way I've got all my icons in one class so any changes I make affects all the icons (say I wanted them larger or smaller, or rounded borders, etc), the alt text gives screen readers the chance to tell the person what the icon is rather than possibly getting just "text in italics, end of italics" (I don't exactly know how screen readers read screens but I guess it's something like that), and the title also gives the user a chance to mouse over the image and get a tooltip telling them what the icon is in case they can't figure it out. Much better than using <i> - and also it passes W3C standard.

SVN Repository Search

theres krugle and koders but both are expensive. Both have ide plugins for eclipse.

Get commit list between tags in git

FYI:

git log tagA...tagB

provides standard log output in a range.

Find a value in DataTable

A DataTable or DataSet object will have a Select Method that will return a DataRow array of results based on the query passed in as it's parameter.

Looking at your requirement your filterexpression will have to be somewhat general to make this work.

myDataTable.Select("columnName1 like '%" + value + "%'");

Connect HTML page with SQL server using javascript

<script>
var name=document.getElementById("name").value;
var address= document.getElementById("address").value;
var age= document.getElementById("age").value;

$.ajax({
      type:"GET",
      url:"http://hostname/projectfolder/webservicename.php?callback=jsondata&web_name="+name+"&web_address="+address+"&web_age="+age,
      crossDomain:true,
      dataType:'jsonp',
      success: function jsondata(data)
           {

            var parsedata=JSON.parse(JSON.stringify(data));
            var logindata=parsedata["Status"];

            if("sucess"==logindata)
            {   
                alert("success");
            }
            else
            {
                alert("failed");
            }
          }  
    }); 
<script>

You need to use web services. In the above code I have php web service to be used which has a callback function which is optional. Assuming you know HTML5 I did not post the html code. In the url you can send the details to the web server.

How to delete a module in Android Studio

Remove from File > File Structure > Dependencies > - button. Then if it is stull there you can remove the module by going to the settings.gradle file and removing it from the include line.

Why use pip over easy_install?

Two reasons, there may be more:

  1. pip provides an uninstall command

  2. if an installation fails in the middle, pip will leave you in a clean state.

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

You can also do

t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')

as in the Ruby on Rails API.

Converting a byte array to PNG/JPG

There are two problems with this question:

Assuming you have a gray scale bitmap, you have two factors to consider:

  1. For JPGS... what loss of quality is tolerable?
  2. For pngs... what level of compression is tolerable? (Although for most things I've seen, you don't have that much of a choice, so this choice might be negligible.) For anybody thinking this question doesn't make sense: yes, you can change the amount of compression/number of passes attempted to compress; check out either Ifranview or some of it's plugins.

Answer those questions, and then you might be able to find your original answer.

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

Either decorate your root entity with the XmlRoot attribute which will be used at compile time.

[XmlRoot(Namespace = "www.contoso.com", ElementName = "MyGroupName", DataType = "string", IsNullable=true)]

Or specify the root attribute when de serializing at runtime.

XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "user";
// xRoot.Namespace = "http://www.cpandl.com";
xRoot.IsNullable = true;

XmlSerializer xs = new XmlSerializer(typeof(User),xRoot);

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

Xamarin.Android

Note: The path xml/provider_paths.xml (.axml) couldn't be resolved, even after making the xml folder under Resources (maybe it can be put in an existing location like Values, didn't try), so I resorted to this which works for now. Testing showed that it only needs to be called once per application run (which makes sense being that it changes the operational state of the host VM).

Note: xml needs to be capitalized, so Resources/Xml/provider_paths.xml

Java.Lang.ClassLoader cl = _this.Context.ClassLoader;
Java.Lang.Class strictMode = cl.LoadClass("android.os.StrictMode");                
System.IntPtr ptrStrictMode = JNIEnv.FindClass("android/os/StrictMode");
var method = JNIEnv.GetStaticMethodID(ptrStrictMode, "disableDeathOnFileUriExposure", "()V");                
JNIEnv.CallStaticVoidMethod(strictMode.Handle, method);

How to center Font Awesome icons horizontally?

Since you don't want to add a class to cells containing an icon, how about this...

Wrap the contents of each non-icon td in a span:

<td><span>consectetur</span></td>
<td><span>adipiscing</span></td>
<td><span>elit</span></td>

And use this CSS:

td {
    text-align: center;
}
td span {
    text-align: left;
    display: block;
}

I wouldn't normally post an answer in this situation, but this seems too long for a comment.

Split string based on regex

I suggest

l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)

Check this demo.

Get the name of an object's type

Say you have var obj;

If you just want the name of obj's type, like "Object", "Array", or "String", you can use this:

Object.prototype.toString.call(obj).split(' ')[1].replace(']', '');

Python virtualenv questions

in my project wsgi.py file i have this code (it works with virtualenv,django,apache2 in windows and python 3.4)

import os
import sys
DJANGO_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')
sys.path.append(DJANGO_PATH)
sys.path.append('c:/myproject/env/Scripts')
sys.path.append('c:/myproject/env/Lib/site-packages')
activate_this = 'c:/myproject/env/scripts/activate_this.py'
exec(open(activate_this).read())
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
application = get_wsgi_application()

in virtualhost file conf i have

<VirtualHost *:80>
    ServerName mysite
    WSGIScriptAlias / c:/myproject/myproject/myproject/wsgi.py
    DocumentRoot c:/myproject/myproject/
    <Directory  "c:/myproject/myproject/myproject/">
       Options +Indexes +FollowSymLinks +MultiViews
       AllowOverride All
      Require local
   </Directory>
</VirtualHost>

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

Can I call a base class's virtual function if I'm overriding it?

The C++ syntax is like this:

class Bar : public Foo {
  // ...

  void printStuff() {
    Foo::printStuff(); // calls base class' function
  }
};

How do I simulate a low bandwidth, high latency environment?

Another client-side program (Windows only), is NetLimiter - http://www.netlimiter.com

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

You need an HTML element for each column in your layout.

I’d suggest:

HTML

<div class="two-col">
    <div class="col1">
        <label for="field1">Field One:</label>
        <input id="field1" name="field1" type="text">
    </div>

    <div class="col2">
        <label for="field2">Field Two:</label>
        <input id="field2" name="field2" type="text">
    </div>
</div>

CSS

.two-col {
    overflow: hidden;/* Makes this div contain its floats */
}

.two-col .col1,
.two-col .col2 {
    width: 49%;
}

.two-col .col1 {
    float: left;
}

.two-col .col2 {
    float: right;
}

.two-col label {
    display: block;
}

Class method decorator with self arguments?

Yes. Instead of passing in the instance attribute at class definition time, check it at runtime:

def check_authorization(f):
    def wrapper(*args):
        print args[0].url
        return f(*args)
    return wrapper

class Client(object):
    def __init__(self, url):
        self.url = url

    @check_authorization
    def get(self):
        print 'get'

>>> Client('http://www.google.com').get()
http://www.google.com
get

The decorator intercepts the method arguments; the first argument is the instance, so it reads the attribute off of that. You can pass in the attribute name as a string to the decorator and use getattr if you don't want to hardcode the attribute name:

def check_authorization(attribute):
    def _check_authorization(f):
        def wrapper(self, *args):
            print getattr(self, attribute)
            return f(self, *args)
        return wrapper
    return _check_authorization

Running a Python script from PHP

To clarify which command to use based on the situation

exec() - Execute an external program

system() - Execute an external program and display the output

passthru() - Execute an external program and display raw output

Source: http://php.net/manual/en/function.exec.php

Send email using the GMail SMTP server from a PHP page

Your code does not appear to be using TLS (SSL), which is necessary to deliver mail to Google (and using ports 465 or 587).

You can do this by setting

$host = "ssl://smtp.gmail.com";

Your code looks suspiciously like this example which refers to ssl:// in the hostname scheme.

Rename multiple columns by names

With dplyr you would do:

library(dplyr)

df = data.frame(q = 1, w = 2, e = 3)
    
df %>% rename(A = q, B = e)

#  A w B
#1 1 2 3

Or if you want to use vectors, as suggested by @Jelena-bioinf:

library(dplyr)

df = data.frame(q = 1, w = 2, e = 3)

oldnames = c("q","e")
newnames = c("A","B")

df %>% rename_at(vars(oldnames), ~ newnames)

#  A w B
#1 1 2 3

L. D. Nicolas May suggested a change given rename_at is being superseded by rename_with:

df %>% 
  rename_with(~ newnames[which(oldnames == .x)], .cols = oldnames)

#  A w B
#1 1 2 3

How do I run Selenium in Xvfb?

The easiest way is probably to use xvfb-run:

DISPLAY=:1 xvfb-run java -jar selenium-server-standalone-2.0b3.jar

xvfb-run does the whole X authority dance for you, give it a try!

An error when I add a variable to a string

You have empty $entry_database variable. As you see in error: ListEmail, Title FROM WHERE ID bewteen FROM and WHERE should be name of table. Proper syntax of SELECT:

SELECT columns FROM table [optional things as WHERE/ORDER/GROUP/JOIN etc]

which in your way should become:

SELECT ID, ListStID, ListEmail, Title FROM some_table_you_got WHERE ID = '4'

How do I retrieve a textbox value using JQuery?

You need to use the val() function to get the textbox value. text does not exist as a property only as a function and even then its not the correct function to use in this situation.

var from = $("input#fromAddress").val()

val() is the standard function for getting the value of an input.

How to shift a block of code left/right by one space in VSCode?

No need to use any tool for that

  1. Set Tab Spaces to 1.
  2. Select whole block of code and then press Shift + Tab

Shift + Tab = Shift text right to left

How can I truncate a datetime in SQL Server?

In SQl 2005 your trunc_date function could be written like this.

(1)

CREATE FUNCTION trunc_date(@date DATETIME)
RETURNS DATETIME
AS
BEGIN
    CAST(FLOOR( CAST( @date AS FLOAT ) )AS DATETIME)
END

The first method is much much cleaner. It uses only 3 method calls including the final CAST() and performs no string concatenation, which is an automatic plus. Furthermore, there are no huge type casts here. If you can imagine that Date/Time stamps can be represented, then converting from dates to numbers and back to dates is a fairly easy process.

(2)

CREATE FUNCTION trunc_date(@date DATETIME)
RETURNS DATETIME
AS
BEGIN
      SELECT CONVERT(varchar, @date,112)
END

If you are concerned about microsoft's implementation of datetimes (2) or (3) might be ok.

(3)

CREATE FUNCTION trunc_date(@date DATETIME)
RETURNS DATETIME
AS
BEGIN
SELECT CAST((STR( YEAR( @date ) ) + '/' +STR( MONTH( @date ) ) + '/' +STR( DAY(@date ) )
) AS DATETIME
END

Third, the more verbose method. This requires breaking the date into its year, month, and day parts, putting them together in "yyyy/mm/dd" format, then casting that back to a date. This method involves 7 method calls including the final CAST(), not to mention string concatenation.

How to reset settings in Visual Studio Code?

You can get your menu back by pressing/holding alt, you can then toggle the menu back on via the View menu.

As for your settings, you can open your user settings through the command palette:

  1. Press F1
  2. Type user settings
  3. Press enter
  4. Click the "sheet" icon to open the settings.json file:

    enter image description here

From there you can delete the file's contents and save to reset your settings.


For a more manual route, the settings files are located in the following locations:

  • Windows %APPDATA%\Code\User\settings.json
  • macOS $HOME/Library/Application Support/Code/User/settings.json
  • Linux $HOME/.config/Code/User/settings.json

Extensions are located in the following locations:

  • Windows %USERPROFILE%\.vscode\extensions
  • macOS ~/.vscode/extensions
  • Linux ~/.vscode/extensions

How do I remove the non-numeric character from a string in java?

Are you removing or splitting? This will remove all the non-numeric characters.

myStr = myStr.replaceAll( "[^\\d]", "" )

How to copy java.util.list Collection

Use the ArrayList copy constructor, then sort that.

List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);

After making the copy, any changes to newList do not affect oldList.

Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.

What is the difference between null and System.DBNull.Value?

From the documentation of the DBNull class:

Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.

jQuery: Performing synchronous AJAX requests

You're using the ajax function incorrectly. Since it's synchronous it'll return the data inline like so:

var remote = $.ajax({
    type: "GET",
    url: remote_url,
    async: false
}).responseText;

How to access random item in list?

  1. Create an instance of Random class somewhere. Note that it's pretty important not to create a new instance each time you need a random number. You should reuse the old instance to achieve uniformity in the generated numbers. You can have a static field somewhere (be careful about thread safety issues):

    static Random rnd = new Random();
    
  2. Ask the Random instance to give you a random number with the maximum of the number of items in the ArrayList:

    int r = rnd.Next(list.Count);
    
  3. Display the string:

    MessageBox.Show((string)list[r]);
    

How do I add a resources folder to my Java project in Eclipse

Build Path -> Configure Build Path -> Libraries (Tab) -> Add Class Folder, then select your folder or create one.

GitHub README.md center image

You can also resize the image to the desired width and height. For example:

<p align="center">
  <img src="https://anyserver.com/image.png" width="750px" height="300px"/></p>

To add a centered caption to the image, just one more line:

<p align="center">This is a centered caption for the image<p align="center">

Fortunately, this works both for README.md and the GitHub Wiki pages.

Remove duplicates from an array of objects in JavaScript

This is simple way how to remove duplicity from array of objects.

I work with data a lot and this is useful for me.

const data = [{name: 'AAA'}, {name: 'AAA'}, {name: 'BBB'}, {name: 'AAA'}];
function removeDuplicity(datas){
    return datas.filter((item, index,arr)=>{
    const c = arr.map(item=> item.name);
    return  index === c.indexOf(item.name)
  })
}

console.log(removeDuplicity(data))

will print into console :

[[object Object] {
name: "AAA"
}, [object Object] {
name: "BBB"
}]

Find and replace entire mysql database

Short answer: You can't.

Long answer: You can use the INFORMATION_SCHEMA to get the table definitions and use this to generate the necessary UPDATE statements dynamically. For example you could start with this:

SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'your_schema'

I'd try to avoid doing this though if at all possible.

Safest way to run BAT file from Powershell script

What about invoke-item script.bat.

How can one see the structure of a table in SQLite?

You can use the Firefox add-on called SQLite Manager to view the database's structure clearly.

IF - ELSE IF - ELSE Structure in Excel

Say P7 is a Cell then you can use the following Syntex to check the value of the cell and assign appropriate value to another cell based on this following nested if:

=IF(P7=0,200,IF(P7=1,100,IF(P7=2,25,IF(P7=3,10,IF((P7=4),5,0)))))

Can't choose class as main class in IntelliJ

Here is the complete procedure for IDEA IntelliJ 2019.3:

  1. File > Project Structure

  2. Under Project Settings > Modules

  3. Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.

  4. Apply changes.

Java JSON serialization - best practice

Well, when writing it out to file, you do know what class T is, so you can store that in dump. Then, when reading it back in, you can dynamically call it using reflection.

public JSONObject dump() throws JSONException {
    JSONObject result = new JSONObject();
    JSONArray a = new JSONArray();
    for(T i : items){
        a.put(i.dump());
        // inside this i.dump(), store "class-name"
    }
    result.put("items", a);
    return result;
}

public void load(JSONObject obj) throws JSONException {
    JSONArray arrayItems = obj.getJSONArray("items");
    for (int i = 0; i < arrayItems.length(); i++) {
        JSONObject item = arrayItems.getJSONObject(i);
        String className = item.getString("class-name");
        try {
            Class<?> clazzy = Class.forName(className);
            T newItem = (T) clazzy.newInstance();
            newItem.load(obj);
            items.add(newItem);
        } catch (InstantiationException e) {
            // whatever
        } catch (IllegalAccessException e) {
            // whatever
        } catch (ClassNotFoundException e) {
            // whatever
        }
    }

javascript, for loop defines a dynamic variable name

You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do

for (var i = myArray.length - 1; i >= 0; i--) {    console.log(eval(myArray[i])); }; 

More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.

var result = {}; for (var i = myArray.length - 1; i >= 0; i--) {     result[myArray[i]] = eval(myArray[i]);   }; 

I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via

window['myVarName'] = 'namingCollisionsAreFun';  

(per comment)

Use a.empty, a.bool(), a.item(), a.any() or a.all()

As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &. That also requires using parentheses so that & wouldn't take precedence.

It would go something like this:

mask = ((50  < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...

In order to avoid that, you can build series for lower and upper limits:

low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)

Now you can slice it as follows:

mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out: 
     dyastolic blood pressure  heart rate  pulse oximetry  respiratory rate  \
17                        136          62              97                15   
69                        110          85              96                18   
72                        105          85              97                16   
161                       126          57              99                16   
286                       127          84              99                12   
435                        92          67              96                13   
499                       110          66              97                15   

     systolic blood pressure  temperature  
17                       141           37  
69                       155           38  
72                       154           36  
161                      153           36  
286                      156           37  
435                      155           36  
499                      149           36  

And for assignment you can use np.where:

df['class'] = np.where(mask, 'excellent', 'critical')

How to compare only date in moment.js

For checking one date is after another by using isAfter() method.

moment('2020-01-20').isAfter('2020-01-21'); // false
moment('2020-01-20').isAfter('2020-01-19'); // true

For checking one date is before another by using isBefore() method.

moment('2020-01-20').isBefore('2020-01-21'); // true
moment('2020-01-20').isBefore('2020-01-19'); // false

For checking one date is same as another by using isSame() method.

moment('2020-01-20').isSame('2020-01-21'); // false
moment('2020-01-20').isSame('2020-01-20'); // true

installing urllib in Python3.6

urllib is a standard library, you do not have to install it. Simply import urllib

JSON library for C#

To answer your first question, Microsoft does ship a DataContractJsonSerializer: see msdn How to: Serialize and Deserialize JSON Data

jQuery UI - Draggable is not a function?

4 years after the question got posted, but maybe it will help others who run into this problem. The answer has been posted elsewhere on StackExchange as well, but I lost the link and it's hard to find.

ANSWER: In jQueryTOOLS, the jQuery 'core' is also embedded if you use the default download.

When you load jQuery and jQuery tools, jQuery core gets defined twice and will 'unset' any plugins. 'Draggable' (from jQuery-UI) is such a plug-in.

The solution is to use jQuery tools WITHOUT the jQuery 'core' files and everything will work fine.

CSS/HTML: What is the correct way to make text italic?

The i element is non-semantic, so for the screen readers, Googlebot, etc., it should be some kind of transparent (just like span or div elements). But it's not a good choice for the developer, because it joins the presentation layer with the structure layer - and that's a bad practice.

em element (strong as well) should be always used in a semantic context, not a presentation one. It has to be used whenever some word or sentence is important. Just for an example in the previous sentence, I should use em to put more emphasis on the 'should be always used' part. Browsers provides some default CSS properties for these elements, but you can and you're supposed to override the default values if your design requires this to keep the correct semantic meaning of these elements.

<span class="italic">Italic Text</span> is the most wrong way. First of all, it's inconvenient in use. Secondly, it suggest that the text should be italic. And the structure layer (HTML, XML, etc.) shouldn't ever do it. Presentation should be always kept separated from the structure.

<span class="footnote">Italic Text</span> seems to be the best way for a footnote. It doesn't suggest any presentation and just describes the markup. You can't predict what will happen in the feature. If a footnote will grow up in the feature, you might be forced to change its class name (to keep some logic in your code).

So whenever you've some important text, use em or strong to emphasis it. But remember that these elements are inline elements and shouldn't be used to emphasis large blocks of text.

Use CSS if you care only about how something looks like and always try to avoid any extra markup.

Matplotlib (pyplot) savefig outputs blank image

First, what happens when T0 is not None? I would test that, then I would adjust the values I pass to plt.subplot(); maybe try values 131, 132, and 133, or values that depend whether or not T0 exists.

Second, after plt.show() is called, a new figure is created. To deal with this, you can

  1. Call plt.savefig('tessstttyyy.png', dpi=100) before you call plt.show()

  2. Save the figure before you show() by calling plt.gcf() for "get current figure", then you can call savefig() on this Figure object at any time.

For example:

fig1 = plt.gcf()
plt.show()
plt.draw()
fig1.savefig('tessstttyyy.png', dpi=100)

In your code, 'tesssttyyy.png' is blank because it is saving the new figure, to which nothing has been plotted.

Size of Matrix OpenCV

If you are using the Python wrappers, then (assuming your matrix name is mat):

  • mat.shape gives you an array of the type- [height, width, channels]

  • mat.size gives you the size of the array

Sample Code:

import cv2
mat = cv2.imread('sample.png')
height, width, channel = mat.shape[:3]
size = mat.size

YAML equivalent of array of objects in JSON

Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq

Save your JSON example to a file, say ex.json and then

yq -y '.' ex.json

AAPL:
- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

What is SYSNAME data type in SQL Server?

sysname is a built in datatype limited to 128 Unicode characters that, IIRC, is used primarily to store object names when creating scripts. Its value cannot be NULL

It is basically the same as using nvarchar(128) NOT NULL

EDIT

As mentioned by @Jim in the comments, I don't think there is really a business case where you would use sysname to be honest. It is mainly used by Microsoft when building the internal sys tables and stored procedures etc within SQL Server.

For example, by executing Exec sp_help 'sys.tables' you will see that the column name is defined as sysname this is because the value of this is actually an object in itself (a table)

I would worry too much about it.

It's also worth noting that for those people still using SQL Server 6.5 and lower (are there still people using it?) the built in type of sysname is the equivalent of varchar(30)

Documentation

sysname is defined with the documentation for nchar and nvarchar, in the remarks section:

sysname is a system-supplied user-defined data type that is functionally equivalent to nvarchar(128), except that it is not nullable. sysname is used to reference database object names.

To clarify the above remarks, by default sysname is defined as NOT NULL it is certainly possible to define it as nullable. It is also important to note that the exact definition can vary between instances of SQL Server.

Using Special Data Types

The sysname data type is used for table columns, variables, and stored procedure parameters that store object names. The exact definition of sysname is related to the rules for identifiers. Therefore, it can vary between instances of SQL Server. sysname is functionally the same as nvarchar(128) except that, by default, sysname is NOT NULL. In earlier versions of SQL Server, sysname is defined as varchar(30).

Some further information about sysname allowing or disallowing NULL values can be found here https://stackoverflow.com/a/52290792/300863

Just because it is the default (to be NOT NULL) does not guarantee that it will be!

system("pause"); - Why is it wrong?

For me it doesn't make sense in general to wait before exiting without reason. A program that has done its work should just end and hand over its resources back to its creator.

One also doesn't silently wait in a dark corner after a work day, waiting for someone tipping ones shoulder.

How to count check-boxes using jQuery?

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

If you changed the ruby version you're using with rvm use, remove Gemfile.lock and try again.

Run jQuery function onclick

You can bind the mouseenter and mouseleave events and jQuery will emulate those where they are not native.

$("div.system_box").on('mouseenter', function(){
    //enter
})
.on('mouseleave', function(){
    //leave
});

fiddle

note: do not use hover as that is deprecated

ld: framework not found Pods

In my case, I created the workspace before installing the pods, so when I installed the pods, the workspace included my project only, add the Pods project to your workspace, clean and rebuild solved the issue in my case

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

How to step through Python code to help debug issues?

By using Python Interactive Debugger 'pdb'

First step is to make the Python interpreter to enter into the debugging mode.

A. From the Command Line

Most straight forward way, running from command line, of python interpreter

$ python -m pdb scriptName.py
> .../pdb_script.py(7)<module>()
-> """
(Pdb)

B. Within the Interpreter

While developing early versions of modules and to experiment it more iteratively.

$ python
Python 2.7 (r27:82508, Jul  3 2010, 21:12:11)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdb_script
>>> import pdb
>>> pdb.run('pdb_script.MyObj(5).go()')
> <string>(1)<module>()
(Pdb)

C. From Within Your Program

For a big project and long-running module, can start the debugging from inside the program using import pdb and set_trace() like this :

#!/usr/bin/env python
# encoding: utf-8
#

import pdb

class MyObj(object):
    count = 5
    def __init__(self):
        self.count= 9

    def go(self):
        for i in range(self.count):
            pdb.set_trace()
            print i
        return

if __name__ == '__main__':
    MyObj(5).go()

Step-by-Step debugging to go into more internal

  1. Execute the next statement… with “n” (next)

  2. Repeating the last debugging command… with ENTER

  3. Quitting it all… with “q” (quit)

  4. Printing the value of variables… with “p” (print)

    a) p a

  5. Turning off the (Pdb) prompt… with “c” (continue)

  6. Seeing where you are… with “l” (list)

  7. Stepping into subroutines… with “s” (step into)

  8. Continuing… but just to the end of the current subroutine… with “r” (return)

  9. Assign a new value

    a) !b = "B"

  10. Set a breakpoint

    a) break linenumber

    b) break functionname

    c) break filename:linenumber

  11. Temporary breakpoint

    a) tbreak linenumber

  12. Conditional breakpoint

    a) break linenumber, condition

Note:**All these commands should be execute from **pdb

For in-depth knowledge, refer:-

https://pymotw.com/2/pdb/

https://pythonconquerstheuniverse.wordpress.com/2009/09/10/debugging-in-python/

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

Java Currency Number format

I'd recommend using the java.text package:

double money = 100.1;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String moneyString = formatter.format(money);
System.out.println(moneyString);

This has the added benefit of being locale specific.

But, if you must, truncate the String you get back if it's a whole dollar:

if (moneyString.endsWith(".00")) {
    int centsIndex = moneyString.lastIndexOf(".00");
    if (centsIndex != -1) {
        moneyString = moneyString.substring(1, centsIndex);
    }
}

How to set a time zone (or a Kind) of a DateTime value?

You can try this as well, it is easy to implement

TimeZone time2 = TimeZone.CurrentTimeZone;
DateTime test = time2.ToUniversalTime(DateTime.Now);
var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);

Change the text to which standard time you want to change.

Use TimeZone feature of C# to implement.

How to choose an AES encryption mode (CBC ECB CTR OCB CFB)?

I know one aspect: Although CBC gives better security by changing the IV for each block, it's not applicable to randomly accessed encrypted content (like an encrypted hard disk).

So, use CBC (and the other sequential modes) for sequential streams and ECB for random access.

Looping through list items with jquery

To solve this without jQuery .each() you'd have to fix your code like this:

var listItems = $("#productList").find("li");
var ind, len, product;

for ( ind = 0, len = listItems.length; ind < len; ind++ ) {
    product = $(listItems[ind]);

    // ...
}

Bugs in your original code:

  1. for ... in will also loop through all inherited properties; i.e. you will also get a list of all functions that are defined by jQuery.

  2. The loop variable li is not the list item, but the index to the list item. In that case the index is a normal array index (i.e. an integer)

Basically you are save to use .each() as it is more comfortable, but espacially when you are looping bigger arrays the code in this answer will be much faster.

For other alternatives to .each() you can check out this performance comparison: http://jsperf.com/browser-diet-jquery-each-vs-for-loop

Java; String replace (using regular expressions)?

You'll want to look into capturing in regex to handle wrapping the 3 in ^3.

tmux set -g mouse-mode on doesn't work

As @Graham42 noted, mouse option has changed in version 2.1. Scrolling now requires for you to enter copy mode first. To enable scrolling almost identical to how it was before 2.1 add following to your .tmux.conf.

set-option -g mouse on

# make scrolling with wheels work
bind -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= '#{pane_in_mode}' 'send-keys -M' 'select-pane -t=; copy-mode -e; send-keys -M'"
bind -n WheelDownPane select-pane -t= \; send-keys -M

This will enable scrolling on hover over a pane and you will be able to scroll that pane line by line.

Source: https://groups.google.com/d/msg/tmux-users/TRwPgEOVqho/Ck_oth_SDgAJ

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

One contending technology you've omitted is Server-Sent Events / Event Source. What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet? has a good discussion of all of these. Keep in mind that some of these are easier than others to integrate with on the server side.

How do I tell if a variable has a numeric value in Perl?

The original question was how to tell if a variable was numeric, not if it "has a numeric value".

There are a few operators that have separate modes of operation for numeric and string operands, where "numeric" means anything that was originally a number or was ever used in a numeric context (e.g. in $x = "123"; 0+$x, before the addition, $x is a string, afterwards it is considered numeric).

One way to tell is this:

if ( length( do { no warnings "numeric"; $x & "" } ) ) {
    print "$x is numeric\n";
}

If the bitwise feature is enabled, that makes & only a numeric operator and adds a separate string &. operator, you must disable it:

if ( length( do { no if $] >= 5.022, "feature", "bitwise"; no warnings "numeric"; $x & "" } ) ) {
    print "$x is numeric\n";
}

(bitwise is available in perl 5.022 and above, and enabled by default if you use 5.028; or above.)

Rails find_or_create_by more than one attribute?

In Rails 4 you could do:

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

And use where is different:

GroupMember.where(member_id: 4, group_id: 7).first_or_create

This will call create on GroupMember.where(member_id: 4, group_id: 7):

GroupMember.where(member_id: 4, group_id: 7).create

On the contrary, the find_or_create_by(member_id: 4, group_id: 7) will call create on GroupMember:

GroupMember.create(member_id: 4, group_id: 7)

Please see this relevant commit on rails/rails.

How to put a symbol above another in LaTeX?

${a \atop \#}$

or

${a \above 0pt \#}$

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

I had a similar problem while moving from Visual Studio 2013 to Visual Studio 2015 on a MVC project.

Deleting the whole .vs solution worked as a charm as Johan J v Rensburg pointed out.

Routing HTTP Error 404.0 0x80070002

My solution, after trying EVERYTHING:

Bad deployment, an old PrecompiledApp.config was hanging around my deploy location, and making everything not work.

My final settings that worked:

  • IIS 7.5, Win2k8r2 x64,
  • Integrated mode application pool
  • Nothing changes in the web.config - this means no special handlers for routing. Here's my snapshot of the sections a lot of other posts reference. I'm using FluorineFX, so I do have that handler added, but I did not need any others:

    <system.web>
      <compilation debug="true" targetFramework="4.0" />
      <authentication mode="None"/>
    
      <pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
      <httpRuntime requestPathInvalidCharacters=""/>
    
      <httpModules>
        <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx"/>
      </httpModules>
    </system.web>
      <system.webServer>
        <!-- Modules for IIS 7.0 Integrated mode -->
        <modules>
          <add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx" />
        </modules>
    
        <!-- Disable detection of IIS 6.0 / Classic mode ASP.NET configuration -->
        <validation validateIntegratedModeConfiguration="false" />
      </system.webServer>
    
  • Global.ashx: (only method of any note)

    void Application_Start(object sender, EventArgs e) {
        // Register routes...
        System.Web.Routing.Route echoRoute = new System.Web.Routing.Route(
              "{*message}",
            //the default value for the message
              new System.Web.Routing.RouteValueDictionary() { { "message", "" } },
            //any regular expression restrictions (i.e. @"[^\d].{4,}" means "does not start with number, at least 4 chars
              new System.Web.Routing.RouteValueDictionary() { { "message", @"[^\d].{4,}" } },
              new TestRoute.Handlers.PassthroughRouteHandler()
           );
    
        System.Web.Routing.RouteTable.Routes.Add(echoRoute);
    }
    
  • PassthroughRouteHandler.cs - this achieved an automatic conversion from http://andrew.arace.info/stackoverflow to http://andrew.arace.info/#stackoverflow which would then be handled by the default.aspx:

    public class PassthroughRouteHandler : IRouteHandler {
    
        public IHttpHandler GetHttpHandler(RequestContext requestContext) {
            HttpContext.Current.Items["IncomingMessage"] = requestContext.RouteData.Values["message"];
            requestContext.HttpContext.Response.Redirect("#" + HttpContext.Current.Items["IncomingMessage"], true);
            return null;
        }
    }
    

List all files from a directory recursively with Java

Java's interface for reading filesystem folder contents is not very performant (as you've discovered). JDK 7 fixes this with a completely new interface for this sort of thing, which should bring native level performance to these sorts of operations.

The core issue is that Java makes a native system call for every single file. On a low latency interface, this is not that big of a deal - but on a network with even moderate latency, it really adds up. If you profile your algorithm above, you'll find that the bulk of the time is spent in the pesky isDirectory() call - that's because you are incurring a round trip for every single call to isDirectory(). Most modern OSes can provide this sort of information when the list of files/folders was originally requested (as opposed to querying each individual file path for it's properties).

If you can't wait for JDK7, one strategy for addressing this latency is to go multi-threaded and use an ExecutorService with a maximum # of threads to perform your recursion. It's not great (you have to deal with locking of your output data structures), but it'll be a heck of a lot faster than doing this single threaded.

In all of your discussions about this sort of thing, I highly recommend that you compare against the best you could do using native code (or even a command line script that does roughly the same thing). Saying that it takes an hour to traverse a network structure doesn't really mean that much. Telling us that you can do it native in 7 second, but it takes an hour in Java will get people's attention.

Importing data from a JSON file into R

First install the rjson package:

install.packages("rjson")

Then:

library("rjson")
json_file <- "http://api.worldbank.org/country?per_page=10&region=OED&lendingtype=LNX&format=json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))

Update: since version 0.2.1

json_data <- fromJSON(file=json_file)

How can I get dict from sqlite query?

After you connect to SQLite: con = sqlite3.connect(.....) it is sufficient to just run:

con.row_factory = sqlite3.Row

Voila!

How can a windows service programmatically restart itself?

The problem with shelling out to a batch file or EXE is that a service may or may not have the permissions required to run the external app.

The cleanest way to do this that I have found is to use the OnStop() method, which is the entry point for the Service Control Manager. Then all your cleanup code will run, and you won't have any hanging sockets or other processes, assuming your stop code is doing its job.

To do this you need to set a flag before you terminate that tells the OnStop method to exit with an error code; then the SCM knows that the service needs to be restarted. Without this flag you won't be able to stop the service manually from the SCM. This also assumes you have set up the service to restart on an error.

Here's my stop code:

...

bool ABORT;

protected override void OnStop()
{
    Logger.log("Stopping service");
    WorkThreadRun = false;
    WorkThread.Join();
    Logger.stop();
    // if there was a problem, set an exit error code
    // so the service manager will restart this
    if(ABORT)Environment.Exit(1);
}

If the service runs into a problem and needs to restart, I launch a thread that stops the service from the SCM. This allows the service to clean up after itself:

...

if(NeedToRestart)
{
    ABORT = true;
    new Thread(RestartThread).Start();
}

void RestartThread()
{
    ServiceController sc = new ServiceController(ServiceName);
    try
    {
        sc.Stop();
    }
    catch (Exception) { }
}

Group By Eloquent ORM

try: ->unique('column')

example:

$users = User::get()->unique('column');

HTTP response code for POST when resource already exists

I would go with 422 Unprocessable Entity, which is used when a request is invalid but the issue is not in syntax or authentication.

As an argument against other answers, to use any non-4xx error code would imply it's not a client error, and it obviously is. To use a non-4xx error code to represent a client error just makes no sense at all.

It seems that 409 Conflict is the most common answer here, but, according to the spec, that implies that the resource already exists and the new data you are applying to it is incompatible with its current state. If you are sending a POST request, with, for example, a username that is already taken, it's not actually conflicting with the target resource, as the target resource (the resource you're trying to create) has not yet been posted. It's an error specifically for version control, when there is a conflict between the version of the resource stored and the version of the resource requested. It's very useful for that purpose, for example when the client has cached an old version of the resource and sends a request based on that incorrect version which would no longer be conditionally valid. "In this case, the response representation would likely contain information useful for merging the differences based on the revision history." The request to create another user with that username is just unprocessable, having nothing to do with version control.

For the record, 422 is also the status code GitHub uses when you try to create a repository by a name already in use.

What is a regex to match ONLY an empty string?

Another possible answer considering also the case that an empty string might contain several whitespace characters for example spaces,tabs,line break characters can be the folllowing pattern.

pattern = r"^(\s*)$"

This pattern matches if the string starts and ends with zero or more whitespace characters.

It was tested in Python 3

Can constructors be async?

if you make constructor asynchronous, after creating an object, you may fall into problems like null values instead of instance objects. For instance;

MyClass instance = new MyClass();
instance.Foo(); // null exception here

That's why they don't allow this i guess.

Get the closest number out of an array

All of the solutions are over-engineered.

It is as simple as:

const needle = 5;
const haystack = [1, 2, 3, 4, 5, 6, 7, 8, 9];

haystack.sort((a, b) => {
  return Math.abs(a - needle) - Math.abs(b - needle);
})[0];

// 5

Convert np.array of type float64 to type uint8 scaling values

A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2], the code right now would scale that to have intensities of [0, 128, 255]. You want these to remain small after converting to np.uint8.

Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo and provide it the type (dtype) of the image and you will obtain a structure of information for that type. You would then access the max field from this structure to determine the maximum value.

So with the above, do the following modifications to your code:

import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)

Note that I've additionally converted the image into np.float64 in case the incoming data type is not so and to maintain floating-point precision when doing the division.

Unable to start Service Intent

For anyone else coming across this thread I had this issue and was pulling my hair out. I had the service declaration OUTSIDE of the '< application>' end tag DUH!

RIGHT:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  ...>
...
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity ...>
        ...
    </activity>    

    <service android:name=".Service"/>

    <receiver android:name=".Receiver">
        <intent-filter>
            ...
        </intent-filter>
    </receiver>        
</application>

<uses-permission android:name="..." />

WRONG but still compiles without errors:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  ...>
...
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity ...>
        ...
    </activity>

</application>

    <service android:name=".Service"/>

    <receiver android:name=".Receiver">
        <intent-filter>
            ...
        </intent-filter>
    </receiver>        

<uses-permission android:name="..." />

fatal error: iostream.h no such file or directory

That header doesn't exist in standard C++. It was part of some pre-1990s compilers, but it is certainly not part of C++.

Use #include <iostream> instead. And all the library classes are in the std:: namespace, for ex­am­ple std::cout.

Also, throw away any book or notes that mention the thing you said.

Insert value into a string at a certain position?

You can't modify strings; they're immutable. You can do this instead:

txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);

how to change php version in htaccess in server

To switch to PHP 4.4:

AddHandler application/x-httpd-php4 .php .php4 .php3

To switch to PHP 5.0:

AddHandler application/x-httpd-php5 .php .php5 .php4 .php3

To switch to PHP 5.1:

AddHandler application/x-httpd-php51 .php .php5 .php4 .php3

To switch to PHP 5.2:

AddHandler application/x-httpd-php52 .php .php5 .php4 .php3

To switch to PHP 5.3:

AddHandler application/x-httpd-php53 .php .php5 .php4 .php3

To switch to PHP 5.4:

AddHandler application/x-httpd-php54 .php .php5 .php4 .php3

To switch to PHP 5.5:

AddHandler application/x-httpd-php55 .php .php5 .php4 .php3

To switch to the secure PHP 5.2 with Suhosin patch:

AddHandler application/x-httpd-php52s .php .php5 .php4 .php3

How to import cv2 in python3?

The best way is to create a virtual env. first and then do pip install , everything will work fine

How to link 2 cell of excel sheet?

Just follow these Steps :

If you want the contents of, say, C1 to mirror the contents of cell A1, you just need to set the formula in C1 to =A1. From this point forward, anything you type in A1 will show up in C1 as well.

To Link Multiple Cells in Excel From Another Worksheet :

Step 1

Click the worksheet tab at the bottom of the screen that contains a range of precedent cells to which you want to link. A range is a block or group of adjacent cells. For example, assume you want to link a range of blank cells in “Sheet1” to a range of precedent cells in “Sheet2.” Click the “Sheet2” tab.

Step 2

Determine the precedent range’s width in columns and height in rows. In this example, assume cells A1 through A4 on “Sheet2” contain a list of numbers 1, 2, 3 and 4, respectively, which will be your precedent cells. This precedent range is one column wide by four rows high.

Step 3

Click the worksheet tab at the bottom of the screen that contains the blank cells in which you will insert a link. In this example, click the “Sheet1” tab.

Step 4

Select the range of blank cells you want to link to the precedent cells. This range must be the same size as the precedent range, but can be in a different location on the worksheet. Click and hold the mouse button on the top left cell of the range, drag the mouse cursor to the bottom right cell in the range and release the mouse button to select the range. In this example, assume you want to link cells C1 through C4 to the precedent range. Click and hold on cell C1, drag the mouse to cell C4 and release the mouse to highlight the range.

Step 5

Type “=,” the worksheet name containing the precedent cells, “!,” the top left cell of the precedent range, “:” and the bottom right cell of the precedent range. Press “Ctrl,” “Shift” and “Enter” simultaneously to complete the array formula. Each dependent cell is now linked to the cell in the precedent range that’s in the same respective location within the range. In this example, type “=Sheet2!A1:A4” and press “Ctrl,” “Shift” and “Enter” simultaneously. Cells C1 through C4 on “Sheet1” now contain the array formula “{=Sheet2!A1:A4}” surrounded by curly brackets, and show the same data as the precedent cells in “Sheet2.”

Good Luck !!!

Test if string is a number in Ruby on Rails

Tl;dr: Use a regex approach. It is 39x faster than the rescue approach in the accepted answer and also handles cases like "1,000"

def regex_is_number? string
  no_commas =  string.gsub(',', '')
  matches = no_commas.match(/-?\d+(?:\.\d+)?/)
  if !matches.nil? && matches.size == 1 && matches[0] == no_commas
    true
  else
    false
  end
end

--

The accepted answer by @Jakob S works for the most part, but catching exceptions can be really slow. In addition, the rescue approach fails on a string like "1,000".

Let's define the methods:

def rescue_is_number? string
  true if Float(string) rescue false
end

def regex_is_number? string
  no_commas =  string.gsub(',', '')
  matches = no_commas.match(/-?\d+(?:\.\d+)?/)
  if !matches.nil? && matches.size == 1 && matches[0] == no_commas
    true
  else
    false
  end
end

And now some test cases:

test_cases = {
  true => ["5.5", "23", "-123", "1,234,123"],
  false => ["hello", "99designs", "(123)456-7890"]
}

And a little code to run the test cases:

test_cases.each do |expected_answer, cases|
  cases.each do |test_case|
    if rescue_is_number?(test_case) != expected_answer
      puts "**rescue_is_number? got #{test_case} wrong**"
    else
      puts "rescue_is_number? got #{test_case} right"
    end

    if regex_is_number?(test_case) != expected_answer
      puts "**regex_is_number? got #{test_case} wrong**"
    else
      puts "regex_is_number? got #{test_case} right"
    end  
  end
end

Here is the output of the test cases:

rescue_is_number? got 5.5 right
regex_is_number? got 5.5 right
rescue_is_number? got 23 right
regex_is_number? got 23 right
rescue_is_number? got -123 right
regex_is_number? got -123 right
**rescue_is_number? got 1,234,123 wrong**
regex_is_number? got 1,234,123 right
rescue_is_number? got hello right
regex_is_number? got hello right
rescue_is_number? got 99designs right
regex_is_number? got 99designs right
rescue_is_number? got (123)456-7890 right
regex_is_number? got (123)456-7890 right

Time to do some performance benchmarks:

Benchmark.ips do |x|

  x.report("rescue") { test_cases.values.flatten.each { |c| rescue_is_number? c } }
  x.report("regex") { test_cases.values.flatten.each { |c| regex_is_number? c } }

  x.compare!
end

And the results:

Calculating -------------------------------------
              rescue   128.000  i/100ms
               regex     4.649k i/100ms
-------------------------------------------------
              rescue      1.348k (±16.8%) i/s -      6.656k
               regex     52.113k (± 7.8%) i/s -    260.344k

Comparison:
               regex:    52113.3 i/s
              rescue:     1347.5 i/s - 38.67x slower

How can I make my own event in C#?

to do it we have to know the three components

  1. the place responsible for firing the Event
  2. the place responsible for responding to the Event
  3. the Event itself

    a. Event

    b .EventArgs

    c. EventArgs enumeration

now lets create Event that fired when a function is called

but I my order of solving this problem like this: I'm using the class before I create it

  1. the place responsible for responding to the Event

    NetLog.OnMessageFired += delegate(object o, MessageEventArgs args) 
    {
            // when the Event Happened I want to Update the UI
            // this is WPF Window (WPF Project)  
            this.Dispatcher.Invoke(() =>
            {
                LabelFileName.Content = args.ItemUri;
                LabelOperation.Content = args.Operation;
                LabelStatus.Content = args.Status;
            });
    };
    

NetLog is a static class I will Explain it later

the next step is

  1. the place responsible for firing the Event

    //this is the sender object, MessageEventArgs Is a class I want to create it  and Operation and Status are Event enums
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started));
    downloadFile = service.DownloadFile(item.Uri);
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));
    

the third step

  1. the Event itself

I warped The Event within a class called NetLog

public sealed class NetLog
{
    public delegate void MessageEventHandler(object sender, MessageEventArgs args);

    public static event MessageEventHandler OnMessageFired;
    public static void FireMessage(Object obj,MessageEventArgs eventArgs)
    {
        if (OnMessageFired != null)
        {
            OnMessageFired(obj, eventArgs);
        }
    }
}

public class MessageEventArgs : EventArgs
{
    public string ItemUri { get; private set; }
    public Operation Operation { get; private set; }
    public Status Status { get; private set; }

    public MessageEventArgs(string itemUri, Operation operation, Status status)
    {
        ItemUri = itemUri;
        Operation = operation;
        Status = status;
    }
}

public enum Operation
{
    Upload,Download
}

public enum Status
{
    Started,Finished
}

this class now contain the Event, EventArgs and EventArgs Enums and the function responsible for firing the event

sorry for this long answer

Java: Date from unix timestamp

If you are converting a timestamp value on a different machine, you should also check the timezone of that machine. For example;

The above decriptions will result different Date values, if you run with EST or UTC timezones.

To set the timezone; aka to UTC, you can simply rewrite;

    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    java.util.Date time= new java.util.Date((Long.parseLong(timestamp)*1000));

Use JAXB to create Object from XML String

If you want to parse using InputStreams

public Object xmlToObject(String xmlDataString) {
        Object converted = null;
        try {
        
            JAXBContext jc = JAXBContext.newInstance(Response.class);
        
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
            
            converted = unmarshaller.unmarshal(stream);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return converted;
    }

SQL Server default character encoding

I think this is worthy of a separate answer: although internally unicode data is stored as UTF-16 in Sql Server this is the Little Endian flavour, so if you're calling the database from an external system, you probably need to specify UTF-16LE.

How to check whether a int is not null or empty?

if your int variable is declared as a class level variable (instance variable) it would be defaulted to 0. But that does not indicate if the value sent from the client was 0 or a null. may be you could have a setter method which could be called to initialize/set the value sent by the client. then you can define your indicator value , may be a some negative value to indicate the null..

PreparedStatement with list of parameters in a IN clause

Many DBs have a concept of a temporary table, even assuming you don't have a temporary table you can always generate one with a unique name and drop it when you are done. While the overhead of creating and dropping a table is large, this may be reasonable for very large operations, or in cases where you are using the database as a local file or in memory (SQLite).

An example from something I am in the middle of (using Java/SqlLite):

String tmptable = "tmp" + UUID.randomUUID();

sql = "create table " + tmptable + "(pagelist text not null)";
cnn.createStatement().execute(sql);

cnn.setAutoCommit(false);
stmt = cnn.prepareStatement("insert into "+tmptable+" values(?);");
for(Object o : rmList){
    Path path = (Path)o;
    stmt.setString(1, path.toString());
    stmt.execute();
}
cnn.commit();
cnn.setAutoCommit(true);

stmt = cnn.prepareStatement(sql);
stmt.execute("delete from filelist where path + page in (select * from "+tmptable+");");
stmt.execute("drop table "+tmptable+");");

Note that the fields used by my table are created dynamically.

This would be even more efficient if you are able to reuse the table.

Bootstrap 3 and Youtube in Modal

I have solved it on wordpress template:

$videoLink ="http://www.youtube.com/watch?v=yRuVYkA8i1o;".   
<?php
    parse_str( parse_url( $videoLink, PHP_URL_QUERY ), $my_array_of_vars );
    $youtube_ID = $my_array_of_vars['v'];    
?> 
<a class="video" data-toggle="modal" data-target="#myModal" rel="<?php echo $youtube_ID;?>">
    <img src="<?php bloginfo('template_url');?>/assets/img/play.png" />
</a>

<div class="modal fade video-lightbox" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">    
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body"></div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script> 
    jQuery(document).ready(function ($) {
        var $midlayer = $('.modal-body');     
        $('#myModal').on('show.bs.modal', function (e) {
            var $video = $('a.video');
            var vid = $video.attr('rel');
            var iframe = '<iframe />';  
            var url = "//youtube.com/embed/"+vid+"?autoplay=1&autohide=1&modestbranding=1&rel=0&hd=1";
            var width_f = '100%';
            var height_f = 400;
            var frameborder = 0;
            jQuery(iframe, {
                name: 'videoframe',
                id: 'videoframe',
                src: url,
                width:  width_f,
                height: height_f,
                frameborder: 0,
                class: 'youtube-player',
                type: 'text/html',
                allowfullscreen: true
            }).appendTo($midlayer);   
        });

        $('#myModal').on('hide.bs.modal', function (e) {
            $('div.modal-body').html('');
        }); 
    });
</script>

Postgres integer arrays as parameters?

I realize this is an old question, but it took me several hours to find a good solution and thought I'd pass on what I learned here and save someone else the trouble. Try, for example,

SELECT * FROM some_table WHERE id_column = ANY(@id_list)

where @id_list is bound to an int[] parameter by way of

command.Parameters.Add("@id_list", NpgsqlDbType.Array | NpgsqlDbType.Integer).Value = my_id_list;

where command is a NpgsqlCommand (using C# and Npgsql in Visual Studio).

convert string to number node.js

You do not have to install something.

parseInt(req.params.year, 10);

should work properly.

console.log(typeof parseInt(req.params.year)); // returns 'number'

What is your output, if you use parseInt? is it still a string?

Detecting a redirect in ajax request?

You can now use fetch API/ It returns redirected: *boolean*

Insert 2 million rows into SQL Server quickly

Re the solution for SqlBulkCopy:

I used the StreamReader to convert and process the text file. The result was a list of my object.

I created a class than takes Datatable or a List<T> and a Buffer size (CommitBatchSize). It will convert the list to a data table using an extension (in the second class).

It works very fast. On my PC, I am able to insert more than 10 million complicated records in less than 10 seconds.

Here is the class:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{

public class BulkUploadToSql<T>
{
    public IList<T> InternalStore { get; set; }
    public string TableName { get; set; }
    public int CommitBatchSize { get; set; }=1000;
    public string ConnectionString { get; set; }

    public void Commit()
    {
        if (InternalStore.Count>0)
        {
            DataTable dt;
            int numberOfPages = (InternalStore.Count / CommitBatchSize)  + (InternalStore.Count % CommitBatchSize == 0 ? 0 : 1);
            for (int pageIndex = 0; pageIndex < numberOfPages; pageIndex++)
                {
                    dt= InternalStore.Skip(pageIndex * CommitBatchSize).Take(CommitBatchSize).ToDataTable();
                BulkInsert(dt);
                }
        } 
    }

    public void BulkInsert(DataTable dt)
    {
        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            // make sure to enable triggers
            // more on triggers in next post
            SqlBulkCopy bulkCopy =
                new SqlBulkCopy
                (
                connection,
                SqlBulkCopyOptions.TableLock |
                SqlBulkCopyOptions.FireTriggers |
                SqlBulkCopyOptions.UseInternalTransaction,
                null
                );

            // set the destination table name
            bulkCopy.DestinationTableName = TableName;
            connection.Open();

            // write the data in the "dataTable"
            bulkCopy.WriteToServer(dt);
            connection.Close();
        }
        // reset
        //this.dataTable.Clear();
    }

}

public static class BulkUploadToSqlHelper
{
    public static DataTable ToDataTable<T>(this IEnumerable<T> data)
    {
        PropertyDescriptorCollection properties =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }
}

}

Here is an example when I want to insert a List of my custom object List<PuckDetection> (ListDetections):

var objBulk = new BulkUploadToSql<PuckDetection>()
{
        InternalStore = ListDetections,
        TableName= "PuckDetections",
        CommitBatchSize=1000,
        ConnectionString="ENTER YOU CONNECTION STRING"
};
objBulk.Commit();

The BulkInsert class can be modified to add column mapping if required. Example you have an Identity key as first column.(this assuming that the column names in the datatable are the same as the database)

//ADD COLUMN MAPPING
foreach (DataColumn col in dt.Columns)
{
        bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}

How does one make random number between range for arc4random_uniform()?

Swift 3/4:

func randomNumber(range: ClosedRange<Int> = 1...6) -> Int {
    let min = range.lowerBound
    let max = range.upperBound
    return Int(arc4random_uniform(UInt32(1 + max - min))) + min
}

How can I get a web site's favicon?

You'll want to tackle this a few ways:

  1. Look for the favicon.ico at the root of the domain

    www.domain.com/favicon.ico

  2. Look for a <link> tag with the rel="shortcut icon" attribute

    <link rel="shortcut icon" href="/favicon.ico" />

  3. Look for a <link> tag with the rel="icon" attribute

    <link rel="icon" href="/favicon.png" />

The latter two will usually yield a higher quality image.


Just to cover all of the bases, there are device specific icon files that might yield higher quality images since these devices usually have larger icons on the device than a browser would need:

<link rel="apple-touch-icon" href="images/touch.png" />

<link rel="apple-touch-icon-precomposed" href="images/touch.png" />


And to download the icon without caring what the icon is you can use a utility like http://www.google.com/s2/favicons which will do all of the heavy lifting:

var client = new System.Net.WebClient();

client.DownloadFile(
    @"http://www.google.com/s2/favicons?domain=stackoverflow.com",
    "stackoverflow.com.ico");

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

Add this line to the file xampp\phpMyAdmin\config.inc:

$cfg['Servers'][$i]['port'] = '3307';

Here, my port is 3307, you can change it to yours.

How do I replace multiple spaces with a single space in C#?

This is a shorter version, which should only be used if you are only doing this once, as it creates a new instance of the Regex class every time it is called.

temp = new Regex(" {2,}").Replace(temp, " "); 

If you are not too acquainted with regular expressions, here's a short explanation:

The {2,} makes the regex search for the character preceding it, and finds substrings between 2 and unlimited times.
The .Replace(temp, " ") replaces all matches in the string temp with a space.

If you want to use this multiple times, here is a better option, as it creates the regex IL at compile time:

Regex singleSpacify = new Regex(" {2,}", RegexOptions.Compiled);
temp = singleSpacify.Replace(temp, " ");

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

In case you don't want to use the M2_HOME and want to direct the IntelliJ to the maven installation you can simply set it by:

  • goto File => Setting => Maven => Maven home directory
  • point to your maven build directory e.g. /usr/local/maven/apache-maven-3.0.4

A better way is to have a symlink e.g. 'latest' for the latest version and point your IntelliJ to use that for consistency, given latest points to the latest version of maven installed on your box.

Why is the console window closing immediately once displayed my output?

I assume the reason you don't want it to close in Debug mode, is because you want to look at the values of variables etc. So it's probably best to just insert a break-point on the closing "}" of the main function. If you don't need to debug, then Ctrl-F5 is the best option.

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

Perhaps a more pythonic way of doing so.

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

t = linspace(0,2*math.pi,400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, t, b, t, c)
plt.show()

enter image description here

Very simple C# CSV reader

You can try the some thing like the below LINQ snippet.

string[] allLines = File.ReadAllLines(@"E:\Temp\data.csv");

    var query = from line in allLines
                let data = line.Split(',')
                select new
                {
                    Device = data[0],
                    SignalStrength = data[1],
                    Location = data[2], 
                    Time = data[3],
                    Age = Convert.ToInt16(data[4])
                };

UPDATE: Over a period of time, things evolved. As of now, I would prefer to use this library http://www.aspnetperformance.com/post/LINQ-to-CSV-library.aspx

What is a singleton in C#?

E.X You can use Singleton for global information that needs to be injected.

In my case, I was keeping the Logged user detail(username, permissions etc.) in Global Static Class. And when I tried to implement the Unit Test, there was no way I could inject dependency into Controller classes. Thus I have changed my Static Class to Singleton pattern.

public class SysManager
{
    private static readonly SysManager_instance = new SysManager();

    static SysManager() {}

    private SysManager(){}

    public static SysManager Instance
    {
        get {return _instance;}
    }
}

http://csharpindepth.com/Articles/General/Singleton.aspx#cctor

foreach vs someList.ForEach(){}

There is one important, and useful, distinction between the two.

Because .ForEach uses a for loop to iterate the collection, this is valid (edit: prior to .net 4.5 - the implementation changed and they both throw):

someList.ForEach(x => { if(x.RemoveMe) someList.Remove(x); }); 

whereas foreach uses an enumerator, so this is not valid:

foreach(var item in someList)
  if(item.RemoveMe) someList.Remove(item);

tl;dr: Do NOT copypaste this code into your application!

These examples aren't best practice, they are just to demonstrate the differences between ForEach() and foreach.

Removing items from a list within a for loop can have side effects. The most common one is described in the comments to this question.

Generally, if you are looking to remove multiple items from a list, you would want to separate the determination of which items to remove from the actual removal. It doesn't keep your code compact, but it guarantees that you do not miss any items.

Combining two sorted lists in Python

People seem to be over complicating this.. Just combine the two lists, then sort them:

>>> l1 = [1, 3, 4, 7]
>>> l2 = [0, 2, 5, 6, 8, 9]
>>> l1.extend(l2)
>>> sorted(l1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

..or shorter (and without modifying l1):

>>> sorted(l1 + l2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

..easy! Plus, it's using only two built-in functions, so assuming the lists are of a reasonable size, it should be quicker than implementing the sorting/merging in a loop. More importantly, the above is much less code, and very readable.

If your lists are large (over a few hundred thousand, I would guess), it may be quicker to use an alternative/custom sorting method, but there are likely other optimisations to be made first (e.g not storing millions of datetime objects)

Using the timeit.Timer().repeat() (which repeats the functions 1000000 times), I loosely benchmarked it against ghoseb's solution, and sorted(l1+l2) is substantially quicker:

merge_sorted_lists took..

[9.7439379692077637, 9.8844599723815918, 9.552299976348877]

sorted(l1+l2) took..

[2.860386848449707, 2.7589840888977051, 2.7682540416717529]

HorizontalScrollView within ScrollView Touch Handling

I think I found a simpler solution, only this uses a subclass of ViewPager instead of (its parent) ScrollView.

UPDATE 2013-07-16: I added an override for onTouchEvent as well. It could possibly help with the issues mentioned in the comments, although YMMV.

public class UninterceptableViewPager extends ViewPager {

    public UninterceptableViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean ret = super.onInterceptTouchEvent(ev);
        if (ret)
            getParent().requestDisallowInterceptTouchEvent(true);
        return ret;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        boolean ret = super.onTouchEvent(ev);
        if (ret)
            getParent().requestDisallowInterceptTouchEvent(true);
        return ret;
    }
}

This is similar to the technique used in android.widget.Gallery's onScroll(). It is further explained by the Google I/O 2013 presentation Writing Custom Views for Android.

Update 2013-12-10: A similar approach is also described in a post from Kirill Grouchnikov about the (then) Android Market app.

How do I change a PictureBox's image?

If you have an image imported as a resource in your project there is also this:

picPreview.Image = Properties.Resources.ImageName;

Where picPreview is the name of the picture box and ImageName is the name of the file you want to display.

*Resources are located by going to: Project --> Properties --> Resources

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

How to recover closed output window in netbeans?

If you run the server in normal mode you can recover the log by restarting the main project in debug mode. It seems that NB opens a new server log when the server run mode changes.

In Python, how do I split a string and keep the separators?

  1. replace all seperator: (\W) with seperator + new_seperator: (\W;)

  2. split by the new_seperator: (;)

def split_and_keep(seperator, s):
  return re.split(';', re.sub(seperator, lambda match: match.group() + ';', s))

print('\W', 'foo/bar spam\neggs')

How to convert current date to epoch timestamp?

import time
def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    return int(time.time()+300)

Why are Python lambdas useful?

lambda is just a fancy way of saying function. Other than its name, there is nothing obscure, intimidating or cryptic about it. When you read the following line, replace lambda by function in your mind:

>>> f = lambda x: x + 1
>>> f(3)
4

It just defines a function of x. Some other languages, like R, say it explicitly:

> f = function(x) { x + 1 }
> f(3)
4

You see? It's one of the most natural things to do in programming.

Adding Lombok plugin to IntelliJ project

You need to Enable Annotation Processing on IntelliJ IDEA

> Settings > Build, Execution, Deployment > Compiler > Annotation Processors

enter image description here

Different names of JSON property during serialization and deserialization

You can use a combination of @JsonSetter, and @JsonGetter to control the deserialization, and serialization of your property, respectively. This will also allow you to keep standardized getter and setter method names that correspond to your actual field name.

import com.fasterxml.jackson.annotation.JsonSetter;    
import com.fasterxml.jackson.annotation.JsonGetter;

class Coordinates {
    private int red;

    //# Used during serialization
    @JsonGetter("r")
    public int getRed() {
        return red;
    }

    //# Used during deserialization
    @JsonSetter("red")
    public void setRed(int red) {
        this.red = red;
    }
}

Get Today's date in Java at midnight time

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");    
Date date = new Date(); System.out.println(dateFormat.format(date));    //2014/08/06 15:59:4

How do I get the full url of the page I am on in C#

I usually use Request.Url.ToString() to get the full url (including querystring), no concatenation required.

npm can't find package.json

Generate package.json without having it ask any questions. I ran the below comment in Mac and Windows under the directory that I would like to create package.json and it works

$ npm init -y

Wrote to C:\workspace\package.json:

{
  "name": "workspace",
  "version": "1.0.0",
  "description": "",
  "main": "builder.js",
  "dependencies": {
    "jasmine-spec-reporter": "^4.2.1",
    "selenium-webdriver": "^4.0.0-alpha.5"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Property getters and setters

I don't know if it is good practice but you can do something like this:

class test_ancestor {
    var prop: Int = 0
}


class test: test_ancestor {
    override var prop: Int {
        get {
            return super.prop // reaching ancestor prop
        }
        set {
            super.prop = newValue * 2
        }
    }
}

var test_instance = test()
test_instance.prop = 10

print(test_instance.prop) // 20

Read more

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

Type the following command using your username and repository name:

git clone https://github.com/{user name}/{repo name}

in Ubuntu this works perfectly.

Count the number occurrences of a character in a string

Regular expressions are very useful if you want case-insensitivity (and of course all the power of regex).

my_string = "Mary had a little lamb"
# simplest solution, using count, is case-sensitive
my_string.count("m")   # yields 1
import re
# case-sensitive with regex
len(re.findall("m", my_string))
# three ways to get case insensitivity - all yield 2
len(re.findall("(?i)m", my_string))
len(re.findall("m|M", my_string))
len(re.findall(re.compile("m",re.IGNORECASE), my_string))

Be aware that the regex version takes on the order of ten times as long to run, which will likely be an issue only if my_string is tremendously long, or the code is inside a deep loop.

How to find the extension of a file in C#?

I'm not sure if this is what you want but:

Directory.GetFiles(@"c:\mydir", "*.flv");

Or:

Path.GetExtension(@"c:\test.flv")

Checking if a collection is null or empty in Groovy

FYI this kind of code works (you can find it ugly, it is your right :) ) :

def list = null
list.each { println it }
soSomething()

In other words, this code has null/empty checks both useless:

if (members && !members.empty) {
    members.each { doAnotherThing it }
}

def doAnotherThing(def member) {
  // Some work
}

Apply .gitignore on an existing repository already tracking large number of files

  1. Create a .gitignore file, so to do that, you just create any blank .txt file.

  2. Then you have to change its name writing the following line on the cmd (where git.txt is the name of the file you've just created):

    rename git.txt .gitignore

  3. Then you can open the file and write all the untracked files you want to ignore for good. For example, mine looks like this:

```

OS junk files
[Tt]humbs.db
*.DS_Store

#Visual Studio files
*.[Oo]bj
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.sdf
*.pyc
*.xml
ipch/
obj/
[Bb]in
[Dd]ebug*/
[Rr]elease*/
Ankh.NoLoad

#Tooling
_ReSharper*/
*.resharper
[Tt]est[Rr]esult*

#Project files
[Bb]uild/

#Subversion files
.svn

# Office Temp Files
~$*

There's a whole collection of useful .gitignore files by GitHub

  1. Once you have this, you need to add it to your git repository just like any other file, only it has to be in the root of the repository.

  2. Then in your terminal you have to write the following line:

    git config --global core.excludesfile ~/.gitignore_global

From oficial doc:

You can also create a global .gitignore file, which is a list of rules for ignoring files in every Git repository on your computer. For example, you might create the file at ~/.gitignore_global and add some rules to it.

Open Terminal. Run the following command in your terminal: git config --global core.excludesfile ~/.gitignore_global

If the respository already exists then you have to run these commands:

git rm -r --cached .
git add .
git commit -m ".gitignore is now working"

If the step 2 doesn´t work then you should write the hole route of the files that you would like to add.