Programs & Examples On #.net remoting

.NET Remoting is a legacy technology of the .NET Framework for distributed applications. For development of new distributed applications it is recommened to use Windows Communication Foundation (WCF)

How to convert date to timestamp?

For those who wants to have readable timestamp in format of, yyyymmddHHMMSS

> (new Date()).toISOString().replace(/[^\d]/g,'')              // "20190220044724404"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -3) // "20190220044724"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -9) // "20190220"

Usage example: a backup file extension. /my/path/my.file.js.20190220

How do I send email with JavaScript without opening the mail client?

You can't do it with client side script only... you could make an AJAX call to some server side code that will send an email...

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

Steps for Window10:

  • Go to https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python
  • Download the right version according to python version and hardware specs: for my case, mysqlclient-1.4.2-cp37-cp37m-win32.whl works for python3.7 and Intel CPU.
  • While your env is still activated, go to the download folder and run pip install mysqlclient-1.4.2-cp37-cp37m-win32.whl

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

JSONObject site = (JSONObject)jsonSites.get(i); // Exception happens here.

The return type of jsonSites.get(i) is JSONArray not JSONObject. Because sites have two '[', two means there are two arrays here.

How to select a dropdown value in Selenium WebDriver using Java

Just wrap your WebElement into Select Object as shown below

Select dropdown = new Select(driver.findElement(By.id("identifier")));

Once this is done you can select the required value in 3 ways. Consider an HTML file like this

<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>

Now to identify dropdown do

Select dropdown = new Select(driver.findElement(By.id("designation")));

To select its option say 'Programmer' you can do

dropdown.selectByVisibleText("Programmer ");

or

dropdown.selectByIndex(1);

or

 dropdown.selectByValue("prog");

How do I combine 2 javascript variables into a string

if you want to concatenate the string representation of the values of two variables, use the + sign :

var var1 = 1;
var var2 = "bob";
var var3 = var2 + var1;//=bob1

But if you want to keep the two in only one variable, but still be able to access them later, you could make an object container:

function Container(){
   this.variables = [];
}
Container.prototype.addVar = function(var){
   this.variables.push(var);
}
Container.prototype.toString = function(){
   var result = '';
   for(var i in this.variables)
       result += this.variables[i];
   return result;
}

var var1 = 1;
var var2 = "bob";
var container = new Container();
container.addVar(var2);
container.addVar(var1);
container.toString();// = bob1

the advantage is that you can get the string representation of the two variables, bit you can modify them later :

container.variables[0] = 3;
container.variables[1] = "tom";
container.toString();// = tom3

Get a list of all git commits, including the 'lost' ones

I've had luck recovering the commit by looking at the reflog, which was located at .git/logs/HEAD

I then had to scoll down to the end of the file, and I found the commit I just lost.

How can I get the assembly file version

Use this:

((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
    Assembly.GetExecutingAssembly(), 
    typeof(AssemblyFileVersionAttribute), false)
).Version;

Or this:

new Version(System.Windows.Forms.Application.ProductVersion);

Transfer data between iOS and Android via Bluetooth?

You could use p2pkit, or the free solution it was based on: https://github.com/GitGarage. Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.

How to write a UTF-8 file with Java?

The Java 7 Files utility type is useful for working with files:

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.*;

public class WriteReadUtf8 {
  public static void main(String[] args) throws IOException {
    List<String> lines = Arrays.asList("These", "are", "lines");

    Path textFile = Paths.get("foo.txt");
    Files.write(textFile, lines, StandardCharsets.UTF_8);

    List<String> read = Files.readAllLines(textFile, StandardCharsets.UTF_8);

    System.out.println(lines.equals(read));
  }
}

The Java 8 version allows you to omit the Charset argument - the methods default to UTF-8.

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

I know this is an old question, but I spent a couple of days looking through solutions which didn't work for me so maybe this helps someone else.

My project had a plugin which was throwing an error. I had to remove the plugin and add it again, and suddenly I could make it through the build process.

$ cordova add phonegap-plugin-push
$ cordova plugin add phonegap-plugin-push

I just ran the above and it was solved.

How can I uninstall npm modules in Node.js?

Well, to give a complete answer to this question, there are two methods (for example we call the installed module as module1):

  1. To remove module1 without changing package.json:

    npm uninstall module1

  2. To remove module1 with changing package.json, and removing it from the dependencies in package.json:

    npm uninstall --save module1

Note: to simplify the above mentioned commands, you can use -S instead of --save , and can use remove, rm, r, un, unlink instead of uninstall

What is the best method of handling currency/money?

Here's a fine, simple approach that leverages composed_of (part of ActiveRecord, using the ValueObject pattern) and the Money gem

You'll need

  • The Money gem (version 4.1.0)
  • A model, for example Product
  • An integer column in your model (and database), for example :price

Write this in your product.rb file:

class Product > ActiveRecord::Base

  composed_of :price,
              :class_name => 'Money',
              :mapping => %w(price cents),
              :converter => Proc.new { |value| Money.new(value) }
  # ...

What you'll get:

  • Without any extra changes, all of your forms will show dollars and cents, but the internal representation is still just cents. The forms will accept values like "$12,034.95" and convert it for you. There's no need to add extra handlers or attributes to your model, or helpers in your view.
  • product.price = "$12.00" automatically converts to the Money class
  • product.price.to_s displays a decimal formatted number ("1234.00")
  • product.price.format displays a properly formatted string for the currency
  • If you need to send cents (to a payment gateway that wants pennies), product.price.cents.to_s
  • Currency conversion for free

Select All distinct values in a column using LINQ

Interestingly enough I tried both of these in LinqPad and the variant using group from Dmitry Gribkov by appears to be quicker. (also the final distinct is not required as the result is already distinct.

My (somewhat simple) code was:

public class Pair 
{ 
    public int id {get;set;}
    public string Arb {get;set;}
}

void Main()
{

    var theList = new List<Pair>();
    var randomiser = new Random();
    for (int count = 1; count < 10000; count++)
    {
        theList.Add(new Pair 
        {
            id = randomiser.Next(1, 50),
            Arb = "not used"
        });
    }

    var timer = new Stopwatch();
    timer.Start();
    var distinct = theList.GroupBy(c => c.id).Select(p => p.First().id);
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);

    timer.Start();
    var otherDistinct = theList.Select(p => p.id).Distinct();
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);
}

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

Making TextView scrollable on Android

I struggled with this for over a week and finally figured out how to make this work!

My issue was that everything would scroll as a 'block'. The text itself was scrolling, but as a chunk rather than line by line. This obviously didn't work for me, because it would cut off lines at the bottom. All of the previous solutions did not work for me, so I crafted my own.

Here is the easiest solution by far:

Make a class file called: 'PerfectScrollableTextView' inside a package, then copy and paste this code in:

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;

public class PerfectScrollableTextView extends TextView {

    public PerfectScrollableTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    public PerfectScrollableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    public PerfectScrollableTextView(Context context) {
        super(context);
        setVerticalScrollBarEnabled(true);
        setHorizontallyScrolling(false);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        if(focused)
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if(focused)
            super.onWindowFocusChanged(focused);
    }

    @Override
    public boolean isFocused() {
        return true;
    }
}

Finally change your 'TextView' in XML:

From: <TextView

To: <com.your_app_goes_here.PerfectScrollableTextView

Uncaught TypeError: (intermediate value)(...) is not a function

To make semicolon rules simple

Every line that begins with a (, [, `, or any operator (/, +, - are the only valid ones), must begin with a semicolon.

func()
;[0].concat(myarr).forEach(func)
;(myarr).forEach(func)
;`hello`.forEach(func)
;/hello/.exec(str)
;+0
;-0

This prevents a

func()[0].concat(myarr).forEach(func)(myarr).forEach(func)`hello`.forEach(func)/hello/.forEach(func)+0-0

monstrocity.

Additional Note

To mention what will happen: brackets will index, parentheses will be treated as function parameters. The backtick would transform into a tagged template, and regex or explicitly signed integers will turn into operators. Of course, you can just add a semicolon to the end of every line. It's good to keep mind though when you're quickly prototyping and are dropping your semicolons.

Also, adding semicolons to the end of every line won't help you with the following, so keep in mind statements like

return // Will automatically insert semicolon, and return undefined.
    (1+2);
i // Adds a semicolon
   ++ // But, if you really intended i++ here, your codebase needs help.

The above case will happen to return/continue/break/++/--. Any linter will catch this with dead-code or ++/-- syntax error (++/-- will never realistically happen).

Finally, if you want file concatenation to work, make sure each file ends with a semicolon. If you're using a bundler program (recommended), it should do this automatically.

How to add 10 minutes to my (String) time?

Something like this

 String myTime = "14:10";
 SimpleDateFormat df = new SimpleDateFormat("HH:mm");
 Date d = df.parse(myTime); 
 Calendar cal = Calendar.getInstance();
 cal.setTime(d);
 cal.add(Calendar.MINUTE, 10);
 String newTime = df.format(cal.getTime());

As a fair warning there might be some problems if daylight savings time is involved in this 10 minute period.

How can I copy a Python string?

To put it a different way "id()" is not what you care about. You want to know if the variable name can be modified without harming the source variable name.

>>> a = 'hello'                                                                                                                                                                                                                                                                                        
>>> b = a[:]                                                                                                                                                                                                                                                                                           
>>> c = a                                                                                                                                                                                                                                                                                              
>>> b += ' world'                                                                                                                                                                                                                                                                                      
>>> c += ', bye'                                                                                                                                                                                                                                                                                       
>>> a                                                                                                                                                                                                                                                                                                  
'hello'                                                                                                                                                                                                                                                                                                
>>> b                                                                                                                                                                                                                                                                                                  
'hello world'                                                                                                                                                                                                                                                                                          
>>> c                                                                                                                                                                                                                                                                                                  
'hello, bye'                                                                                                                                                                                                                                                                                           

If you're used to C, then these are like pointer variables except you can't de-reference them to modify what they point at, but id() will tell you where they currently point.

The problem for python programmers comes when you consider deeper structures like lists or dicts:

>>> o={'a': 10}                                                                                                                                                                                                                                                                                        
>>> x=o                                                                                                                                                                                                                                                                                                
>>> y=o.copy()                                                                                                                                                                                                                                                                                         
>>> x['a'] = 20                                                                                                                                                                                                                                                                                        
>>> y['a'] = 30                                                                                                                                                                                                                                                                                        
>>> o                                                                                                                                                                                                                                                                                                  
{'a': 20}                                                                                                                                                                                                                                                                                              
>>> x                                                                                                                                                                                                                                                                                                  
{'a': 20}                                                                                                                                                                                                                                                                                              
>>> y                                                                                                                                                                                                                                                                                                  
{'a': 30}                                                                                                                                                                                                                                                                                              

Here o and x refer to the same dict o['a'] and x['a'], and that dict is "mutable" in the sense that you can change the value for key 'a'. That's why "y" needs to be a copy and y['a'] can refer to something else.

How to run batch file from network share without "UNC path are not supported" message?

I needed to be able to just Windows Explorer browse through the server share, then double-click launch the batch file. @dbenham led me to an easier solution for my scenario (without the popd worries):

:: Capture UNC or mapped-drive path script was launched from
set NetPath=%~dp0

:: Assumes that setup.exe is in the same UNC path
%NetPath%setup.exe

:: Note that NetPath has a trailing backslash ("\")
robocopy.exe "%NetPath%Custom" /copyall "C:\Program Files (x86)\WP\Custom Templates"
Regedit.exe /s %NetPath%..\WPX5\Custom\Migrate.reg

:: I am not sure if WPX5 was typo, so use ".." for parent directory
set NetPath=
pause

type checking in javascript

A clean approach

You can consider using a very small, dependency-free library like Not. Solves all problems:

// at the basic level it supports primitives
let number = 10
let array = []
not('number', 10) // returns false
not('number', []) // throws error

// so you need to define your own:
let not = Object.create(Not)

not.defineType({
    primitive: 'number',
    type: 'integer',
    pass: function(candidate) {
        // pre-ECMA6
        return candidate.toFixed(0) === candidate.toString()
        // ECMA6
        return Number.isInteger(candidate)
    }
})
not.not('integer', 4.4) // gives error message
not.is('integer', 4.4) // returns false
not.is('integer', 8) // returns true

If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.

function test (string, boolean) {
    // any of these below will throw errors to protect you
    not('string', string)
    not('boolean', boolean)

    // continue with your code.
}

How to Automatically Close Alerts using Twitter Bootstrap

With each of the solutions above I continued to lose re-usability of the alert. My solution was as follows:

On page load

$("#success-alert").hide();

Once the alert needed to be displayed

 $("#success-alert").show();
 window.setTimeout(function () {
     $("#success-alert").slideUp(500, function () {
          $("#success-alert").hide();
      });
 }, 5000);

Note that fadeTo sets the opacity to 0, so the display was none and the opacity was 0 which is why I removed from my solution.

Cassandra port usage - how are the ports used?

In addition to the above answers, as part of configuring your firewall, if you are using SSH then use port 22.

How do I determine k when using k-means clustering?

You can maximize the Bayesian Information Criterion (BIC):

BIC(C | X) = L(X | C) - (p / 2) * log n

where L(X | C) is the log-likelihood of the dataset X according to model C, p is the number of parameters in the model C, and n is the number of points in the dataset. See "X-means: extending K-means with efficient estimation of the number of clusters" by Dan Pelleg and Andrew Moore in ICML 2000.

Another approach is to start with a large value for k and keep removing centroids (reducing k) until it no longer reduces the description length. See "MDL principle for robust vector quantisation" by Horst Bischof, Ales Leonardis, and Alexander Selb in Pattern Analysis and Applications vol. 2, p. 59-72, 1999.

Finally, you can start with one cluster, then keep splitting clusters until the points assigned to each cluster have a Gaussian distribution. In "Learning the k in k-means" (NIPS 2003), Greg Hamerly and Charles Elkan show some evidence that this works better than BIC, and that BIC does not penalize the model's complexity strongly enough.

How can I use goto in Javascript?

const
    start = 0,
    more = 1,
    pass = 2,
    loop = 3,
    skip = 4,
    done = 5;

var label = start;


while (true){
    var goTo = null;
    switch (label){
        case start:
            console.log('start');
        case more:
            console.log('more');
        case pass:
            console.log('pass');
        case loop:
            console.log('loop');
            goTo = pass; break;
        case skip:
            console.log('skip');
        case done:
            console.log('done');

    }
    if (goTo == null) break;
    label = goTo;
}

How can I trigger an onchange event manually?

There's a couple of ways you can do this. If the onchange listener is a function set via the element.onchange property and you're not bothered about the event object or bubbling/propagation, the easiest method is to just call that function:

element.onchange();

If you need it to simulate the real event in full, or if you set the event via the html attribute or addEventListener/attachEvent, you need to do a bit of feature detection to correctly fire the event:

if ("createEvent" in document) {
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("change", false, true);
    element.dispatchEvent(evt);
}
else
    element.fireEvent("onchange");

Using Python's ftplib to get a directory listing, portably

I happen to be stuck with an FTP server (Rackspace Cloud Sites virtual server) that doesn't seem to support MLSD. Yet I need several fields of file information, such as size and timestamp, not just the filename, so I have to use the DIR command. On this server, the output of DIR looks very much like the OP's. In case it helps anyone, here's a little Python class that parses a line of such output to obtain the filename, size and timestamp.

import datetime

class FtpDir:
    def parse_dir_line(self, line):
        words = line.split()
        self.filename = words[8]
        self.size = int(words[4])
        t = words[7].split(':')
        ts = words[5] + '-' + words[6] + '-' + datetime.datetime.now().strftime('%Y') + ' ' + t[0] + ':' + t[1]
        self.timestamp = datetime.datetime.strptime(ts, '%b-%d-%Y %H:%M')

Not very portable, I know, but easy to extend or modify to deal with various different FTP servers.

Total Number of Row Resultset getRow Method

BalusC's answer is right! but I have to mention according to the user instance variable such as:

rSet.last(); 
total = rSet.getRow();

and then which you are missing

rSet.beforeFirst();

the remaining code is same you will get your desire result.

Set select option 'selected', by value

It's better to use change() after setting select value.

$("div.id_100 select").val("val2").change();

By doing this, the code will close to changing select by user, the explanation is included in JS Fiddle:

JS Fiddle

How to read from a text file using VBScript?

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll

or line by line with the method ReadLine:

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

'Loop over it
For Each line in dict.Items
  WScript.Echo line
Next

How to get the insert ID in JDBC?

In my case ->

ConnectionClass objConnectionClass=new ConnectionClass();
con=objConnectionClass.getDataBaseConnection();
pstmtGetAdd=con.prepareStatement(SQL_INSERT_ADDRESS_QUERY,Statement.RETURN_GENERATED_KEYS);
pstmtGetAdd.setString(1, objRegisterVO.getAddress());
pstmtGetAdd.setInt(2, Integer.parseInt(objRegisterVO.getCityId()));
int addId=pstmtGetAdd.executeUpdate();              
if(addId>0)
{
    ResultSet rsVal=pstmtGetAdd.getGeneratedKeys();
    rsVal.next();
    addId=rsVal.getInt(1);
}

How to make Python script run as service?

for my script of python, I use...

To START python script :

start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --exec $DAEMON

To STOP python script :

PID=$(cat $PIDFILE)
kill -9 $PID
rm -f $PIDFILE

P.S.: sorry for poor English, I'm from CHILE :D

Aesthetics must either be length one, or the same length as the dataProblems

Similar to @joran's answer. Reshape the df so that the prices for each product are in different columns:

xx <- reshape(df, idvar=c("skew","version","color"),
              v.names="price", timevar="product", direction="wide")

xx will have columns price.p1, ... price.p4, so:

ggp <- ggplot(xx,aes(x=price.p1, y=price.p3, color=factor(skew))) +
       geom_point(shape=19, size=5)
ggp + facet_grid(color~version)

gives the result from your image.

use a javascript array to fill up a drop down select box

This is a part from a REST-Service I´ve written recently.

var select = $("#productSelect")
for (var prop in data) {
    var option = document.createElement('option');
    option.innerHTML = data[prop].ProduktName
    option.value = data[prop].ProduktName;
    select.append(option)
}

The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.

How to define partitioning of DataFrame?

Spark >= 2.3.0

SPARK-22614 exposes range partitioning.

val partitionedByRange = df.repartitionByRange(42, $"k")

partitionedByRange.explain
// == Parsed Logical Plan ==
// 'RepartitionByExpression ['k ASC NULLS FIRST], 42
// +- AnalysisBarrier Project [_1#2 AS k#5, _2#3 AS v#6]
// 
// == Analyzed Logical Plan ==
// k: string, v: int
// RepartitionByExpression [k#5 ASC NULLS FIRST], 42
// +- Project [_1#2 AS k#5, _2#3 AS v#6]
//    +- LocalRelation [_1#2, _2#3]
// 
// == Optimized Logical Plan ==
// RepartitionByExpression [k#5 ASC NULLS FIRST], 42
// +- LocalRelation [k#5, v#6]
// 
// == Physical Plan ==
// Exchange rangepartitioning(k#5 ASC NULLS FIRST, 42)
// +- LocalTableScan [k#5, v#6]

SPARK-22389 exposes external format partitioning in the Data Source API v2.

Spark >= 1.6.0

In Spark >= 1.6 it is possible to use partitioning by column for query and caching. See: SPARK-11410 and SPARK-4849 using repartition method:

val df = Seq(
  ("A", 1), ("B", 2), ("A", 3), ("C", 1)
).toDF("k", "v")

val partitioned = df.repartition($"k")
partitioned.explain

// scala> df.repartition($"k").explain(true)
// == Parsed Logical Plan ==
// 'RepartitionByExpression ['k], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
// 
// == Analyzed Logical Plan ==
// k: string, v: int
// RepartitionByExpression [k#7], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
// 
// == Optimized Logical Plan ==
// RepartitionByExpression [k#7], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
// 
// == Physical Plan ==
// TungstenExchange hashpartitioning(k#7,200), None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- Scan PhysicalRDD[_1#5,_2#6]

Unlike RDDs Spark Dataset (including Dataset[Row] a.k.a DataFrame) cannot use custom partitioner as for now. You can typically address that by creating an artificial partitioning column but it won't give you the same flexibility.

Spark < 1.6.0:

One thing you can do is to pre-partition input data before you create a DataFrame

import org.apache.spark.sql.types._
import org.apache.spark.sql.Row
import org.apache.spark.HashPartitioner

val schema = StructType(Seq(
  StructField("x", StringType, false),
  StructField("y", LongType, false),
  StructField("z", DoubleType, false)
))

val rdd = sc.parallelize(Seq(
  Row("foo", 1L, 0.5), Row("bar", 0L, 0.0), Row("??", -1L, 2.0),
  Row("foo", -1L, 0.0), Row("??", 3L, 0.6), Row("bar", -3L, 0.99)
))

val partitioner = new HashPartitioner(5) 

val partitioned = rdd.map(r => (r.getString(0), r))
  .partitionBy(partitioner)
  .values

val df = sqlContext.createDataFrame(partitioned, schema)

Since DataFrame creation from an RDD requires only a simple map phase existing partition layout should be preserved*:

assert(df.rdd.partitions == partitioned.partitions)

The same way you can repartition existing DataFrame:

sqlContext.createDataFrame(
  df.rdd.map(r => (r.getInt(1), r)).partitionBy(partitioner).values,
  df.schema
)

So it looks like it is not impossible. The question remains if it make sense at all. I will argue that most of the time it doesn't:

  1. Repartitioning is an expensive process. In a typical scenario most of the data has to be serialized, shuffled and deserialized. From the other hand number of operations which can benefit from a pre-partitioned data is relatively small and is further limited if internal API is not designed to leverage this property.

    • joins in some scenarios, but it would require an internal support,
    • window functions calls with matching partitioner. Same as above, limited to a single window definition. It is already partitioned internally though, so pre-partitioning may be redundant,
    • simple aggregations with GROUP BY - it is possible to reduce memory footprint of the temporary buffers**, but overall cost is much higher. More or less equivalent to groupByKey.mapValues(_.reduce) (current behavior) vs reduceByKey (pre-partitioning). Unlikely to be useful in practice.
    • data compression with SqlContext.cacheTable. Since it looks like it is using run length encoding, applying OrderedRDDFunctions.repartitionAndSortWithinPartitions could improve compression ratio.
  2. Performance is highly dependent on a distribution of the keys. If it is skewed it will result in a suboptimal resource utilization. In the worst case scenario it will be impossible to finish the job at all.

  3. A whole point of using a high level declarative API is to isolate yourself from a low level implementation details. As already mentioned by @dwysakowicz and @RomiKuntsman an optimization is a job of the Catalyst Optimizer. It is a pretty sophisticated beast and I really doubt you can easily improve on that without diving much deeper into its internals.

Related concepts

Partitioning with JDBC sources:

JDBC data sources support predicates argument. It can be used as follows:

sqlContext.read.jdbc(url, table, Array("foo = 1", "foo = 3"), props)

It creates a single JDBC partition per predicate. Keep in mind that if sets created using individual predicates are not disjoint you'll see duplicates in the resulting table.

partitionBy method in DataFrameWriter:

Spark DataFrameWriter provides partitionBy method which can be used to "partition" data on write. It separates data on write using provided set of columns

val df = Seq(
  ("foo", 1.0), ("bar", 2.0), ("foo", 1.5), ("bar", 2.6)
).toDF("k", "v")

df.write.partitionBy("k").json("/tmp/foo.json")

This enables predicate push down on read for queries based on key:

val df1 = sqlContext.read.schema(df.schema).json("/tmp/foo.json")
df1.where($"k" === "bar")

but it is not equivalent to DataFrame.repartition. In particular aggregations like:

val cnts = df1.groupBy($"k").sum()

will still require TungstenExchange:

cnts.explain

// == Physical Plan ==
// TungstenAggregate(key=[k#90], functions=[(sum(v#91),mode=Final,isDistinct=false)], output=[k#90,sum(v)#93])
// +- TungstenExchange hashpartitioning(k#90,200), None
//    +- TungstenAggregate(key=[k#90], functions=[(sum(v#91),mode=Partial,isDistinct=false)], output=[k#90,sum#99])
//       +- Scan JSONRelation[k#90,v#91] InputPaths: file:/tmp/foo.json

bucketBy method in DataFrameWriter (Spark >= 2.0):

bucketBy has similar applications as partitionBy but it is available only for tables (saveAsTable). Bucketing information can used to optimize joins:

// Temporarily disable broadcast joins
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)

df.write.bucketBy(42, "k").saveAsTable("df1")
val df2 = Seq(("A", -1.0), ("B", 2.0)).toDF("k", "v2")
df2.write.bucketBy(42, "k").saveAsTable("df2")

// == Physical Plan ==
// *Project [k#41, v#42, v2#47]
// +- *SortMergeJoin [k#41], [k#46], Inner
//    :- *Sort [k#41 ASC NULLS FIRST], false, 0
//    :  +- *Project [k#41, v#42]
//    :     +- *Filter isnotnull(k#41)
//    :        +- *FileScan parquet default.df1[k#41,v#42] Batched: true, Format: Parquet, Location: InMemoryFileIndex[file:/spark-warehouse/df1], PartitionFilters: [], PushedFilters: [IsNotNull(k)], ReadSchema: struct<k:string,v:int>
//    +- *Sort [k#46 ASC NULLS FIRST], false, 0
//       +- *Project [k#46, v2#47]
//          +- *Filter isnotnull(k#46)
//             +- *FileScan parquet default.df2[k#46,v2#47] Batched: true, Format: Parquet, Location: InMemoryFileIndex[file:/spark-warehouse/df2], PartitionFilters: [], PushedFilters: [IsNotNull(k)], ReadSchema: struct<k:string,v2:double>

* By partition layout I mean only a data distribution. partitioned RDD has no longer a partitioner. ** Assuming no early projection. If aggregation covers only small subset of columns there is probably no gain whatsoever.

Activity restart on rotation Android

People are saying that you should use

android:configChanges="keyboardHidden|orientation"

But the best and most professional way to handle rotation in Android is to use the Loader class. It's not a famous class(I don't know why), but it is way better than the AsyncTask. For more information, you can read the Android tutorials found in Udacity's Android courses.

Of course, as another way, you could store the values or the views with onSaveInstanceState and read them with onRestoreInstanceState. It's up to you really.

C# Change A Button's Background Color

In WPF, the background is not a Color, it is a Brush. So, try this for starters:

using System.Windows.Media;

// ....

ButtonToday.Background = new SolidColorBrush(Colors.Red);

More sensibly, though, you should probably look at doing this in your Xaml instead of in code.

How to use jQuery in chrome extension?

Its very easy just do the following:

add the following line in your manifest.json

"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",

Now you are free to load jQuery directly from url

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

Source: google doc

Invalid application of sizeof to incomplete type with a struct

Your error is also shown when trying to access the sizeof() of an non-initialized extern array:

extern int a[];
sizeof(a);
>> error: invalid application of 'sizeof' to incomplete type 'int[]'

Note that you would get an array size missing error without the extern keyword.

c# Image resizing to different size while preserving aspect ratio

Just generalizing it down to aspect ratios and sizes, image stuff can be done outside of this function

public static d.RectangleF ScaleRect(d.RectangleF dest, d.RectangleF src, 
  bool keepWidth, bool keepHeight)  
{
    d.RectangleF destRect = new d.RectangleF();

    float sourceAspect = src.Width / src.Height;
    float destAspect = dest.Width / dest.Height;

    if (sourceAspect > destAspect)
    {
        // wider than high keep the width and scale the height
        destRect.Width = dest.Width;
        destRect.Height = dest.Width / sourceAspect;

        if (keepHeight)
        {
            float resizePerc = dest.Height / destRect.Height;
            destRect.Width = dest.Width * resizePerc;
            destRect.Height = dest.Height;
        }
    }
    else
    {
        // higher than wide – keep the height and scale the width
        destRect.Height = dest.Height;
        destRect.Width = dest.Height * sourceAspect;

        if (keepWidth)
        {
            float resizePerc = dest.Width / destRect.Width;
            destRect.Width = dest.Width;
            destRect.Height = dest.Height * resizePerc;
        }

    }

    return destRect;
}

Where does PostgreSQL store the database?

Under my Linux installation, it's here: /var/lib/postgresql/8.x/

You can change it with initdb -D "c:/mydb/"

VB.NET Switch Statement GoTo Case

Why not just do it like this:

Select Case parameter     
   Case "userID"                
      ' does something here.        
   Case "packageID"                
      ' does something here.        
   Case "mvrType"                 
      If otherFactor Then                         
         ' does something here.                 
      Else                         
         ' do processing originally part of GoTo here
         Exit Select  
      End If      
End Select

I'm not sure if not having a case else at the end is a big deal or not, but it seems like you don't really need the go to if you just put it in the else statement of your if.

Sockets: Discover port availability using Java

This is the implementation coming from the Apache camel project:

/**
 * Checks to see if a specific port is available.
 *
 * @param port the port to check for availability
 */
public static boolean available(int port) {
    if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
        throw new IllegalArgumentException("Invalid start port: " + port);
    }

    ServerSocket ss = null;
    DatagramSocket ds = null;
    try {
        ss = new ServerSocket(port);
        ss.setReuseAddress(true);
        ds = new DatagramSocket(port);
        ds.setReuseAddress(true);
        return true;
    } catch (IOException e) {
    } finally {
        if (ds != null) {
            ds.close();
        }

        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                /* should not be thrown */
            }
        }
    }

    return false;
}

They are checking the DatagramSocket as well to check if the port is avaliable in UDP and TCP.

Hope this helps.

How do you rename a MongoDB database?

Alternative solution: you can dump your db and restore that in different name. As I've experienced it's much quicker than db.copyDatabase().

$ mongodump -d old_db_name -o mongodump/
$ mongorestore -d new_db_name mongodump/old_db_name

http://docs.mongodb.org/manual/tutorial/backup-with-mongodump/


This is the current official recommended approach for database renames, given that copyDatabase was removed in MongoDB 4.2:

The "copydb" command is deprecated, please use these two commands instead:

  1. mongodump (to back up data)
  2. mongorestore (to recover data from mongodump into a new namespace)

Difference between a theta join, equijoin and natural join

Theta Join: When you make a query for join using any operator,(e.g., =, <, >, >= etc.), then that join query comes under Theta join.

Equi Join: When you make a query for join using equality operator only, then that join query comes under Equi join.

Example:

> SELECT * FROM Emp JOIN Dept ON Emp.DeptID = Dept.DeptID;
> SELECT * FROM Emp INNER JOIN Dept USING(DeptID)
This will show:
 _________________________________________________
| Emp.Name | Emp.DeptID | Dept.Name | Dept.DeptID |
|          |            |           |             |

Note: Equi join is also a theta join!

Natural Join: a type of Equi Join which occurs implicitly by comparing all the same names columns in both tables.

Note: here, the join result has only one column for each pair of same named columns.

Example

 SELECT * FROM Emp NATURAL JOIN Dept
This will show:
 _______________________________
| DeptID | Emp.Name | Dept.Name |
|        |          |           |

How does += (plus equal) work?

...and don't forget what happens when you mix types:

x = 127;
x += " hours "
// x is now a string: "127 hours "
x += 1 === 0;
// x is still a string: "127 hours false"

java.lang.NoClassDefFoundError: Could not initialize class XXX

I had the same exception, this is how I solved the problem:

Preconditions:

  1. Junit class (and test), that extended another class.

  2. ApplicationContext initialized using spring, that init the project.

  3. The Application context was initialized in @Before method

Solution:

Init the application context from @BeforeClass method, since the parent class also required some classes that were initialized from within the application context.

Hope this will help.

angular2: Error: TypeError: Cannot read property '...' of undefined

Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class

  myObj:any = {
    doSomething: function () { console.log('doing something'); return 'doing something'; },
  };
  myArray:any;
  constructor() { }

  ngOnInit() {
    this.myArray = [this.myObj];
  }

You can use it in template html file as following:

<div>test-1: {{  myObj?.doSomething()}}</div>
<div>test-2: {{  myArray[0].doSomething()}}</div>
<div>test-3: {{  myArray[2]?.doSomething()}}</div>

How do I sort arrays using vbscript?

Here is a QuickSort that I wrote for the arrays returned from the GetRows method of ADODB.Recordset.

'Author:        Eric Weilnau
'Date Written:  7/16/2003
'Description:   QuickSortDataArray sorts a data array using the QuickSort algorithm.
'               Its arguments are the data array to be sorted, the low and high
'               bound of the data array, the integer index of the column by which the
'               data array should be sorted, and the string "asc" or "desc" for the
'               sort order.
'
Sub QuickSortDataArray(dataArray, loBound, hiBound, sortField, sortOrder)
    Dim pivot(), loSwap, hiSwap, count
    ReDim pivot(UBound(dataArray))

    If hiBound - loBound = 1 Then
        If (sortOrder = "asc" and dataArray(sortField,loBound) > dataArray(sortField,hiBound)) or (sortOrder = "desc" and dataArray(sortField,loBound) < dataArray(sortField,hiBound)) Then
            Call SwapDataRows(dataArray, hiBound, loBound)
        End If
    End If

    For count = 0 to UBound(dataArray)
        pivot(count) = dataArray(count,int((loBound + hiBound) / 2))
        dataArray(count,int((loBound + hiBound) / 2)) = dataArray(count,loBound)
        dataArray(count,loBound) = pivot(count)
    Next

    loSwap = loBound + 1
    hiSwap = hiBound

    Do
        Do While (sortOrder = "asc" and dataArray(sortField,loSwap) <= pivot(sortField)) or sortOrder = "desc" and (dataArray(sortField,loSwap) >= pivot(sortField))
            loSwap = loSwap + 1

            If loSwap > hiSwap Then
                Exit Do
            End If
        Loop

        Do While (sortOrder = "asc" and dataArray(sortField,hiSwap) > pivot(sortField)) or (sortOrder = "desc" and dataArray(sortField,hiSwap) < pivot(sortField))
            hiSwap = hiSwap - 1
        Loop

        If loSwap < hiSwap Then
            Call SwapDataRows(dataArray,loSwap,hiSwap)
        End If
    Loop While loSwap < hiSwap

    For count = 0 to Ubound(dataArray)
        dataArray(count,loBound) = dataArray(count,hiSwap)
        dataArray(count,hiSwap) = pivot(count)
    Next

    If loBound < (hiSwap - 1) Then
        Call QuickSortDataArray(dataArray, loBound, hiSwap-1, sortField, sortOrder)
    End If

    If (hiSwap + 1) < hiBound Then
        Call QuickSortDataArray(dataArray, hiSwap+1, hiBound, sortField, sortOrder)
    End If
End Sub

What is PAGEIOLATCH_SH wait type in SQL Server?

From Microsoft documentation:

PAGEIOLATCH_SH

Occurs when a task is waiting on a latch for a buffer that is in an I/O request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.

In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.

If your query is like this:

Select * from <table> where <col1> = <value> order by <PrimaryKey>

, check that you have a composite index on (col1, col_primary_key).

If you don't have one, then you'll need either a full INDEX SCAN if the PRIMARY KEY is chosen, or a SORT if an index on col1 is chosen.

Both of them are very disk I/O consuming operations on large tables.

How to add native library to "java.library.path" with Eclipse launch (instead of overriding it)

Many of the existing answers assume you want to set this for a particular project, but I needed to set it for Eclipse itself in order to support integrated authentication for the SQL Server JDBC driver.

To do this, I followed these instructions for launching Eclipse from the Java commandline instead of its normal launcher. Then I just modified that script to add my -Djava.library.path argument to the Java commandline.

Why do table names in SQL Server start with "dbo"?

Microsoft introduced schema in version 2008. For those who didn’t know about schema, and those who didn’t care, objects were put into a default schema dbo.

dbo stands for DataBase Owner, but that’s not really important.

Think of a schema as you would a folder for files:

  • You don’t need to refer to the schema if the object is in the same or default schema
  • You can reference an object in a different schema by using the schema as a prefix, the way you can reference a file in a different folder.
  • You can’t have two objects with the same name in a single schema, but you can in different schema
  • Using schema can help you to organise a larger number of objects
  • Schema can also be assigned to particular users and roles, so you can control access to who can do what.

You can always access any object from any schema.

Because dbo is the default, you normally don’t need to specify it within a single database:

SELECT * FROM customers;
SELECT * FROM dbo.customers;

mean the same thing.

I am inclined to disagree with the notion of always using the dbo. prefix, since the more you clutter your code with unnecessary detail, the harder it is to read and manage.

For the most part, you can ignore the schema. However, the schema will make itself apparent in the following situations:

  1. If you view the tables in either the object navigator or in an external application, such as Microsoft Excel or Access, you will see the dbo. prefix. You can still ignore it.

  2. If you reference a table in another database, you will need its full name in the form database.schema.table:

    SELECT * FROM bookshop.dbo.customers;
    
  3. For historical reasons, if you write a user defined scalar function, you will need to call it with the schema prefix:

    CREATE FUNCTION tax(@amount DECIMAL(6,2) RETURNS DECIMAL(6,2) AS
    BEGIN
        RETURN @amount * 0.1;
    END;
    GO
    SELECT total, dbo.tax(total) FROM pricelist;
    

    This does not apply to other objects, such as table functions, procedures and views.

You can use schema to overcome naming conflicts. For example, if every user has a personal schema, they can create additional objects without having to fight with other users over the name.

ORA-01653: unable to extend table by in tablespace ORA-06512

Just add a new datafile for the existing tablespace

ALTER TABLESPACE LEGAL_DATA ADD DATAFILE '/u01/oradata/userdata03.dbf' SIZE 200M;

To find out the location and size of your data files:

SELECT FILE_NAME, BYTES FROM DBA_DATA_FILES WHERE TABLESPACE_NAME = 'LEGAL_DATA';

ReactJS - How to use comments?

This is how.

Valid:

...
render() {

  return (
    <p>
       {/* This is a comment, one line */}

       {// This is a block 
        // yoohoo
        // ...
       }

       {/* This is a block 
         yoohoo
         ...
         */
       }
    </p>
  )

}
...

Invalid:

...
render() {

  return (
    <p>
       {// This is not a comment! oops! }

       {//
        Invalid comment
       //}
    </p>
  )

}
...

How to declare a inline object with inline variables without a parent class

You can also do this:

var x = new object[] {
    new { firstName = "john", lastName = "walter" },
    new { brand = "BMW" }
};

And if they are the same anonymous type (firstName and lastName), you won't need to cast as object.

var y = new [] {
    new { firstName = "john", lastName = "walter" },
    new { firstName = "jill", lastName = "white" }
};

Aggregate a dataframe on a given column and display another column

This is how I baseically think of the problem.

my.df <- data.frame(group = rep(c(1,2), each = 3), 
        score = runif(6), info = letters[1:6])
my.agg <- with(my.df, aggregate(score, list(group), max))
my.df.split <- with(my.df, split(x = my.df, f = group))
my.agg$info <- unlist(lapply(my.df.split, FUN = function(x) {
            x[which(x$score == max(x$score)), "info"]
        }))

> my.agg
  Group.1         x info
1       1 0.9344336    a
2       2 0.7699763    e

SQL : BETWEEN vs <= and >=

In this scenario col BETWEEN ... AND ... and col <= ... and col >= ... are equivalent.


SQL Standard defines also T461 Symmetric BETWEEN predicate:

 <between predicate part 2> ::=
 [ NOT ] BETWEEN [ ASYMMETRIC | SYMMETRIC ]
 <row value predicand> AND <row value predicand>

Transact-SQL does not support this feature.

BETWEEN requires that values are sorted. For instance:

SELECT 1 WHERE 3 BETWEEN 10 AND 1
-- no rows

<=>

SELECT 1 WHERE 3 >= 10 AND 3 <= 1
-- no rows

On the other hand:

SELECT 1 WHERE 3 BETWEEN SYMMETRIC 1 AND 10;
-- 1

SELECT 1 WHERE 3 BETWEEN SYMMETRIC 10 AND 1
-- 1

It works exactly as the normal BETWEEN but after sorting the comparison values.

db<>fiddle demo

MySQL - UPDATE query with LIMIT

If you want to update multiple rows using limit in MySQL you can use this construct:

UPDATE table_name SET name='test'
WHERE id IN (
    SELECT id FROM (
        SELECT id FROM table_name 
        ORDER BY id ASC  
        LIMIT 0, 10
    ) tmp
)

What is the best Java QR code generator library?

I don't know what qualifies as best but zxing has a qr code generator for java, is actively developed, and is liberally licensed.

When is a timestamp (auto) updated?

An auto-updated column is automatically updated to the current timestamp when the value of any other column in the row is changed from its current value. An auto-updated column remains unchanged if all other columns are set to their current values.

To explain it let's imagine you have only one row:

-------------------------------
| price | updated_at          |
-------------------------------
|  2    | 2018-02-26 16:16:17 |
-------------------------------

Now, if you run the following update column:

 update my_table
 set price = 2

it will not change the value of updated_at, since price value wasn't actually changed (it was already 2).

But if you have another row with price value other than 2, then the updated_at value of that row (with price <> 3) will be updated to CURRENT_TIMESTAMP.

navbar color in Twitter Bootstrap

You can overwrite the bootstrap colors, including the .navbar-inner class, by targetting it in your own stylesheet as opposed to modifying the bootstrap.css stylesheet, like so:

.navbar-inner {
  background-color: #2c2c2c; /* fallback color, place your own */

  /* Gradients for modern browsers, replace as you see fit */
  background-image: -moz-linear-gradient(top, #333333, #222222);
  background-image: -ms-linear-gradient(top, #333333, #222222);
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#333333), to(#222222));
  background-image: -webkit-linear-gradient(top, #333333, #222222);
  background-image: -o-linear-gradient(top, #333333, #222222);
  background-image: linear-gradient(top, #333333, #222222);
  background-repeat: repeat-x;

  /* IE8-9 gradient filter */
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#333333', endColorstr='#222222', GradientType=0);
}

You just have to modify all of those styles with your own and they will get picked up, like something like this for example, where i eliminate all gradient effects and just set a solid black background-color:

.navbar-inner {
  background-color: #000; /* background color will be black for all browsers */
  background-image: none;
  background-repeat: no-repeat;
  filter: none;
}

You can take advantage of such tools as the Colorzilla Gradient Editor and create your own gradient colors for all browsers and replace the original colors with your own.

And as i mentioned on the comments, i would not recommend you modifying the bootstrap.css stylesheet directly as all of your changes will be lost once the stylesheet gets updated (current version is v2.0.2) so it is preferred that you include all of your changes inside your own stylesheet, in tandem with the bootstrap.css stylesheet. But remember to overwrite all of the appropriate properties to have consistency across browsers.

Git - Undo pushed commits

What I do in these cases is:

  • In the server, move the cursor back to the last known good commit:

    git push -f origin <last_known_good_commit>:<branch_name>
    
  • Locally, do the same:

    git reset --hard <last_known_good_commit>
    #         ^^^^^^
    #         optional
    



See a full example on a branch my_new_branch that I created for this purpose:

$ git branch
my_new_branch

This is the recent history after adding some stuff to myfile.py:

$ git log
commit 80143bcaaca77963a47c211a9cbe664d5448d546
Author: me
Date:   Wed Mar 23 12:48:03 2016 +0100

    Adding new stuff in myfile.py

commit b4zad078237fa48746a4feb6517fa409f6bf238e
Author: me
Date:   Tue Mar 18 12:46:59 2016 +0100

    Initial commit

I want to get rid of the last commit, which was already pushed, so I run:

$ git push -f origin b4zad078237fa48746a4feb6517fa409f6bf238e:my_new_branch
Total 0 (delta 0), reused 0 (delta 0)
To [email protected]:me/myrepo.git
 + 80143bc...b4zad07 b4zad078237fa48746a4feb6517fa409f6bf238e -> my_new_branch (forced update)

Nice! Now I see the file that was changed on that commit (myfile.py) shows in "not staged for commit":

$ git status
On branch my_new_branch
Your branch is up-to-date with 'origin/my_new_branch'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   myfile.py

no changes added to commit (use "git add" and/or "git commit -a")

Since I don't want these changes, I just move the cursor back locally as well:

$ git reset --hard b4zad078237fa48746a4feb6517fa409f6bf238e
HEAD is now at b4zad07 Initial commit

So now HEAD is in the previous commit, both in local and remote:

$ git log
commit b4zad078237fa48746a4feb6517fa409f6bf238e
Author: me
Date:   Tue Mar 18 12:46:59 2016 +0100

    Initial commit

Pandas column of lists, create a row for each list element

Very late answer but I want to add this:

A fast solution using vanilla Python that also takes care of the sample_num column in OP's example. On my own large dataset with over 10 million rows and a result with 28 million rows this only takes about 38 seconds. The accepted solution completely breaks down with that amount of data and leads to a memory error on my system that has 128GB of RAM.

df = df.reset_index(drop=True)
lstcol = df.lstcol.values
lstcollist = []
indexlist = []
countlist = []
for ii in range(len(lstcol)):
    lstcollist.extend(lstcol[ii])
    indexlist.extend([ii]*len(lstcol[ii]))
    countlist.extend([jj for jj in range(len(lstcol[ii]))])
df = pd.merge(df.drop("lstcol",axis=1),pd.DataFrame({"lstcol":lstcollist,"lstcol_num":countlist},
index=indexlist),left_index=True,right_index=True).reset_index(drop=True)

How can I download a file from a URL and save it in Rails?

An even shorter version:

require 'open-uri'
download = open('http://example.com/image.png')
IO.copy_stream(download, '~/image.png')

To keep the same filename:

IO.copy_stream(download, "~/#{download.base_uri.to_s.split('/')[-1]}")

How to embed matplotlib in pyqt - for Dummies

For those looking for a dynamic solution to embed Matplotlib in PyQt5 (even plot data using drag and drop). In PyQt5 you need to use super on the main window class to accept the drops. The dropevent function can be used to get the filename and rest is simple:

def dropEvent(self,e):
        """
        This function will enable the drop file directly on to the 
        main window. The file location will be stored in the self.filename
        """
        if e.mimeData().hasUrls:
            e.setDropAction(QtCore.Qt.CopyAction)
            e.accept()
            for url in e.mimeData().urls():
                if op_sys == 'Darwin':
                    fname = str(NSURL.URLWithString_(str(url.toString())).filePathURL().path())
                else:
                    fname = str(url.toLocalFile())
            self.filename = fname
            print("GOT ADDRESS:",self.filename)
            self.readData()
        else:
            e.ignore() # just like above functions  

For starters the reference complete code gives this output: enter image description here

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

Here is a use case... however I am not too concerned with the technicalities of why I should or not use 1 = 1. I am writing a function, using pyodbc to retrieve some data from SQL Server. I was looking for a way to force a filler after the where keyword in my code. This was a great suggestion indeed:

if _where == '': _where = '1=1'
...
...
...
cur.execute(f'select {predicate} from {table_name} where {_where}')

The reason is because I could not implement the keyword 'where' together inside the _where clause variable. So, I think using any dummy condition that evaluates to true would do as a filler.

1114 (HY000): The table is full

In my case, I was trying to run an alter table command and the available disk space was less than the size of table. Once, I increased the disk space the problem went away.

How can I compile and run c# program without using visual studio?

I use a batch script to compile and run C#:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc /out:%1 %2

@echo off

if errorlevel 1 (
    pause
    exit
)

start %1 %1

I call it like this:

C:\bin\csc.bat "C:\code\MyProgram.exe" "C:\code\MyProgram.cs"

I also have a shortcut in Notepad++, which you can define by going to Run > Run...:

C:\bin\csc.bat "$(CURRENT_DIRECTORY)\$(NAME_PART).exe" "$(FULL_CURRENT_PATH)"

I assigned this shortcut to my F5 key for maximum laziness.

Dynamically create Bootstrap alerts box through JavaScript

Found this today, made a few tweaks and combined the features of the other answers while updating it to bootstrap 3.x. NB: This answer requires jQuery.

In html:

<div id="form_errors" class="alert alert-danger fade in" style="display:none">

In JS:

<script>
//http://stackoverflow.com/questions/10082330/dynamically-create-bootstrap-alerts-box-through-javascript
function bootstrap_alert(elem, message, timeout) {
  $(elem).show().html('<div class="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>');

  if (timeout || timeout === 0) {
    setTimeout(function() { 
      $(elem).alert('close');
    }, timeout);    
  }
};
</script>?

Then you can invoke this either as:

bootstrap_alert('#form_errors', 'This message will fade out in 1 second', 1000)
bootstrap_alert('#form_errors', 'User must dismiss this message manually')

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

It depends on whether you have installed Git Bash in the current user only or all users:

If it is installed on all users then put "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe" in your User Settings (Ctrl + Comma).

If it is installed on only the current user then put "terminal.integrated.shell.windows": "C:\\Users\\<name of your user>\\AppData\\Local\\Programs\\Git\\bin\\bash.exe" in your User Settings (Ctrl + Comma).

If the methods listed above do not work then you should try Christer's solution which says -

If you want the integrated environment you need to point to the sh.exe file inside the bin folder of your Git installation.

So the configuration should say C:\\<my-git-install>\\bin\\sh.exe.

Note: The sh.exe and bash.exe appear completely same to me. There should be no difference between them.

Android file chooser

I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:

My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.

private void startCreation(){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_PICK);
    Uri startDir = Uri.fromFile(new File("/sdcard"));

    intent.setDataAndType(startDir,
            "vnd.android.cursor.dir/lysesoft.andexplorer.file");
    intent.putExtra("browser_filter_extension_whitelist", "*.csv");
    intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
    intent.putExtra("browser_title_background_color",
            getText(R.string.browser_title_background_color));
    intent.putExtra("browser_title_foreground_color",
            getText(R.string.browser_title_foreground_color));
    intent.putExtra("browser_list_background_color",
            getText(R.string.browser_list_background_color));
    intent.putExtra("browser_list_fontscale", "120%");
    intent.putExtra("browser_list_layout", "2");

    try{
         ApplicationInfo info = getPackageManager()
                                 .getApplicationInfo("lysesoft.andexplorer", 0 );

            startActivityForResult(intent, PICK_REQUEST_CODE);
    } catch( PackageManager.NameNotFoundException e ){
        showInstallResultMessage(R.string.error_install_andexplorer);
    } catch (Exception e) {
        Log.w(TAG, e.getMessage());
    }
}

This methos is just pick up a dialog and if user wants install the external application from market

private void showInstallResultMessage(int msg_id) {
    AlertDialog dialog = new AlertDialog.Builder(this).create();
    dialog.setMessage(getText(msg_id));
    dialog.setButton(getText(R.string.button_ok),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
    dialog.setButton2(getText(R.string.button_install),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
                    startActivity(intent);
                    finish();
                }
            });
    dialog.show();
}

Are there inline functions in java?

Well, there are methods could be called "inline" methods in java, but depending on the jvm. After compiling, if the method's machine code is less than 35 byte, it will be transferred to a inline method right away, if the method's machine code is less than 325 byte, it could be transferred into a inline method, depending on the jvm.

Cannot start session without errors in phpMyAdmin

There appears to be two common causes for this error, one is to do with the server configuration and the session.save_path and the other is the browser cache.

If you encounter this error try using a different browser or machine before you attempt to alter your Apache and PHP configurations on the server!

Note that clearing the Cookies for the server is not enough, you need to clear the cache.

In Firefox clearing all history and cookies is easy, but you may not want to get rid of everything. Clearing the cache is hidden away in Firefox:

Tools > Options > Advanced > Network: Cached Web Content - Clear Now

On Selenium WebDriver how to get Text from Span Tag

Your code should read -

String kk = wd.findElement(By.cssSelector("div[id^='customSelect'] span.selectLabel")).getText();

Use CSS. it's much cleaner and easier.. Let me know if that solves your issue.

Generating Unique Random Numbers in Java

This isn't significantly different from other answers, but I wanted the array of integers in the end:

    Integer[] indices = new Integer[n];
    Arrays.setAll(indices, i -> i);
    Collections.shuffle(Arrays.asList(indices));
    return Arrays.stream(indices).mapToInt(Integer::intValue).toArray();

remove url parameters with javascript or jquery

You could use a RegEx to match the value of v and build the URL yourself since you know the URL is youtube.com/watch?v=...

http://jsfiddle.net/akURz/

var url = 'http://youtube.com/watch?v=3sZOD3xKL0Y';
alert(url.match(/v\=([a-z0-9]+)/i));

Passing a String by Reference in Java?

String is immutable in java. you cannot modify/change, an existing string literal/object.

String s="Hello"; s=s+"hi";

Here the previous reference s is replaced by the new refernce s pointing to value "HelloHi".

However, for bringing mutability we have StringBuilder and StringBuffer.

StringBuilder s=new StringBuilder(); s.append("Hi");

this appends the new value "Hi" to the same refernce s. //

Why is the <center> tag deprecated in HTML?

For text and images you can use text-align:

<div style="text-align: center;">
    I'm centered.
</div>

Multiple queries executed in java in single statement

Why dont you try and write a Stored Procedure for this?

You can get the Result Set out and in the same Stored Procedure you can Insert what you want.

The only thing is you might not get the newly inserted rows in the Result Set if you Insert after the Select.

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

Raw SQL Query without DbSet - Entity Framework Core

You can use this (from https://github.com/aspnet/EntityFrameworkCore/issues/1862#issuecomment-451671168 ) :

public static class SqlQueryExtensions
{
    public static IList<T> SqlQuery<T>(this DbContext db, string sql, params object[] parameters) where T : class
    {
        using (var db2 = new ContextForQueryType<T>(db.Database.GetDbConnection()))
        {
            return db2.Query<T>().FromSql(sql, parameters).ToList();
        }
    }

    private class ContextForQueryType<T> : DbContext where T : class
    {
        private readonly DbConnection connection;

        public ContextForQueryType(DbConnection connection)
        {
            this.connection = connection;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // switch on the connection type name to enable support multiple providers
            // var name = con.GetType().Name;
            optionsBuilder.UseSqlServer(connection, options => options.EnableRetryOnFailure());

            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<T>().HasNoKey();
            base.OnModelCreating(modelBuilder);
        }
    }
}

And the usage:

    using (var db = new Db())
    {
        var results = db.SqlQuery<ArbitraryType>("select 1 id, 'joe' name");
        //or with an anonymous type like this
        var results2 = db.SqlQuery(() => new { id =1, name=""},"select 1 id, 'joe' name");
    }

What is the "realm" in basic authentication

According to the RFC 7235, the realm parameter is reserved for defining protection spaces (set of pages or resources where credentials are required) and it's used by the authentication schemes to indicate a scope of protection.

For more details, see the quote below (the highlights are not present in the RFC):

2.2. Protection Space (Realm)

The "realm" authentication parameter is reserved for use by authentication schemes that wish to indicate a scope of protection.

A protection space is defined by the canonical root URI (the scheme and authority components of the effective request URI) of the server being accessed, in combination with the realm value if present. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, that can have additional semantics specific to the authentication scheme. Note that a response can have multiple challenges with the same auth-scheme but with different realms. [...]


Note 1: The framework for HTTP authentication is currently defined by the RFC 7235, which updates the RFC 2617 and makes the RFC 2616 obsolete.

Note 2: The realm parameter is no longer always required on challenges.

Using $setValidity inside a Controller

A better and optimised solution to display multiple validation messages for a single element would be like this.

<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
 <span class="error" ng-message="required"> <your message> </span>
 <span class="error" ng-message="size"> <your message> </span>
 <span class="error" ng-message="filetype"> <your message> </span>
</div>

Controller Code should be the one suggested by @ Ben Lesh

How do I use this JavaScript variable in HTML?

The HTML tags that you want to edit is called the DOM (Document object manipulate), you can edit the DOM with many functions in the document global object.

The best example that would work on almost any browser is the document.getElementById, it's search for html tag with that id set as an attribute.

There is another option which is easier but works only on modern browsers (IE8+), the querySelector function, it's will find the first element with the matched selector (CSS selectors).

Examples for both options:

_x000D_
_x000D_
<script>_x000D_
var name = prompt("What's your name?");_x000D_
var lengthOfName = name.length_x000D_
</script>_x000D_
<body>_x000D_
  <p id="a"></p>_x000D_
  <p id="b"></p>_x000D_
  <script>_x000D_
    document.getElementById('a').innerHTML = name;_x000D_
document.querySelector('#b').innerHTML = name.length;</script>_x000D_
</body>
_x000D_
_x000D_
_x000D_

how to open Jupyter notebook in chrome on windows

I found an easier solution that may help beginners to coding.

go to

C:\Users\'-your user-'\AppData\Roaming\jupyter\runtime

and find a file named

nbserver-6176-open.html

then

Right-click > open with > Choose default program...

Here, what ever you choose would be saved on your Windows to open all HTML files; therefore when you run Jupyter notebook, it would open in the program you want.

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

The problem is that your ApplicationUser inherits from IdentityUser, which is defined like this:

IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser
....
public virtual ICollection<TRole> Roles { get; private set; }
public virtual ICollection<TClaim> Claims { get; private set; }
public virtual ICollection<TLogin> Logins { get; private set; }

and their primary keys are mapped in the method OnModelCreating of the class IdentityDbContext:

modelBuilder.Entity<TUserRole>()
            .HasKey(r => new {r.UserId, r.RoleId})
            .ToTable("AspNetUserRoles");

modelBuilder.Entity<TUserLogin>()
            .HasKey(l => new {l.LoginProvider, l.ProviderKey, l.UserId})
            .ToTable("AspNetUserLogins");

and as your DXContext doesn't derive from it, those keys don't get defined.

If you dig into the sources of Microsoft.AspNet.Identity.EntityFramework, you will understand everything.

I came across this situation some time ago, and I found three possible solutions (maybe there are more):

  1. Use separate DbContexts against two different databases or the same database but different tables.
  2. Merge your DXContext with ApplicationDbContext and use one database.
  3. Use separate DbContexts against the same table and manage their migrations accordingly.

Option 1: See update the bottom.

Option 2: You will end up with a DbContext like this one:

public class DXContext : IdentityDbContext<User, Role,
    int, UserLogin, UserRole, UserClaim>//: DbContext
{
    public DXContext()
        : base("name=DXContext")
    {
        Database.SetInitializer<DXContext>(null);// Remove default initializer
        Configuration.ProxyCreationEnabled = false;
        Configuration.LazyLoadingEnabled = false;
    }

    public static DXContext Create()
    {
        return new DXContext();
    }

    //Identity and Authorization
    public DbSet<UserLogin> UserLogins { get; set; }
    public DbSet<UserClaim> UserClaims { get; set; }
    public DbSet<UserRole> UserRoles { get; set; }
    
    // ... your custom DbSets
    public DbSet<RoleOperation> RoleOperations { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

        // Configure Asp Net Identity Tables
        modelBuilder.Entity<User>().ToTable("User");
        modelBuilder.Entity<User>().Property(u => u.PasswordHash).HasMaxLength(500);
        modelBuilder.Entity<User>().Property(u => u.Stamp).HasMaxLength(500);
        modelBuilder.Entity<User>().Property(u => u.PhoneNumber).HasMaxLength(50);

        modelBuilder.Entity<Role>().ToTable("Role");
        modelBuilder.Entity<UserRole>().ToTable("UserRole");
        modelBuilder.Entity<UserLogin>().ToTable("UserLogin");
        modelBuilder.Entity<UserClaim>().ToTable("UserClaim");
        modelBuilder.Entity<UserClaim>().Property(u => u.ClaimType).HasMaxLength(150);
        modelBuilder.Entity<UserClaim>().Property(u => u.ClaimValue).HasMaxLength(500);
    }
}

Option 3: You will have one DbContext equal to the option 2. Let's name it IdentityContext. And you will have another DbContext called DXContext:

public class DXContext : DbContext
{        
    public DXContext()
        : base("name=DXContext") // connection string in the application configuration file.
    {
        Database.SetInitializer<DXContext>(null); // Remove default initializer
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }

    // Domain Model
    public DbSet<User> Users { get; set; }
    // ... other custom DbSets
    
    public static DXContext Create()
    {
        return new DXContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        // IMPORTANT: we are mapping the entity User to the same table as the entity ApplicationUser
        modelBuilder.Entity<User>().ToTable("User"); 
    }

    public DbQuery<T> Query<T>() where T : class
    {
        return Set<T>().AsNoTracking();
    }
}

where User is:

public class User
{
    public int Id { get; set; }

    [Required, StringLength(100)]
    public string Name { get; set; }

    [Required, StringLength(128)]
    public string SomeOtherColumn { get; set; }
}

With this solution, I'm mapping the entity User to the same table as the entity ApplicationUser.

Then, using Code First Migrations you'll need to generate the migrations for the IdentityContext and THEN for the DXContext, following this great post from Shailendra Chauhan: Code First Migrations with Multiple Data Contexts

You'll have to modify the migration generated for DXContext. Something like this depending on which properties are shared between ApplicationUser and User:

        //CreateTable(
        //    "dbo.User",
        //    c => new
        //        {
        //            Id = c.Int(nullable: false, identity: true),
        //            Name = c.String(nullable: false, maxLength: 100),
        //            SomeOtherColumn = c.String(nullable: false, maxLength: 128),
        //        })
        //    .PrimaryKey(t => t.Id);
        AddColumn("dbo.User", "SomeOtherColumn", c => c.String(nullable: false, maxLength: 128));

and then running the migrations in order (first the Identity migrations) from the global.asax or any other place of your application using this custom class:

public static class DXDatabaseMigrator
{
    public static string ExecuteMigrations()
    {
        return string.Format("Identity migrations: {0}. DX migrations: {1}.", ExecuteIdentityMigrations(),
            ExecuteDXMigrations());
    }

    private static string ExecuteIdentityMigrations()
    {
        IdentityMigrationConfiguration configuration = new IdentityMigrationConfiguration();
        return RunMigrations(configuration);
    }

    private static string ExecuteDXMigrations()
    {
        DXMigrationConfiguration configuration = new DXMigrationConfiguration();
        return RunMigrations(configuration);
    }

    private static string RunMigrations(DbMigrationsConfiguration configuration)
    {
        List<string> pendingMigrations;
        try
        {
            DbMigrator migrator = new DbMigrator(configuration);
            pendingMigrations = migrator.GetPendingMigrations().ToList(); // Just to be able to log which migrations were executed

            if (pendingMigrations.Any())                
                    migrator.Update();     
        }
        catch (Exception e)
        {
            ExceptionManager.LogException(e);
            return e.Message;
        }
        return !pendingMigrations.Any() ? "None" : string.Join(", ", pendingMigrations);
    }
}

This way, my n-tier cross-cutting entities don't end up inheriting from AspNetIdentity classes, and therefore I don't have to import this framework in every project where I use them.

Sorry for the extensive post. I hope it could offer some guidance on this. I have already used options 2 and 3 in production environments.

UPDATE: Expand Option 1

For the last two projects I have used the 1st option: having an AspNetUser class that derives from IdentityUser, and a separate custom class called AppUser. In my case, the DbContexts are IdentityContext and DomainContext respectively. And I defined the Id of the AppUser like this:

public class AppUser : TrackableEntity
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    // This Id is equal to the Id in the AspNetUser table and it's manually set.
    public override int Id { get; set; }

(TrackableEntity is the custom abstract base class that I use in the overridden SaveChanges method of my DomainContext context)

I first create the AspNetUser and then the AppUser. The drawback with this approach is that you have ensured that your "CreateUser" functionality is transactional (remember that there will be two DbContexts calling SaveChanges separately). Using TransactionScope didn't work for me for some reason, so I ended up doing something ugly but that works for me:

        IdentityResult identityResult = UserManager.Create(aspNetUser, model.Password);

        if (!identityResult.Succeeded)
            throw new TechnicalException("User creation didn't succeed", new LogObjectException(result));

        AppUser appUser;
        try
        {
            appUser = RegisterInAppUserTable(model, aspNetUser);
        }
        catch (Exception)
        {
            // Roll back
            UserManager.Delete(aspNetUser);
            throw;
        }

(Please, if somebody comes with a better way of doing this part I appreciate commenting or proposing an edit to this answer)

The benefits are that you don't have to modify the migrations and you can use any crazy inheritance hierarchy over the AppUser without messing with the AspNetUser. And actually, I use Automatic Migrations for my IdentityContext (the context that derives from IdentityDbContext):

public sealed class IdentityMigrationConfiguration : DbMigrationsConfiguration<IdentityContext>
{
    public IdentityMigrationConfiguration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = false;
    }

    protected override void Seed(IdentityContext context)
    {
    }
}

This approach also has the benefit of avoiding to have your n-tier cross-cutting entities inheriting from AspNetIdentity classes.

RSA encryption and decryption in Python

In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key

publickey = key.publickey() # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open('encryption.txt', 'r')
message = f.read()


decrypted = key.decrypt(ast.literal_eval(str(encrypted)))

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

List submodules in a Git repository

If you don't mind operating only on initialized submodules, you can use git submodule foreach to avoid text parsing.

git submodule foreach --quiet 'echo $name'

How to make function decorators and chain them together?

#decorator.py
def makeHtmlTag(tag, *args, **kwds):
    def real_decorator(fn):
        css_class = " class='{0}'".format(kwds["css_class"]) \
                                 if "css_class" in kwds else ""
        def wrapped(*args, **kwds):
            return "<"+tag+css_class+">" + fn(*args, **kwds) + "</"+tag+">"
        return wrapped
    # return decorator dont call it
    return real_decorator

@makeHtmlTag(tag="b", css_class="bold_css")
@makeHtmlTag(tag="i", css_class="italic_css")
def hello():
    return "hello world"

print hello()

You can also write decorator in Class

#class.py
class makeHtmlTagClass(object):
    def __init__(self, tag, css_class=""):
        self._tag = tag
        self._css_class = " class='{0}'".format(css_class) \
                                       if css_class != "" else ""

    def __call__(self, fn):
        def wrapped(*args, **kwargs):
            return "<" + self._tag + self._css_class+">"  \
                       + fn(*args, **kwargs) + "</" + self._tag + ">"
        return wrapped

@makeHtmlTagClass(tag="b", css_class="bold_css")
@makeHtmlTagClass(tag="i", css_class="italic_css")
def hello(name):
    return "Hello, {}".format(name)

print hello("Your name")

Pass parameter from a batch file to a PowerShell script

The answer from @Emiliano is excellent. You can also pass named parameters like so:

powershell.exe -Command 'G:\Karan\PowerShell_Scripts\START_DEV.ps1' -NamedParam1 "SomeDataA" -NamedParam2 "SomeData2"

Note the parameters are outside the command call, and you'll use:

[parameter(Mandatory=$false)]
  [string]$NamedParam1,
[parameter(Mandatory=$false)]
  [string]$NamedParam2

HashMap get/put complexity

In practice, it is O(1), but this actually is a terrible and mathematically non-sense simplification. The O() notation says how the algorithm behaves when the size of the problem tends to infinity. Hashmap get/put works like an O(1) algorithm for a limited size. The limit is fairly large from the computer memory and from the addressing point of view, but far from infinity.

When one says that hashmap get/put is O(1) it should really say that the time needed for the get/put is more or less constant and does not depend on the number of elements in the hashmap so far as the hashmap can be presented on the actual computing system. If the problem goes beyond that size and we need larger hashmaps then, after a while, certainly the number of the bits describing one element will also increase as we run out of the possible describable different elements. For example, if we used a hashmap to store 32bit numbers and later we increase the problem size so that we will have more than 2^32 bit elements in the hashmap, then the individual elements will be described with more than 32bits.

The number of the bits needed to describe the individual elements is log(N), where N is the maximum number of elements, therefore get and put are really O(log N).

If you compare it with a tree set, which is O(log n) then hash set is O(long(max(n)) and we simply feel that this is O(1), because on a certain implementation max(n) is fixed, does not change (the size of the objects we store measured in bits) and the algorithm calculating the hash code is fast.

Finally, if finding an element in any data structure were O(1) we would create information out of thin air. Having a data structure of n element I can select one element in n different way. With that, I can encode log(n) bit information. If I can encode that in zero bit (that is what O(1) means) then I created an infinitely compressing ZIP algorithm.

Spring JUnit: How to Mock autowired component in autowired component

Spring Boot 1.4 introduced testing annotation called @MockBean. So now mocking and spying on Spring beans is natively supported by Spring Boot.

Iterating through a list in reverse order in java

As has been suggested at least twice, you can use descendingIterator with a Deque, in particular with a LinkedList. If you want to use the for-each loop (i.e., have an Iterable), you can construct and use a wraper like this:

import java.util.*;

public class Main {

    public static class ReverseIterating<T> implements Iterable<T> {
        private final LinkedList<T> list;

        public ReverseIterating(LinkedList<T> list) {
            this.list = list;
        }

        @Override
        public Iterator<T> iterator() {
            return list.descendingIterator();
        }
    }

    public static void main(String... args) {
        LinkedList<String> list = new LinkedList<String>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");

        for (String s : new ReverseIterating<String>(list)) {
            System.out.println(s);
        }
    }
}

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

I wouldn't use StringTokenizer as it is one of classes in the JDK that's legacy.

The javadoc says:

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

How to find serial number of Android device?

Starting in Android 10, apps must have the READ_PRIVILEGED_PHONE_STATE privileged permission in order to access the device's non-resettable identifiers, which include both IMEI and serial number.

Affected methods include the following:

Build getSerial() TelephonyManager getImei() getDeviceId() getMeid() getSimSerialNumber() getSubscriberId()

READ_PRIVILEGED_PHONE_STATE is available for platform only

Creating columns in listView and add items

I didn't see anyone answer this correctly. So I'm posting it here. In order to get columns to show up you need to specify the following line.

lvRegAnimals.View = View.Details;

And then add your columns after that.

lvRegAnimals.Columns.Add("Id", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);

Hope this helps anyone else looking for this answer in the future.

"Too many values to unpack" Exception

That exception means that you are trying to unpack a tuple, but the tuple has too many values with respect to the number of target variables. For example: this work, and prints 1, then 2, then 3

def returnATupleWithThreeValues():
    return (1,2,3)
a,b,c = returnATupleWithThreeValues()
print a
print b
print c

But this raises your error

def returnATupleWithThreeValues():
    return (1,2,3)
a,b = returnATupleWithThreeValues()
print a
print b

raises

Traceback (most recent call last):
  File "c.py", line 3, in ?
    a,b = returnATupleWithThreeValues()
ValueError: too many values to unpack

Now, the reason why this happens in your case, I don't know, but maybe this answer will point you in the right direction.

Hibernate-sequence doesn't exist

Just in case someone pulls their hair out with this problem like I did today, I couldn't resolve this error until I changed

spring.jpa.hibernate.dll-auto=create

to

spring.jpa.properties.hibernate.hbm2ddl.auto=create

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Improving upon @Ianl's answer,

It seems that if 2-step authentication is enabled, you have to use token instead of password. You could generate a token here.

If you want to disable the prompts for both the username and password then you can set the URL as follows -

git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git

Note that the URL has both the username and password. Also the .git/config file should show your current settings.


Update 20200128:

If you don't want to store the password in the config file, then you can generate your personal token and replace the password with the token. Here are some details.

It would look like this -

git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git

Java JRE 64-bit download for Windows?

Might this be the download you are looking for?

  1. Go to the Java SE Downloads Page.
  2. Scroll down a tad look for the main table with the header of "Java Platform, Standard Edition"
  3. Click the JRE Download Button (JRE is the runtime component. JDK is the developer's kit).
  4. Select the appropriate download (all platforms and 32/64 bit downloads are listed)

Git error: "Please make sure you have the correct access rights and the repository exists"

Like other answers, use https instead of ssh was the solution.

I post an answer to give a concrete example of a possible solution. I solved this issue with bitbucket when I changed remote url to HTTPS with this command line:

git remote set-url origin <bitbucket_URL>

After that, I could push the content to the repository with this command:

git push -u origin --all

And then I could also use Sourcetree

What size do you use for varchar(MAX) in your parameter declaration?

If you do something like this:

    cmd.Parameters.Add("@blah",SqlDbType.VarChar).Value = "some large text";

size will be taken from "some large text".Length

This can be problematic when it's an output parameter, you get back no more characters then you put as input.

Get selected value of a dropdown's item using jQuery

$("#selector <b>></b> option:selected").val()

Or

$("#selector <b>></b> option:selected").text()

Above codes worked well for me

Determine number of pages in a PDF file

One Line:

int pdfPageCount = System.IO.File.ReadAllText("example.pdf").Split(new string[] { "/Type /Page" }, StringSplitOptions.None).Count()-2;

Recommended: ITEXTSHARP

How do you modify the web.config appSettings at runtime?

Who likes directly to the point,

In your Config

    <appSettings>

    <add key="Conf_id" value="71" />

  </appSettings>

in your code(c#)

///SET
    ConfigurationManager.AppSettings.Set("Conf_id", "whateveryourvalue");
      ///GET              
    string conf = ConfigurationManager.AppSettings.Get("Conf_id").ToString();

How do you convert epoch time in C#?

currently you can simply use

DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()

it will be returned as a 64-bits long

Iterate over a Javascript associative array in sorted order

You cannot iterate over them directly, but you can find all the keys and then just sort them.

var a = new Array();
a['b'] = 1;
a['z'] = 1;
a['a'] = 1;    

function keys(obj)
{
    var keys = [];

    for(var key in obj)
    {
        if(obj.hasOwnProperty(key))
        {
            keys.push(key);
        }
    }

    return keys;
}

keys(a).sort(); // ["a", "b", "z"]

However there is no need to make the variable 'a' an array. You are really just using it as an object and should create it like this:

var a = {};
a["key"] = "value";

Creating a jQuery object from a big HTML-string

You can try something like below

$($.parseHTML(<<table html string variable here>>)).find("td:contains('<<some text to find>>')").first().prev().text();

Linq filter List<string> where it contains a string value from another List<string>

Try the following:

var filteredFileSet = fileList.Where(item => filterList.Contains(item));

When you iterate over filteredFileSet (See LINQ Execution) it will consist of a set of IEnumberable values. This is based on the Where Operator checking to ensure that items within the fileList data set are contained within the filterList set.

As fileList is an IEnumerable set of string values, you can pass the 'item' value directly into the Contains method.

How to do a deep comparison between 2 objects with lodash?

Here's a concise solution:

_.differenceWith(a, b, _.isEqual);

What is the default database path for MongoDB?

The default dbpath for mongodb is /data/db.

There is no default config file, so you will either need to specify this when starting mongod with:

 mongod --config /etc/mongodb.conf

.. or use a packaged install of MongoDB (such as for Redhat or Debian/Ubuntu) which will include a config file path in the service definition.

Note: to check the dbpath and command-line options for a running mongod, connect via the mongo shell and run:

db.serverCmdLineOpts()

In particular, if a custom dbpath is set it will be the value of:

db.serverCmdLineOpts().parsed.dbpath           // MongoDB 2.4 and older
db.serverCmdLineOpts().parsed.storage.dbPath   // MongoDB 2.6+

How do I round a double to two decimal places in Java?

Your Money class could be represented as a subclass of Long or having a member representing the money value as a native long. Then when assigning values to your money instantiations, you will always be storing values that are actually REAL money values. You simply output your Money object (via your Money's overridden toString() method) with the appropriate formatting. e.g $1.25 in a Money object's internal representation is 125. You represent the money as cents, or pence or whatever the minimum denomination in the currency you are sealing with is ... then format it on output. No you can NEVER store an 'illegal' money value, like say $1.257.

c# replace \" characters

Where do these characters occur? Do you see them if you examine the XML data in, say, notepad? Or do you see them when examining the XML data in the debugger. If it is the latter, they are only escape characters for the " characters, and so part of the actual XML data.

Mixing C# & VB In The Same Project

You can not mix vb and c# within the same project - if you notice in visual studio the project files are either .vbproj or .csproj. You can within a solution - have 1 proj in vb and 1 in c#.

Looks like according to this you can potentially use them both in a web project in the App_Code directory:

http://pietschsoft.com/post/2006/03/30/ASPNET-20-Use-VBNET-and-C-within-the-App_Code-folder.aspx

pandas read_csv index_col=None not working with delimiters at the end of each line

Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:

df = pd.read_csv('file.csv', index_col=0)

The above will set the first column as the index (and not add a range index in my "common case").

Update

Given the popularity of this answer, I thought i'd add some context/ a demo:

# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})

In [2]: df
Out[2]:
   A  B
0  1  4
1  2  5
2  3  6

In [3]: df.to_csv('file.csv', index=None)
File[3]:
A  B
1  4
2  5
3  6

Reading without index_col or with None/False will all result in a range index:

In [4]: pd.read_csv('file.csv')
Out[4]:
   A  B
0  1  4
1  2  5
2  3  6

# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
   A  B
0  1  4
1  2  5
2  3  6

In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
   A  B
0  1  4
1  2  5
2  3  6

However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:

In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
   B
A
1  4
2  5
3  6

Sorted array list in Java

I think the choice between SortedSets/Lists and 'normal' sortable collections depends, whether you need sorting only for presentation purposes or at almost every point during runtime. Using a sorted collection may be much more expensive because the sorting is done everytime you insert an element.

If you can't opt for a collection in the JDK, you can take a look at the Apache Commons Collections

Convert char to int in C and C++

Presumably you want this conversion for using functions from the C standard library.

In that case, do (C++ syntax)

typedef unsigned char UChar;

char myCppFunc( char c )
{
    return char( someCFunc( UChar( c ) ) );
}

The expression UChar( c ) converts to unsigned char in order to get rid of negative values, which, except for EOF, are not supported by the C functions.

Then the result of that expression is used as actual argument for an int formal argument. Where you get automatic promotion to int. You can alternatively write that last step explicitly, like int( UChar( c ) ), but personally I find that too verbose.

Cheers & hth.,

Google Chrome redirecting localhost to https

The issue could be replicated in VS 2019 also. This is caused due to "Enable Javascript debugging from Visual Studio IDE". The VS attaches to Chrome and it is a possibility that due to security or reasons known to Google and Microsoft, it sometimes fails to attach and you have this issue. I am able to run http and https with localhost from ASP net core 3.1 app. So while debugging in VS, go to the run with arrow -> IIS express, just below "Web Browser(Chrome)" select "Script Debugging (Disabled)".

See article: https://devblogs.microsoft.com/aspnet/client-side-debugging-of-asp-net-projects-in-google-chrome/

https://docs.microsoft.com/en-us/visualstudio/debugger/debugging-web-applications?view=vs-2019

Always fallback to Microsoft docs to get more clarity than googling an issue.

Maven dependency for Servlet 3.0 API?

This seems to be added recently:

https://repo1.maven.org/maven2/javax/servlet/javax.servlet-api/3.0.1/

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
</dependency>

Loop timer in JavaScript

Note that setTimeout and setInterval are very different functions:

  • setTimeout will execute the code once, after the timeout.
  • setInterval will execute the code forever, in intervals of the provided timeout.

Both functions return a timer ID which you can use to abort the timeout. All you have to do is store that value in a variable and use it as argument to clearTimeout(tid) or clearInterval(tid) respectively.

So, depending on what you want to do, you have two valid choices:

// set timeout
var tid = setTimeout(mycode, 2000);
function mycode() {
  // do some stuff...
  tid = setTimeout(mycode, 2000); // repeat myself
}
function abortTimer() { // to be called when you want to stop the timer
  clearTimeout(tid);
}

or

// set interval
var tid = setInterval(mycode, 2000);
function mycode() {
  // do some stuff...
  // no need to recall the function (it's an interval, it'll loop forever)
}
function abortTimer() { // to be called when you want to stop the timer
  clearInterval(tid);
}

Both are very common ways of achieving the same.

Connect to SQL Server database from Node.js

This is mainly for future readers. As the question (at least the title) focuses on "connecting to sql server database from node js", I would like to chip in about "mssql" node module.

At this moment, we have a stable version of Microsoft SQL Server driver for NodeJs ("msnodesql") available here: https://www.npmjs.com/package/msnodesql. While it does a great job of native integration to Microsoft SQL Server database (than any other node module), there are couple of things to note about.

"msnodesql" require a few pre-requisites (like python, VC++, SQL native client etc.) to be installed on the host machine. That makes your "node" app "Windows" dependent. If you are fine with "Windows" based deployment, working with "msnodesql" is the best.

On the other hand, there is another module called "mssql" (available here https://www.npmjs.com/package/mssql) which can work with "tedious" or "msnodesql" based on configuration. While this module may not be as comprehensive as "msnodesql", it pretty much solves most of the needs.

If you would like to start with "mssql", I came across a simple and straight forward video, which explains about connecting to Microsoft SQL Server database using NodeJs here: https://www.youtube.com/watch?v=MLcXfRH1YzE

Source code for the above video is available here: http://techcbt.com/Post/341/Node-js-basic-programming-tutorials-videos/how-to-connect-to-microsoft-sql-server-using-node-js

Just in case, if the above links are not working, I am including the source code here:

_x000D_
_x000D_
var sql = require("mssql");_x000D_
_x000D_
var dbConfig = {_x000D_
    server: "localhost\\SQL2K14",_x000D_
    database: "SampleDb",_x000D_
    user: "sa",_x000D_
    password: "sql2014",_x000D_
    port: 1433_x000D_
};_x000D_
_x000D_
function getEmp() {_x000D_
    var conn = new sql.Connection(dbConfig);_x000D_
    _x000D_
    conn.connect().then(function () {_x000D_
        var req = new sql.Request(conn);_x000D_
        req.query("SELECT * FROM emp").then(function (recordset) {_x000D_
            console.log(recordset);_x000D_
            conn.close();_x000D_
        })_x000D_
        .catch(function (err) {_x000D_
            console.log(err);_x000D_
            conn.close();_x000D_
        });        _x000D_
    })_x000D_
    .catch(function (err) {_x000D_
        console.log(err);_x000D_
    });_x000D_
_x000D_
    //--> another way_x000D_
    //var req = new sql.Request(conn);_x000D_
    //conn.connect(function (err) {_x000D_
    //    if (err) {_x000D_
    //        console.log(err);_x000D_
    //        return;_x000D_
    //    }_x000D_
    //    req.query("SELECT * FROM emp", function (err, recordset) {_x000D_
    //        if (err) {_x000D_
    //            console.log(err);_x000D_
    //        }_x000D_
    //        else { _x000D_
    //            console.log(recordset);_x000D_
    //        }_x000D_
    //        conn.close();_x000D_
    //    });_x000D_
    //});_x000D_
_x000D_
}_x000D_
_x000D_
getEmp();
_x000D_
_x000D_
_x000D_

The above code is pretty self explanatory. We define the db connection parameters (in "dbConfig" JS object) and then use "Connection" object to connect to SQL Server. In order to execute a "SELECT" statement, in this case, it uses "Request" object which internally works with "Connection" object. The code explains both flavors of using "promise" and "callback" based executions.

The above source code explains only about connecting to sql server database and executing a SELECT query. You can easily take it to the next level by following documentation of "mssql" node available at: https://www.npmjs.com/package/mssql

UPDATE: There is a new video which does CRUD operations using pure Node.js REST standard (with Microsoft SQL Server) here: https://www.youtube.com/watch?v=xT2AvjQ7q9E. It is a fantastic video which explains everything from scratch (it has got heck a lot of code and it will not be that pleasing to explain/copy the entire code here)

Remove directory from remote repository after adding them to .gitignore

If you're working from PowerShell, try the following as a single command.

PS MyRepo> git filter-branch --force --index-filter
>> "git rm --cached --ignore-unmatch -r .\\\path\\\to\\\directory"
>> --prune-empty --tag-name-filter cat -- --all

Then, git push --force --all.

Documentation: https://git-scm.com/docs/git-filter-branch

How to rename a class and its corresponding file in Eclipse?

I found the answers above didn't give me the guidance I needed (I too expected to be in the code for the .java file, and right-click on the tab and see a Refactor option). Here's what I did:

  1. Go to the top of the .java module (ctrl+Home)
  2. Double-click on the class name that is the same name as the .java module and the class name should now be highlight
  3. Right-click the highlighted class name | Open Type Hierarchy. The Type Hierarchy should open showing the class name
  4. Right-click the class name in the Type Hierarchy | Refactor | Rename | type the new name in the popup window Rename Type

How to replace (null) values with 0 output in PIVOT

If you have a situation where you are using dynamic columns in your pivot statement you could use the following:

DECLARE @cols               NVARCHAR(MAX)
DECLARE @colsWithNoNulls    NVARCHAR(MAX)
DECLARE @query              NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(Name) 
            FROM Hospital
            WHERE Active = 1 AND StateId IS NOT NULL
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @colsWithNoNulls = STUFF(
            (
                SELECT distinct ',ISNULL(' + QUOTENAME(Name) + ', ''No'') ' + QUOTENAME(Name)
                FROM Hospital
                WHERE Active = 1 AND StateId IS NOT NULL
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

EXEC ('
        SELECT Clinician, ' + @colsWithNoNulls + '
        FROM
        (
            SELECT DISTINCT p.FullName AS Clinician, h.Name, CASE WHEN phl.personhospitalloginid IS NOT NULL THEN ''Yes'' ELSE ''No'' END AS HasLogin
            FROM Person p
            INNER JOIN personlicense pl ON pl.personid = p.personid
            INNER JOIN LicenseType lt on lt.licensetypeid = pl.licensetypeid
            INNER JOIN licensetypegroup ltg ON ltg.licensetypegroupid = lt.licensetypegroupid
            INNER JOIN Hospital h ON h.StateId = pl.StateId
            LEFT JOIN PersonHospitalLogin phl ON phl.personid = p.personid AND phl.HospitalId = h.hospitalid
            WHERE ltg.Name = ''RN'' AND
                pl.licenseactivestatusid = 2 AND
                h.Active = 1 AND
                h.StateId IS NOT NULL
        ) AS Results
        PIVOT
        (
            MAX(HasLogin)
            FOR Name IN (' + @cols + ')
        ) p
')

How to check the version before installing a package using apt-get?

Also, according to the man page:

apt-cache showpkg <package_name>

can also be used to:

...display information about the packages listed on the command line. Remaining arguments are package names. The available versions and reverse dependencies of each package listed are listed, as well as forward dependencies for each version. Forward (normal) dependencies are those packages upon which the package in question depends; reverse dependencies are those packages that depend upon the package in question. Thus, forward dependencies must be satisfied for a package, but reverse dependencies need not be.

Ex:

apt-cache policy conky

conky:
  Installed: (none)
  Candidate: 1.10.3-1
  Version table:
     1.10.3-1 500
        500 http://us.archive.ubuntu.com/ubuntu yakkety/universe amd64 Packages
        500 http://us.archive.ubuntu.com/ubuntu yakkety/universe i386 Packages

EF 5 Enable-Migrations : No context type was found in the assembly

How to Update table and column in mvc using entity framework code first approach

1: tool > package manager console

2: select current project where context class exist

3: Enable migration using following command PM > enable-migrations

4: Add migration folder name using following command PM > add-migration MyMigrationName

4: Now update database following command PM > update-database

Angular2, what is the correct way to disable an anchor element?

I have used

tabindex="{{isEditedParaOrder?-1:0}}" 
[style.pointer-events]="isEditedParaOrder ?'none':'auto'" 

in my anchor tag so that they can not move to anchor tag by using tab to use "enter" key and also pointer itself we are setting to 'none' based on property 'isEditedParaO rder' whi

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Oracle Error ORA-06512

The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:

 EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';

Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);

// No need for the list
// List<string> list_lines = new List<string>(lines); 

Parallel.ForEach(lines, line =>
{
    //My Stuff
});

This will cause the lines to be parsed in parallel, within the loop. If you want a more detailed, less "reference oriented" introduction to the Parallel class, I wrote a series on the TPL which includes a section on Parallel.ForEach.

What is your most productive shortcut with Vim?

I recently (got) discovered this site: http://vimcasts.org/

It's pretty new and really really good. The guy who is running the site switched from textmate to vim and hosts very good and concise casts on specific vim topics. Check it out!

MongoDB query with an 'or' condition

In case anyone finds it useful, www.querymongo.com does translation between SQL and MongoDB, including OR clauses. It can be really helpful for figuring out syntax when you know the SQL equivalent.

In the case of OR statements, it looks like this

SQL:

SELECT * FROM collection WHERE columnA = 3 OR columnB = 'string';

MongoDB:

db.collection.find({
    "$or": [{
        "columnA": 3
    }, {
        "columnB": "string"
    }]
});

how to download file in react js

You can define a component and use it wherever.

import React from 'react';
import PropTypes from 'prop-types';


export const DownloadLink = ({ to, children, ...rest }) => {

  return (
    <a
      {...rest}
      href={to}
      download
    >
      {children}
    </a>
  );
};


DownloadLink.propTypes = {
  to: PropTypes.string,
  children: PropTypes.any,
};

export default DownloadLink;

How do I make a composite key with SQL Server Management Studio?

enter image description here

  1. Open the design table tab
  2. Highlight your two INT fields (Ctrl/Shift+click on the grey blocks in the very first column)
  3. Right click -> Set primary key

How to force addition instead of concatenation in javascript

Your code concatenates three strings, then converts the result to a number.

You need to convert each variable to a number by calling parseFloat() around each one.

total = parseFloat(myInt1) + parseFloat(myInt2) + parseFloat(myInt3);

jQuery get textarea text

Methinks the word "console" is causing the confusion.

If you want to emulate an old-style full/half duplex console, you'd use something like this:

$('console').keyup(function(event){
    $.get("url", { keyCode: event.which }, ... );
    return true;
});

event.which has the key that was pressed. For backspace handling, event.which === 8.

Listen to changes within a DIV and act accordingly

You can opt to create your own custom events so you'll still have a clear separation of logic.

Bind to a custom event:

$('#laneconfigdisplay').bind('contentchanged', function() {
  // do something after the div content has changed
  alert('woo');
});

In your function that updates the div:

// all logic for grabbing xml and updating the div here ..
// and then send a message/event that we have updated the div
$('#laneconfigdisplay').trigger('contentchanged'); // this will call the function above

Detect IE version (prior to v9) in JavaScript

If you need to delect IE Browser version then you can follow below code. This code working well for version IE6 to IE11

<!DOCTYPE html>
<html>
<body>

<p>Click on Try button to check IE Browser version.</p>

<button onclick="getInternetExplorerVersion()">Try it</button>

<p id="demo"></p>

<script>
function getInternetExplorerVersion() {
   var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");
        var rv = -1;

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer, return version number
        {               
            if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) {
                //For IE 11 >
                if (navigator.appName == 'Netscape') {
                    var ua = navigator.userAgent;
                    var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
                    if (re.exec(ua) != null) {
                        rv = parseFloat(RegExp.$1);
                        alert(rv);
                    }
                }
                else {
                    alert('otherbrowser');
                }
            }
            else {
                //For < IE11
                alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
            }
            return false;
        }}
</script>

</body>
</html>

How do I check if a property exists on a dynamic anonymous type in c#?

In case someone need to handle a dynamic object come from Json, I has modified Seth Reno answer to handle dynamic object deserialized from NewtonSoft.Json.JObjcet.

public static bool PropertyExists(dynamic obj, string name)
    {
        if (obj == null) return false;
        if (obj is ExpandoObject)
            return ((IDictionary<string, object>)obj).ContainsKey(name);
        if (obj is IDictionary<string, object> dict1)
            return dict1.ContainsKey(name);
        if (obj is IDictionary<string, JToken> dict2)
            return dict2.ContainsKey(name);
        return obj.GetType().GetProperty(name) != null;
    }

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

Help -> check for updates upon Eclipse update solved the issue

NSArray + remove item from array

Made a category like mxcl, but this is slightly faster.

My testing shows ~15% improvement (I could be wrong, feel free to compare the two yourself).

Basically I take the portion of the array thats in front of the object and the portion behind and combine them. Thus excluding the element.

- (NSArray *)prefix_arrayByRemovingObject:(id)object 
{
    if (!object) {
        return self;
    }

    NSUInteger indexOfObject = [self indexOfObject:object];
    NSArray *firstSubArray = [self subarrayWithRange:NSMakeRange(0, indexOfObject)];
    NSArray *secondSubArray = [self subarrayWithRange:NSMakeRange(indexOfObject + 1, self.count - indexOfObject - 1)];
    NSArray *newArray = [firstSubArray arrayByAddingObjectsFromArray:secondSubArray];

    return newArray;
}

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

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

When I had the problem recently it was a cross site issue where our dev server hosts our analytics software as well as the application. In the other environments the chrome console would show this error and the javascript file (tracker) on the dev server as the source. This was causing issues for QA personnel who were trying to view the analytics data for their environment (nothing was being captured because of this issue).

The solution to fix this in-house was to add the SSL certificate the DEV site was using to the Trusted People store on the QA people's machine.

If this was a problem in production I would most likely move the javascript into the actual web apps.

JAVA_HOME and PATH are set but java -version still shows the old one

$JAVA_HOME/bin/java -version says 'Permission Denied'

If you cannot access or run code, it which be ignored if added to your path. You need to make it accessible and runnable or get a copy of your own.

Do an

ls -ld $JAVA_HOME $JAVA_HOME/bin $JAVA_HOME/bin/java

to see why you cannot access or run this program,.

Command-line Git on Windows

For me, I'm using Windows 10, @andrew-marshall's instructions worked (Thanks!) except that git.exe was within a cmd directory within PortableGit..., not bin, so I had to put \cmd on the end of the path I added to PATH. Thought I would post this here in case anyone else hits the same issue. You can tell it works once git in a new Command Prompt window returns command usage info and not an error.

Regular expression to match balanced parentheses

This do not fully address the OP question but I though it may be useful to some coming here to search for nested structure regexp:

Parse parmeters from function string (with nested structures) in javascript

Match structures like:
Parse parmeters from function string

  • matches brackets, square brackets, parentheses, single and double quotes

Here you can see generated regexp in action

/**
 * get param content of function string.
 * only params string should be provided without parentheses
 * WORK even if some/all params are not set
 * @return [param1, param2, param3]
 */
exports.getParamsSAFE = (str, nbParams = 3) => {
    const nextParamReg = /^\s*((?:(?:['"([{](?:[^'"()[\]{}]*?|['"([{](?:[^'"()[\]{}]*?|['"([{][^'"()[\]{}]*?['")}\]])*?['")}\]])*?['")}\]])|[^,])*?)\s*(?:,|$)/;
    const params = [];
    while (str.length) { // this is to avoid a BIG performance issue in javascript regexp engine
        str = str.replace(nextParamReg, (full, p1) => {
            params.push(p1);
            return '';
        });
    }
    return params;
};

Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed

In my case. I installed the release-version app. And after uninstall the app from my device. Thing works fine.

Convert seconds to HH-MM-SS with JavaScript?

--update 2

Please use @Frank's a one line solution:

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

It is by far the best solution.

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

Something that is not explicitly said in the documentation or in the answers on this page (even though implied by @Naruto), is that FragmentPagerAdapter will not update the Fragments if the data in the Fragment changes because it keeps the Fragment in memory.

So even if you have a limited number of Fragments to display, if you want to be able to refresh your fragments (say for example you re-run the query to update the listView in the Fragment), you need to use FragmentStatePagerAdapter.

My whole point here is that the number of Fragments and whether or not they are similar is not always the key aspect to consider. Whether or not your fragments are dynamic is also key.

Add resources, config files to your jar using gradle

I ran into the same problem. I had a PNG file in a Java package and it wasn't exported in the final JAR along with the sources, which caused the app to crash upon start (file not found).

None of the answers above solved my problem but I found the solution on the Gradle forums. I added the following to my build.gradle file :

sourceSets.main.resources.srcDirs = [ "src/" ]
sourceSets.main.resources.includes = [ "**/*.png" ]

It tells Gradle to look for resources in the src folder, and ask it to include only PNG files.

EDIT: Beware that if you're using Eclipse, this will break your run configurations and you'll get a main class not found error when trying to run your program. To fix that, the only solution I've found is to move the image(s) to another directory, res/ for example, and to set it as srcDirs instead of src/.

how to add json library

You can also install simplejson.

If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:

 pip install simplejson

This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".

Difference between Hive internal tables and external tables?

Also Keep in mind that Hive is a big data warehouse. When you want to drop a table you dont want to lose Gigabytes or Terabytes of data. Generating, moving and copying data at that scale can be time consuming. When you drop a 'Managed' table hive will also trash its data. When you drop a 'External' table only the schema definition from hive meta-store is removed. The data on the hdfs still remains.

how do I create an array in jquery?

You may be confusing Javascript arrays with PHP arrays. In PHP, arrays are very flexible. They can either be numerically indexed or associative, or even mixed.

array('Item 1', 'Item 2', 'Items 3')  // numerically indexed array
array('first' => 'Item 1', 'second' => 'Item 2')  // associative array
array('first' => 'Item 1', 'Item 2', 'third' => 'Item 3')

Other languages consider these two to be different things, Javascript being among them. An array in Javascript is always numerically indexed:

['Item 1', 'Item 2', 'Item 3']  // array (numerically indexed)

An "associative array", also called Hash or Map, technically an Object in Javascript*, works like this:

{ first : 'Item 1', second : 'Item 2' }  // object (a.k.a. "associative array")

They're not interchangeable. If you need "array keys", you need to use an object. If you don't, you make an array.


* Technically everything is an Object in Javascript, please put that aside for this argument. ;)

"Debug certificate expired" error in Eclipse Android plugins

In Windows 7 it is at the path

C:\Users\[username]\.android
  • goto this path and remove debug.keystore
  • clean and build your project.

Illegal access: this web application instance has been stopped already

In short: this happens likely when you are hot-deploying webapps. For instance, your ide+development server hot-deploys a war again. Threads, that have been created previously are still running. But meanwhile their classloader/context is invalid and faces the IllegalAccessException / IllegalStateException becouse its orgininating webapp (the former runtime-environment) has been redeployed.

So, as states here, a restart does not permanently resolve this issue. Instead, it is better to find/implement a managed Thread Pool, s.th. like this to handle the termination of threads appropriately. In JavaEE you will use these ManagedThreadExeuctorServices. A similar opinion and reference here.

Examples for this are the EvictorThread of Apache Commons Pool, that "cleans" pooled instances according to the pool's configuration (max idle etc.).

python xlrd unsupported format, or corrupt file.

there's nothing wrong with your file. xlrd does not yet support xlsx (excel 2007+) files although it's purported to have supported this for some time.

Simplistix github

2-days ago they committed a pre-alpha version to their git which integrates xlsx support. Other forums suggest that you use a DOM parser for xlsx files since the xlsx file type is just a zip archive containing XML. I have not tried this. there is another package with similar functionality as xlrd and this is called openpyxl which you can get from easy_install or pip. I have not tried this either, however, its API is supposed to be similar to xlrd.

sqlite database default time value 'now'

This is a full example based on the other answers and comments to the question. In the example the timestamp (created_at-column) is saved as unix epoch UTC timezone and converted to local timezone only when necessary.

Using unix epoch saves storage space - 4 bytes integer vs. 24 bytes string when stored as ISO8601 string, see datatypes. If 4 bytes is not enough that can be increased to 6 or 8 bytes.

Saving timestamp on UTC timezone makes it convenient to show a reasonable value on multiple timezones.

SQLite version is 3.8.6 that ships with Ubuntu LTS 14.04.

$ sqlite3 so.db
SQLite version 3.8.6 2014-08-15 11:46:33
Enter ".help" for usage hints.
sqlite> .headers on

create table if not exists example (
   id integer primary key autoincrement
  ,data text not null unique
  ,created_at integer(4) not null default (strftime('%s','now'))
);

insert into example(data) values
 ('foo')
,('bar')
;

select
 id
,data
,created_at as epoch
,datetime(created_at, 'unixepoch') as utc
,datetime(created_at, 'unixepoch', 'localtime') as localtime
from example
order by id
;

id|data|epoch     |utc                |localtime
1 |foo |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02
2 |bar |1412097842|2014-09-30 17:24:02|2014-09-30 20:24:02

Localtime is correct as I'm located at UTC+2 DST at the moment of the query.

window.location (JS) vs header() (PHP) for redirection

The result is same for all options. Redirect.

<meta> in HTML:

  • Show content of your site, and next redirect user after a few (or 0) seconds.
  • Don't need JavaScript enabled.
  • Don't need PHP.

window.location in JS:

  • Javascript enabled needed.
  • Don't need PHP.
  • Show content of your site, and next redirect user after a few (or 0) seconds.
  • Redirect can be dependent on any conditions if (1 === 1) { window.location.href = 'http://example.com'; }.

header('Location:') in PHP:

  • Don't need JavaScript enabled.
  • PHP needed.
  • Redirect will be executed first, user never see what is after. header() must be the first command in php script, before output any other. If you try output some before header, will receive an Warning: Cannot modify header information - headers already sent

Handling null values in Freemarker

Starting from freemarker 2.3.7, you can use this syntax :

${(object.attribute)!}

or, if you want display a default text when the attribute is null :

${(object.attribute)!"default text"}

Is the practice of returning a C++ reference variable evil?

It's not evil. Like many things in C++, it's good if used correctly, but there are many pitfalls you should be aware of when using it (like returning a reference to a local variable).

There are good things that can be achieved with it (like map[name] = "hello world")

How to evaluate http response codes from bash/shell script?

Here is my implementation, which is a bit more verbose than some of the previous answers

curl https://somewhere.com/somepath   \
--silent \
--insecure \
--request POST \
--header "your-curl-may-want-a-header" \
--data @my.input.file \
--output site.output \
--write-out %{http_code} \
  > http.response.code 2> error.messages
errorLevel=$?
httpResponse=$(cat http.response.code)


jq --raw-output 'keys | @csv' site.output | sed 's/"//g' > return.keys
hasErrors=`grep --quiet --invert errors return.keys;echo $?`

if [[ $errorLevel -gt 0 ]] || [[ $hasErrors -gt 0 ]] || [[ "$httpResponse" != "200" ]]; then
  echo -e "Error POSTing https://somewhere.com/somepath with input my.input (errorLevel $errorLevel, http response code $httpResponse)" >> error.messages
  send_exit_message # external function to send error.messages to whoever.
fi

Transpose a range in VBA

First copy the source range then paste-special on target range with Transpose:=True, short sample:

Option Explicit

Sub test()
  Dim sourceRange As Range
  Dim targetRange As Range

  Set sourceRange = ActiveSheet.Range(Cells(1, 1), Cells(5, 1))
  Set targetRange = ActiveSheet.Cells(6, 1)

  sourceRange.Copy
  targetRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
End Sub

The Transpose function takes parameter of type Varaiant and returns Variant.

  Sub transposeTest()
    Dim transposedVariant As Variant
    Dim sourceRowRange As Range
    Dim sourceRowRangeVariant As Variant

    Set sourceRowRange = Range("A1:H1") ' one row, eight columns
    sourceRowRangeVariant = sourceRowRange.Value
    transposedVariant = Application.Transpose(sourceRowRangeVariant)

    Dim rangeFilledWithTransposedData As Range
    Set rangeFilledWithTransposedData = Range("I1:I8") ' eight rows, one column
    rangeFilledWithTransposedData.Value = transposedVariant
  End Sub

I will try to explaine the purpose of 'calling transpose twice'. If u have row data in Excel e.g. "a1:h1" then the Range("a1:h1").Value is a 2D Variant-Array with dimmensions 1 to 1, 1 to 8. When u call Transpose(Range("a1:h1").Value) then u get transposed 2D Variant Array with dimensions 1 to 8, 1 to 1. And if u call Transpose(Transpose(Range("a1:h1").Value)) u get 1D Variant Array with dimension 1 to 8.

First Transpose changes row to column and second transpose changes the column back to row but with just one dimension.

If the source range would have more rows (columns) e.g. "a1:h3" then Transpose function just changes the dimensions like this: 1 to 3, 1 to 8 Transposes to 1 to 8, 1 to 3 and vice versa.

Hope i did not confuse u, my english is bad, sorry :-).

OS X Terminal Colors

You can use the Linux based syntax in one of your startup scripts. Just tested this on an OS X Mountain Lion box.

eg. in your ~/.bash_profile

export TERM="xterm-color" 
export PS1='\[\e[0;33m\]\u\[\e[0m\]@\[\e[0;32m\]\h\[\e[0m\]:\[\e[0;34m\]\w\[\e[0m\]\$ '

This gives you a nice colored prompt. To add the colored ls output, you can add alias ls="ls -G".

To test, just run a source ~/.bash_profile to update your current terminal.

Side note about the colors: The colors are preceded by an escape sequence \e and defined by a color value, composed of [style;color+m] and wrapped in an escaped [] sequence. eg.

  • red = \[\e[0;31m\]
  • bold red (style 1) = \[\e[1;31m\]
  • clear coloring = \[\e[0m\]

I always add a slightly modified color-scheme in the root's .bash_profile to make the username red, so I always see clearly if I'm logged in as root (handy to avoid mistakes if I have many terminal windows open).

In /root/.bash_profile:

PS1='\[\e[0;31m\]\u\[\e[0m\]@\[\e[0;32m\]\h\[\e[0m\]:\[\e[0;34m\]\w\[\e[0m\]\$ '

For all my SSH accounts online I make sure to put the hostname in red, to distinguish if I'm in a local or remote terminal. Just edit the .bash_profile file in your home dir on the server.. If there is no .bash_profile file on the server, you can create it and it should be sourced upon login.

If this is not working as expected for you, please read some of the comments below since I'm not using MacOS very often..

If you want to do this on a remote server, check if the ~/.bash_profile file exists. If not, simply create it and it should be automatically sourced upon your next login.

Delete all local git branches

if you want to delete test branch then

Step1

  • go to other branch
  • git branch -d branch_name

enter image description here

More Detail in depth

React won't load local images

I too would like to add to the answers from @Hawkeye Parker and @Kiszuriwalilibori:

As was noted from the docs here, it is typically best to import the images as needed.

However, I needed many files to be dynamically loaded, which led me to put the images in the public folder (also stated in the README), because of this recommendation below from the documentation:

Normally we recommend importing stylesheets, images, and fonts from JavaScript. The public folder is useful as a workaround for a number of less common cases:

  • You need a file with a specific name in the build output, such as manifest.webmanifest.
  • You have thousands of images and need to dynamically reference their paths.
  • You want to include a small script like pace.js outside of the bundled code.
  • Some library may be incompatible with Webpack and you have no other option but to include it as a tag.

Hope that helps someone else! Leave me a comment if I need to clear any of that up.

querying WHERE condition to character length?

Sorry, I wasn't sure which SQL platform you're talking about:

In MySQL:

$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");

in MSSQL

$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");

The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.

Edit

I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.

So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():

CREATE TABLE words (
    word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;

INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');

SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;

+--------+-----------+----------------+
| word   | num_bytes | num_characters |
+--------+-----------+----------------+
| ??    |         6 |              2 |
| happy  |         5 |              5 |
| hayir  |         6 |              5 |
+--------+-----------+----------------+

Be careful if you're dealing with multi-byte characters.

How to put/get multiple JSONObjects to JSONArray?

I found very good link for JSON: http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object

Here's code to add multiple JSONObjects to JSONArray.

JSONArray Obj = new JSONArray();
try {
    for(int i = 0; i < 3; i++) {
        // 1st object
        JSONObject list1 = new JSONObject();
        list1.put("val1",i+1);
        list1.put("val2",i+2);
        list1.put("val3",i+3);
        obj.put(list1);
    }

} catch (JSONException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}             
Toast.makeText(MainActivity.this, ""+obj, Toast.LENGTH_LONG).show();

How to "select distinct" across multiple data frame columns in pandas?

I think use drop duplicate sometimes will not so useful depending dataframe.

I found this:

[in] df['col_1'].unique()
[out] array(['A', 'B', 'C'], dtype=object)

And work for me!

https://riptutorial.com/pandas/example/26077/select-distinct-rows-across-dataframe

Difference between spring @Controller and @RestController annotation

As you can see in Spring documentation (Spring RestController Documentation) Rest Controller annotation is the same as Controller annotation, but assuming that @ResponseBody is active by default, so all the Java objects are serialized to JSON representation in the response body.

What is the difference between children and childNodes in JavaScript?

Understand that .children is a property of an Element. 1 Only Elements have .children, and these children are all of type Element. 2

However, .childNodes is a property of Node. .childNodes can contain any node. 3

A concrete example would be:

let el = document.createElement("div");
el.textContent = "foo";

el.childNodes.length === 1; // Contains a Text node child.
el.children.length === 0;   // No Element children.

Most of the time, you want to use .children because generally you don't want to loop over Text or Comment nodes in your DOM manipulation.

If you do want to manipulate Text nodes, you probably want .textContent instead. 4


1. Technically, it is an attribute of ParentNode, a mixin included by Element.
2. They are all elements because .children is a HTMLCollection, which can only contain elements.
3. Similarly, .childNodes can hold any node because it is a NodeList.
4. Or .innerText. See the differences here or here.

How to use bootstrap datepicker

You should include bootstrap-datepicker.js after bootstrap.js and you should bind the datepicker to your control.

$(function(){
   $('.datepicker').datepicker({
      format: 'mm-dd-yyyy'
    });
});

How can I check if an ip is in a network in Python?

Here is my code

# -*- coding: utf-8 -*-
import socket


class SubnetTest(object):
    def __init__(self, network):
        self.network, self.netmask = network.split('/')
        self._network_int = int(socket.inet_aton(self.network).encode('hex'), 16)
        self._mask = ((1L << int(self.netmask)) - 1) << (32 - int(self.netmask))
        self._net_prefix = self._network_int & self._mask

    def match(self, ip):
        '''
        ????? IP ???? Network ?? IP
        '''
        ip_int = int(socket.inet_aton(ip).encode('hex'), 16)
        return (ip_int & self._mask) == self._net_prefix

st = SubnetTest('100.98.21.0/24')
print st.match('100.98.23.32')

How can I get the DateTime for the start of the week?

Modulo in C# works bad for -1mod7 (should be 6, c# returns -1) so... "oneliner" solution to this will look like this :)

private static DateTime GetFirstDayOfWeek(DateTime date)
    {
        return date.AddDays(-(((int)date.DayOfWeek - 1) - (int)Math.Floor((double)((int)date.DayOfWeek - 1) / 7) * 7));
    }

POST string to ASP.NET Web Api application - returns null

([FromBody] IDictionary<string,object> data)

What does %s mean in a python format string?

Here is a good example in Python3.

  >>> a = input("What is your name?")
  What is your name?Peter

  >>> b = input("Where are you from?")
  Where are you from?DE

  >>> print("So you are %s of %s" % (a, b))
  So you are Peter of DE

Change WPF window background image in C# code

The problem is the way you are using it in code. Just try the below code

public partial class MainView : Window
{
    public MainView()
    {
        InitializeComponent();

        ImageBrush myBrush = new ImageBrush();
        myBrush.ImageSource =
            new BitmapImage(new Uri("pack://application:,,,/icon.jpg", UriKind.Absolute));
        this.Background = myBrush;
    }
}

You can find more details regarding this in
http://msdn.microsoft.com/en-us/library/aa970069.aspx

How to add a delay for a 2 or 3 seconds

System.Threading.Thread.Sleep(
    (int)System.TimeSpan.FromSeconds(3).TotalMilliseconds);

Or with using statements:

Thread.Sleep((int)TimeSpan.FromSeconds(2).TotalMilliseconds);

I prefer this to 1000 * numSeconds (or simply 3000) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep before. It better documents your intent.

What are the complexity guarantees of the standard containers?

Another quick lookup table is available at this github page

Note : This does not consider all the containers such as, unordered_map etc. but is still great to look at. It is just a cleaner version of this

Java count occurrence of each item in an array

With , you can do it like this:

String[] array = {"name1","name2","name3","name4", "name5", "name2"};
Arrays.stream(array)
      .collect(Collectors.groupingBy(s -> s))
      .forEach((k, v) -> System.out.println(k+" "+v.size()));

Output:

name5 1
name4 1
name3 1
name2 2
name1 1

What it does is:

  • Create a Stream<String> from the original array
  • Group each element by identity, resulting in a Map<String, List<String>>
  • For each key value pair, print the key and the size of the list

If you want to get a Map that contains the number of occurences for each word, it can be done doing:

Map<String, Long> map = Arrays.stream(array)
    .collect(Collectors.groupingBy(s -> s, Collectors.counting()));

For more informations:

Hope it helps! :)

How to delete a file or folder?

shutil.rmtree is the asynchronous function, so if you want to check when it complete, you can use while...loop

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')

Programmatically read from STDIN or input file in Perl

while (<>) {
print;
}

will read either from a file specified on the command line or from stdin if no file is given

If you are required this loop construction in command line, then you may use -n option:

$ perl -ne 'print;'

Here you just put code between {} from first example into '' in second

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

Stephen Darlington makes a very good point, and you can see that if you change my benchmark to use a more realistically sized table if I fill the table out to 10000 rows using the following:

begin 
  for i in 2 .. 10000 loop
    insert into t (NEEDED_FIELD, cond) values (i, 10);
  end loop;
end;

Then re-run the benchmarks. (I had to reduce the loop counts to 5000 to get reasonable times).

declare
  otherVar  number;
  cnt number;
begin
  for i in 1 .. 5000 loop
     select count(*) into cnt from t where cond = 0;

     if (cnt = 1) then
       select NEEDED_FIELD INTO otherVar from t where cond = 0;
     else
       otherVar := 0;
     end if;
   end loop;
end;
/

PL/SQL procedure successfully completed.

Elapsed: 00:00:04.34

declare
  otherVar  number;
begin
  for i in 1 .. 5000 loop
     begin
       select NEEDED_FIELD INTO otherVar from t where cond = 0;
     exception
       when no_data_found then
         otherVar := 0;
     end;
   end loop;
end;
/

PL/SQL procedure successfully completed.

Elapsed: 00:00:02.10

The method with the exception is now more than twice as fast. So, for almost all cases,the method:

SELECT NEEDED_FIELD INTO var WHERE condition;
EXCEPTION
WHEN NO_DATA_FOUND....

is the way to go. It will give correct results and is generally the fastest.

In Python, what happens when you import inside of a function?

It imports once when the function is called for the first time.

I could imagine doing it this way if I had a function in an imported module that is used very seldomly and is the only one requiring the import. Looks rather far-fetched, though...

VBA error 1004 - select method of range class failed

assylias and Head of Catering have already given your the reason why the error is occurring.

Now regarding what you are doing, from what I understand, you don't need to use Select at all

I guess you are doing this from VBA PowerPoint? If yes, then your code be rewritten as

Dim sourceXL As Object, sourceBook As Object
Dim sourceSheet As Object, sourceSheetSum As Object
Dim lRow As Long
Dim measName As Variant, partName As Variant
Dim filepath As String

filepath = CStr(FileDialog)

'~~> Establish an EXCEL application object
On Error Resume Next
Set sourceXL = GetObject(, "Excel.Application")

'~~> If not found then create new instance
If Err.Number <> 0 Then
    Set sourceXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0

Set sourceBook = sourceXL.Workbooks.Open(filepath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")

lRow = sourceSheetSum.Range("C" & sourceSheetSum.Rows.Count).End(xlUp).Row
measName = sourceSheetSum.Range("C3:C" & lRow)

lRow = sourceSheetSum.Range("D" & sourceSheetSum.Rows.Count).End(xlUp).Row
partName = sourceSheetSum.Range("D3:D" & lRow)

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

Click on "Connect as" and select "specific user", then type in the credentials of your user (I used the admin of the server).

Best way to style a TextBox in CSS

You can use:

input[type=text]
{
 /*Styles*/
}

Define your common style attributes inside this. and for extra style you can add a class then.

how to get the current working directory's absolute path from irb

If you want to get the full path of the directory of the current rb file:

File.expand_path('../', __FILE__)

Hash function that produces short hashes?

It is now 2019 and there are better options. Namely, xxhash.

~ echo test | xxhsum                                                           
2d7f1808da1fa63c  stdin

Git/GitHub can't push to master

The below cmnds will fix the issue.

 git pull --rebase
 git push

Java - Getting Data from MySQL database

Here is what I just did right now:

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.sun.javafx.runtime.VersionInfo;  

public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();

public static void main(String args[]) {
    getData();
    }



public static void getData () {

    try {
        Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage", 
 "root", "root");
        
 // here mynewpage is database name, root is username and password
    
Statement stmt = con.createStatement();
        System.out.println("stmt  " + stmt);
        ResultSet rs = stmt.executeQuery("select * from carsData");
        System.out.println("rs  " + rs);
        int count = 1;
        while (rs.next()) {
            String vehicleType = rs.getString("VHCL_TYPE");
            System.out.println(count  +": " + vehicleType);
            count++;

        }

        con.close();
    } catch (Exception e) {
        Logger lgr = Logger.getLogger(VersionInfo.class.getName());
        lgr.log(Level.SEVERE, e.getMessage(), e);

        System.out.println(e.getMessage());
    }
    
    
}

}

The Above code will get you the first column of the table you have.

This is the table which you might need to create in your MySQL database

CREATE TABLE
carsData
(
    VHCL_TYPE CHARACTER(10) NOT NULL,
);

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

htaccess Access-Control-Allow-Origin

The other answers didn't work for me, this is what ended up doing the trick for apache2:

1) Enable the headers mod:

sudo a2enmod headers

2) Create the /etc/apache2/mods-enabled/headers.conf file and insert:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

3) Restart your server:

sudo service apache2 restart