Programs & Examples On #Fileupdate

Get screen width and height in Android

Just to update the answer by parag and SpK to align with current SDK backward compatibility from deprecated methods:

int Measuredwidth = 0;  
int Measuredheight = 0;  
Point size = new Point();
WindowManager w = getWindowManager();

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)    {
    w.getDefaultDisplay().getSize(size);
    Measuredwidth = size.x;
    Measuredheight = size.y; 
}else{
    Display d = w.getDefaultDisplay(); 
    Measuredwidth = d.getWidth(); 
    Measuredheight = d.getHeight(); 
}

java.math.BigInteger cannot be cast to java.lang.Long

It's a very old post, but if it benefits anyone, we can do something like this:

Long max=((BigInteger) Collections.max(dynamics)).longValue(); 

jQuery, checkboxes and .is(":checked")

  $("#checkbox").change(function(e) {

  if ($(this).prop('checked')){
    console.log('checked');
  }
});

Get key from a HashMap using the value

You mixed the keys and the values.

Hashmap <Integer,String> hashmap = new HashMap<Integer, String>();

hashmap.put(100, "one");
hashmap.put(200, "two");

Afterwards a

hashmap.get(100);

will give you "one"

Spring 3 RequestMapping: Get path value

I have a similar problem and I resolved in this way:

@RequestMapping(value = "{siteCode}/**/{fileName}.{fileExtension}")
public HttpEntity<byte[]> getResource(@PathVariable String siteCode,
        @PathVariable String fileName, @PathVariable String fileExtension,
        HttpServletRequest req, HttpServletResponse response ) throws IOException {
    String fullPath = req.getPathInfo();
    // Calling http://localhost:8080/SiteXX/images/argentine/flag.jpg
    // fullPath conentent: /SiteXX/images/argentine/flag.jpg
}

Note that req.getPathInfo() will return the complete path (with {siteCode} and {fileName}.{fileExtension}) so you will have to process conveniently.

"Android library projects cannot be launched"?

right-click in your project and select Properties. In the Properties window -> "Android" -> uncheck the option "is Library" and apply -> Click "ok" to close the properties window.

This is the best answer to solve the problem

Converting Pandas dataframe into Spark dataframe error

Type related errors can be avoided by imposing a schema as follows:

note: a text file was created (test.csv) with the original data (as above) and hypothetical column names were inserted ("col1","col2",...,"col25").

import pyspark
from pyspark.sql import SparkSession
import pandas as pd

spark = SparkSession.builder.appName('pandasToSparkDF').getOrCreate()

pdDF = pd.read_csv("test.csv")

contents of the pandas data frame:

       col1     col2    col3    col4    col5    col6    col7    col8   ... 
0      10000001 1       0       1       12:35   OK      10002   1      ...
1      10000001 2       0       1       12:36   OK      10002   1      ...
2      10000002 1       0       4       12:19   PA      10003   1      ...

Next, create the schema:

from pyspark.sql.types import *

mySchema = StructType([ StructField("col1", LongType(), True)\
                       ,StructField("col2", IntegerType(), True)\
                       ,StructField("col3", IntegerType(), True)\
                       ,StructField("col4", IntegerType(), True)\
                       ,StructField("col5", StringType(), True)\
                       ,StructField("col6", StringType(), True)\
                       ,StructField("col7", IntegerType(), True)\
                       ,StructField("col8", IntegerType(), True)\
                       ,StructField("col9", IntegerType(), True)\
                       ,StructField("col10", IntegerType(), True)\
                       ,StructField("col11", StringType(), True)\
                       ,StructField("col12", StringType(), True)\
                       ,StructField("col13", IntegerType(), True)\
                       ,StructField("col14", IntegerType(), True)\
                       ,StructField("col15", IntegerType(), True)\
                       ,StructField("col16", IntegerType(), True)\
                       ,StructField("col17", IntegerType(), True)\
                       ,StructField("col18", IntegerType(), True)\
                       ,StructField("col19", IntegerType(), True)\
                       ,StructField("col20", IntegerType(), True)\
                       ,StructField("col21", IntegerType(), True)\
                       ,StructField("col22", IntegerType(), True)\
                       ,StructField("col23", IntegerType(), True)\
                       ,StructField("col24", IntegerType(), True)\
                       ,StructField("col25", IntegerType(), True)])

Note: True (implies nullable allowed)

create the pyspark dataframe:

df = spark.createDataFrame(pdDF,schema=mySchema)

confirm the pandas data frame is now a pyspark data frame:

type(df)

output:

pyspark.sql.dataframe.DataFrame

Aside:

To address Kate's comment below - to impose a general (String) schema you can do the following:

df=spark.createDataFrame(pdDF.astype(str)) 

git: Your branch is ahead by X commits

I would like to reiterate the same as mentioned by @Marian Zburlia above. It worked for me and would suggest the same to others.

git pull origin develop

should be followed by $ git pull --rebase.

This will remove the comments coming up on the $ git status after the latest pull.

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

The image below is from the article written by Erwin van der Valk:

image explaining MVC, MVP and MVVM - by Erwin Vandervalk

The article explains the differences and gives some code examples in C#

How to open/run .jar file (double-click not working)?

I had this problem a while back and the solution was really easy.

Just uninstall the current version of Java, download an older one, then uninstall the older and install the latest again.

For example: Java 8 Update 73 current install Java 7 Update 95.

How it works: Java's registry keys were messed up, and when you install the older version they get fixed.

Mongodb: failed to connect to server on first connect

Local MongoDb problem solution

solve it by following the below steps:

Changed

mongodb://localhost:27017/local

to

localhost/local

And the error gone

Determining the current foreground application from a background task or service

From lollipop onwards this got changed. Please find below code, before that user has to go Settings -> Security -> (Scroll down to last) Apps with usage access -> Give the permissions to our app

private void printForegroundTask() {
    String currentApp = "NULL";
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
        long time = System.currentTimeMillis();
        List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,  time - 1000*1000, time);
        if (appList != null && appList.size() > 0) {
            SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
            for (UsageStats usageStats : appList) {
                mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
            }
            if (mySortedMap != null && !mySortedMap.isEmpty()) {
                currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
            }
        }
    } else {
        ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
        currentApp = tasks.get(0).processName;
    }

    Log.e(TAG, "Current App in foreground is: " + currentApp);
}

How to calculate a Mod b in Casio fx-991ES calculator

This calculator does not have any modulo function. However there is quite simple way how to compute modulo using display mode ab/c (instead of traditional d/c).

How to switch display mode to ab/c:

  • Go to settings (Shift + Mode).
  • Press arrow down (to view more settings).
  • Select ab/c (number 1).

Now do your calculation (in comp mode), like 50 / 3 and you will see 16 2/3, thus, mod is 2. Or try 54 / 7 which is 7 5/7 (mod is 5). If you don't see any fraction then the mod is 0 like 50 / 5 = 10 (mod is 0).

The remainder fraction is shown in reduced form, so 60 / 8 will result in 7 1/2. Remainder is 1/2 which is 4/8 so mod is 4.

EDIT: As @lawal correctly pointed out, this method is a little bit tricky for negative numbers because the sign of the result would be negative.

For example -121 / 26 = -4 17/26, thus, mod is -17 which is +9 in mod 26. Alternatively you can add the modulo base to the computation for negative numbers: -121 / 26 + 26 = 21 9/26 (mod is 9).

EDIT2: As @simpatico pointed out, this method will not work for numbers that are out of calculator's precision. If you want to compute say 200^5 mod 391 then some tricks from algebra are needed. For example, using rule (A * B) mod C = ((A mod C) * B) mod C we can write:

200^5 mod 391 = (200^3 * 200^2) mod 391 = ((200^3 mod 391) * 200^2) mod 391 = 98

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

JAVA_HOME is not the name of the java executable. But of the directory, java was installed in. The executable should be $JAVA_HOME/bin/java.

The which command is not helpful for you there. It will not give you the java home, but most likely this is just a wrapper or symlink to java installed in a very different directory.

Remove Duplicates from range of cells in excel vba

To remove duplicates from a single column

 Sub removeDuplicate()
 'removeDuplicate Macro
 Columns("A:A").Select
 ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _ 
 Header:=xlNo 
 Range("A1").Select
 End Sub

if you have header then use Header:=xlYes

Increase your range as per your requirement.
you can make it to 1000 like this :

ActiveSheet.Range("$A$1:$A$1000")

More info here here

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

Doing :

ini_set('memory_limit', '-1');

is never good. If you want to read a very large file, it is a best practise to copy it bit by bit. Try the following code for best practise.

$path = 'path_to_file_.txt';

$file = fopen($path, 'r');
$len = 1024; // 1MB is reasonable for me. You can choose anything though, but do not make it too big
$output = fread( $file, $len );

while (!feof($file)) {
    $output .= fread( $file, $len );
}

fclose($file);

echo 'Output is: ' . $output;

Sort matrix according to first column in R

Read the data:

foo <- read.table(text="1 349
  1 393
  1 392
  4 459
  3 49
  3 32
  2 94")

And sort:

foo[order(foo$V1),]

This relies on the fact that order keeps ties in their original order. See ?order.

Python Script to convert Image into Byte array

Use bytearray:

with open("img.png", "rb") as image:
  f = image.read()
  b = bytearray(f)
  print b[0]

You can also have a look at struct which can do many conversions of that kind.

What is a method group in C#?

A method group is the name for a set of methods (that might be just one) - i.e. in theory the ToString method may have multiple overloads (plus any extension methods): ToString(), ToString(string format), etc - hence ToString by itself is a "method group".

It can usually convert a method group to a (typed) delegate by using overload resolution - but not to a string etc; it doesn't make sense.

Once you add parentheses, again; overload resolution kicks in and you have unambiguously identified a method call.

Which are more performant, CTE or temporary tables?

Late to the party, but...

The environment I work in is highly constrained, supporting some vendor products and providing "value-added" services like reporting. Due to policy and contract limitations, I am not usually allowed the luxury of separate table/data space and/or the ability to create permanent code [it gets a little better, depending upon the application].

IOW, I can't usually develop a stored procedure or UDFs or temp tables, etc. I pretty much have to do everything through MY application interface (Crystal Reports - add/link tables, set where clauses from w/in CR, etc.). One SMALL saving grace is that Crystal allows me to use COMMANDS (as well as SQL Expressions). Some things that aren't efficient through the regular add/link tables capability can be done by defining a SQL Command. I use CTEs through that and have gotten very good results "remotely". CTEs also help w/ report maintenance, not requiring that code be developed, handed to a DBA to compile, encrypt, transfer, install, and then require multiple-level testing. I can do CTEs through the local interface.

The down side of using CTEs w/ CR is, each report is separate. Each CTE must be maintained for each report. Where I can do SPs and UDFs, I can develop something that can be used by multiple reports, requiring only linking to the SP and passing parameters as if you were working on a regular table. CR is not really good at handling parameters into SQL Commands, so that aspect of the CR/CTE aspect can be lacking. In those cases, I usually try to define the CTE to return enough data (but not ALL data), and then use the record selection capabilities in CR to slice and dice that.

So... my vote is for CTEs (until I get my data space).

Execution sequence of Group By, Having and Where clause in SQL Server?

In below Order

  1. FROM & JOIN
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT
  6. ORDER BY
  7. LIMIT

Why are my PHP files showing as plain text?

You need to configure Apache (the webserver) to process PHP scripts as PHP. Check Apache's configuration. You need to load the module (the path may differ on your system):

LoadModule php5_module "c:/php/php5apache.dll"

And you also need to tell Apache what to process with PHP:

AddType application/x-httpd-php .php

See the documentation for more details.

AngularJs ReferenceError: $http is not defined

I have gone through the same problem when I was using

    myApp.controller('mainController', ['$scope', function($scope,) {
        //$http was not working in this
    }]);

I have changed the above code to given below. Remember to include $http(2 times) as given below.

 myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
      //$http is working in this
 }]);

and It has worked well.

How to get screen dimensions as pixels in Android

For who is searching for usable screen dimension without Status Bar and Action Bar (also thanks to Swapnil's answer):

DisplayMetrics dm = getResources().getDisplayMetrics();
float screen_w = dm.widthPixels;
float screen_h = dm.heightPixels;

int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resId > 0) {
    screen_h -= getResources().getDimensionPixelSize(resId);
}

TypedValue typedValue = new TypedValue();
if(getTheme().resolveAttribute(android.R.attr.actionBarSize, typedValue, true)){
    screen_h -= getResources().getDimensionPixelSize(typedValue.resourceId);
}

Detecting superfluous #includes in C/C++?

The problem with detecting superfluous includes is that it can't be just a type dependency checker. A superfluous include is a file which provides nothing of value to the compilation and does not alter another item which other files depend. There are many ways a header file can alter a compile, say by defining a constant, redefining and/or deleting a used macro, adding a namespace which alters the lookup of a name some way down the line. In order to detect items like the namespace you need much more than a preprocessor, you in fact almost need a full compiler.

Lint is more of a style checker and certainly won't have this full capability.

I think you'll find the only way to detect a superfluous include is to remove, compile and run suites.

How to get label of select option with jQuery?

Try this:

$('select option:selected').prop('label');

This will pull out the displayed text for both styles of <option> elements:

  • <option label="foo"><option> -> "foo"
  • <option>bar<option> -> "bar"

If it has both a label attribute and text inside the element, it'll use the label attribute, which is the same behavior as the browser.

For posterity, this was tested under jQuery 3.1.1

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

I solved it by putting this:

@Override
protected void onDestroy() {
    accessTokenTracker.stopTracking();
    super.onDestroy();
}

Error loading the SDK when Eclipse starts

I solve this issue deleting the 10 packages in my android sdk manage.

enter image description here

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

Turns out you can't use the root user in 5.7 anymore without becoming a sudoer. That means you can't just run mysql -u root anymore and have to do sudo mysql -u root instead.

That also means that it will no longer work if you're using the root user in a GUI (or supposedly any non-command line application). To make it work you'll have to create a new user with the required privileges and use that instead.

See this answer for more details.

How do I show/hide a UIBarButtonItem?

One way to do it is use the initWithCustomView:(UIView *) property of when allocating the UIBarButtonItem. Subclass for UIView will have hide/unhide property.

For example:

1. Have a UIButton which you want to hide/unhide.

2. Make the UIButtonas the custom view. Like :

UIButton*myButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];//your button

UIBarButtonItem*yourBarButton=[[UIBarButtonItem alloc] initWithCustomView:myButton];

3. You can hide/unhide the myButton you've created. [myButton setHidden:YES];

Querying Windows Active Directory server using ldapsearch from command line

You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify

How do I create a random alpha-numeric string in C++?

Rather than manually looping, prefer using the appropriate C++ algorithm, in this case std::generate_n, with a proper random number generator:

auto generate_random_alphanumeric_string(std::size_t len) -> std::string {
    static constexpr auto chars =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    thread_local auto rng = random_generator<>();
    auto dist = std::uniform_int_distribution{{}, std::strlen(chars) - 1};
    auto result = std::string(len, '\0');
    std::generate_n(begin(result), len, [&]() { return chars[dist(rng)]; });
    return result;
}

This is close to something I would call the “canonical” solution for this problem.

Unfortunately, correctly seeding a generic C++ random number generator (e.g. MT19937) is really hard. The above code therefore uses a helper function template, random_generator:

template <typename T = std::mt19937>
auto random_generator() -> T {
    auto constexpr seed_bytes = sizeof(typename T::result_type) * T::state_size;
    auto constexpr seed_len = seed_bytes / sizeof(std::seed_seq::result_type);
    auto seed = std::array<std::seed_seq::result_type, seed_len>();
    auto dev = std::random_device();
    std::generate_n(begin(seed), seed_len, std::ref(dev));
    auto seed_seq = std::seed_seq(begin(seed), end(seed));
    return T{seed_seq};
}

This is complex and relatively inefficient. Luckily it’s used to initialise a thread_local variable and is therefore only invoked once per thread.

Finally, the necessary includes for the above are:

#include <algorithm>
#include <array>
#include <cstring>
#include <functional>
#include <random>
#include <string>

The above code uses class template argument deduction and thus requires C++17. It can be trivially adapted for earlier versions by adding the required template arguments.

How to use source: function()... and AJAX in JQuery UI autocomplete

When you ask about:

Blockquote // But what now? How do I display my data? Blockquote

you need to map an array of object, that way:

response([{label: 'result_name', value: 'result_id'},]);

That way when you use the select event of the autocomplete plugin, you can see the result bellow;

Result of the select event

You can use the select event that way:

jQuery("#field").autocomplete({
      source: function (request, response) {

      },
      minLength: 3,
      select: function(event, ui)
      {
        console.log(ui);
      }
  });

I hope that it can help and complement the answers.

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

How to unescape a Java string literal in Java?

Came across a similar problem, wasn't also satisfied with the presented solutions and implemented this one myself.

Also available as a Gist on Github:

/**
 * Unescapes a string that contains standard Java escape sequences.
 * <ul>
 * <li><strong>&#92;b &#92;f &#92;n &#92;r &#92;t &#92;" &#92;'</strong> :
 * BS, FF, NL, CR, TAB, double and single quote.</li>
 * <li><strong>&#92;X &#92;XX &#92;XXX</strong> : Octal character
 * specification (0 - 377, 0x00 - 0xFF).</li>
 * <li><strong>&#92;uXXXX</strong> : Hexadecimal based Unicode character.</li>
 * </ul>
 * 
 * @param st
 *            A string optionally containing standard java escape sequences.
 * @return The translated string.
 */
public String unescapeJavaString(String st) {

    StringBuilder sb = new StringBuilder(st.length());

    for (int i = 0; i < st.length(); i++) {
        char ch = st.charAt(i);
        if (ch == '\\') {
            char nextChar = (i == st.length() - 1) ? '\\' : st
                    .charAt(i + 1);
            // Octal escape?
            if (nextChar >= '0' && nextChar <= '7') {
                String code = "" + nextChar;
                i++;
                if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
                        && st.charAt(i + 1) <= '7') {
                    code += st.charAt(i + 1);
                    i++;
                    if ((i < st.length() - 1) && st.charAt(i + 1) >= '0'
                            && st.charAt(i + 1) <= '7') {
                        code += st.charAt(i + 1);
                        i++;
                    }
                }
                sb.append((char) Integer.parseInt(code, 8));
                continue;
            }
            switch (nextChar) {
            case '\\':
                ch = '\\';
                break;
            case 'b':
                ch = '\b';
                break;
            case 'f':
                ch = '\f';
                break;
            case 'n':
                ch = '\n';
                break;
            case 'r':
                ch = '\r';
                break;
            case 't':
                ch = '\t';
                break;
            case '\"':
                ch = '\"';
                break;
            case '\'':
                ch = '\'';
                break;
            // Hex Unicode: u????
            case 'u':
                if (i >= st.length() - 5) {
                    ch = 'u';
                    break;
                }
                int code = Integer.parseInt(
                        "" + st.charAt(i + 2) + st.charAt(i + 3)
                                + st.charAt(i + 4) + st.charAt(i + 5), 16);
                sb.append(Character.toChars(code));
                i += 5;
                continue;
            }
            i++;
        }
        sb.append(ch);
    }
    return sb.toString();
}

Mapping two integers to one, in a unique and deterministic way

If you want more control such as allocate X bits for the first number and Y bits for the second number, you can use this code:

class NumsCombiner
{

    int num_a_bits_size;
    int num_b_bits_size;

    int BitsExtract(int number, int k, int p)
    {
        return (((1 << k) - 1) & (number >> (p - 1)));
    }

public:
    NumsCombiner(int num_a_bits_size, int num_b_bits_size)
    {
        this->num_a_bits_size = num_a_bits_size;
        this->num_b_bits_size = num_b_bits_size;
    }

    int StoreAB(int num_a, int num_b)
    {
        return (num_b << num_a_bits_size) | num_a;
    }

    int GetNumA(int bnum)
    {
        return BitsExtract(bnum, num_a_bits_size, 1);
    }

    int GetNumB(int bnum)
    {
        return BitsExtract(bnum, num_b_bits_size, num_a_bits_size + 1);
    }
};

I use 32 bits in total. The idea here is that if you want for example that first number will be up to 10 bits and second number will be up to 12 bits, you can do this:

NumsCombiner nums_mapper(10/*bits for first number*/, 12/*bits for second number*/);

Now you can store in num_a the maximum number that is 2^10 - 1 = 1023 and in num_b naximum value of 2^12 - 1 = 4095.

To set value for num A and num B:

int bnum = nums_mapper.StoreAB(10/*value for a*/, 12 /*value from b*/);

Now bnum is all of the bits (32 bits in total. You can modify the code to use 64 bits) To get num a:

int a = nums_mapper.GetNumA(bnum);

To get num b:

int b = nums_mapper.GetNumB(bnum);

EDIT: bnum can be stored inside the class. I did not did it because my own needs I shared the code and hope that it will be helpful.

Thanks for source: https://www.geeksforgeeks.org/extract-k-bits-given-position-number/ for function to extract bits and thanks also to mouviciel answer in this post. Using these to sources I could figure out more advanced solution

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I have same problem after upgrading to Gradle Wrapper 5.1.rec3. I am back to Gradle 4.6

Joining two lists together

List<string> list1 = new List<string>();
list1.Add("dot");
list1.Add("net");

List<string> list2 = new List<string>();
list2.Add("pearls");
list2.Add("!");

var result = list1.Concat(list2);

Get google map link with latitude/longitude

See documentation on how to search using latitude/longitude here.

For location specified as: +38° 34' 24.00", -109° 32' 57.00

https://maps.google.com/maps?q=%2B38%C2%B0+34'+24.00%22,+-109%C2%B0+32'+57.00&ie=UTF-8

Note that the plus signs (%2B) and degree symbols(%C2%B0) need to be properly encoded.

Removing fields from struct or hiding them in JSON Response

Other answers already explained that this isn't possible using the encoding/json package features directly.

Instead, I'd like to offer an alternative solution using a third-party library. Disclaimer: I am the author of the library.

https://github.com/wI2L/jettison

Jettison is a faster and flexible alternative to encoding/json, while still retaining a behavior identical to the standard library by default.

You can use the DenyList option to filter-out fields that should be omitted from the result. Note that the feature is limited, and only works for 1st-level fields.

how to concatenate two dictionaries to create a new one in Python?

You can use the update() method to build a new dictionary containing all the items:

dall = {}
dall.update(d1)
dall.update(d2)
dall.update(d3)

Or, in a loop:

dall = {}
for d in [d1, d2, d3]:
  dall.update(d)

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

I experienced this error when running some very memory-expensive processes. When the system started to run short of memory, I begun to notice this kind of error. I had to change the algorithm in order to make a better use of RAM.

To be noted that while some threads threw this exception, some other threw:

System.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired. The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement. This could be because the pre-login handshake failed or the server was unable to respond back in time. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=43606; handshake=560; ---> System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out

Both problems disappeared after the system was changed so that it could run using less RAM.

HMAC-SHA256 Algorithm for signature calculation

If but any chance you found a solution how to calculate HMAC-SHA256 here, but you're getting an exception like this one:

java.lang.NoSuchMethodError: No static method encodeHexString([B)Ljava/lang/String; in class Lorg/apache/commons/codec/binary/Hex; or its super classes (declaration of 'org.apache.commons.codec.binary.Hex' appears in /system/framework/org.apache.http.legacy.boot.jar)

Then use:

public static String encode(String key, String data) {
    try {
        Mac hmac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        hmac.init(secret_key);
        return new String(Hex.encodeHex(hmac.doFinal(data.getBytes("UTF-8"))));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Sending a notification from a service in Android

Both Activity and Service actually extend Context so you can simply use this as your Context within your Service.

NotificationManager notificationManager =
    (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
Notification notification = new Notification(/* your notification */);
PendingIntent pendingIntent = /* your intent */;
notification.setLatestEventInfo(this, /* your content */, pendingIntent);
notificationManager.notify(/* id */, notification);

One line ftp server in python

For pyftpdlib users. I found this on the pyftpdlib website. This creates anonymous ftp with write access to your filesystem so please use with due care. More features are available under the hood for better security so just go look:

sudo pip3 install pyftpdlib

python3 -m pyftpdlib -w  

## updated for python3 Feb14:2020

Might be helpful for those that tried using the deprecated method above.

sudo python -m pyftpdlib.ftpserver

git clone through ssh

I want to attempt an answer that includes git-flow, and three 'points' or use-cases, the git central repository, the local development and the production machine. This is not well tested.

I am giving incredibly specific commands. Instead of saying <your folder>, I will say /root/git. The only place where I am changing the original command is replacing my specific server name with example.com. I will explain the folders purpose is so you can adjust it accordingly. Please let me know of any confusion and I will update the answer.

The git version on the server is 1.7.1. The server is CentOS 6.3 (Final).

The git version on the development machine is 1.8.1.1. This is Mac OS X 10.8.4.

The central repository and the production machine are on the same machine.

the central repository, which svn users can related to as 'server' is configured as follows. I have a folder /root/git where I keep all my git repositories. I want to create a git repository for a project I call 'flowers'.

cd /root/git
git clone --bare flowers flowers.git

The git command gave two messages:

Initialized empty Git repository in /root/git/flowers.git/
warning: You appear to have cloned an empty repository.

Nothing to worry about.

On the development machine is configured as follows. I have a folder /home/kinjal/Sites where I put all my projects. I now want to get the central git repository.

cd /home/kinjal/Sites
git clone [email protected]:/root/git/flowers.git

This gets me to a point where I can start adding stuff to it. I first set up git flow

git flow init -d

By default this is on branch develop. I add my code here, now. Then I need to commit to the central git repository.

git add .
git commit -am 'initial'
git push

At this point it pushed to the develop branch. I want to also add this to the master branch.

git flow release start v0.0.0 develop
git flow release finish v0.0.0
git push

Note that I did nothing between the release start and release finish. And when I did the release finish I was prompted to edit two files. This pushed the develop branch to master.

On the production site, which is on the same machine as my central git repository, I want put the repository in /var/www/vhosts/example.net. I already have /var/www/vhosts.

cd /var/www/vhosts
git clone file:///root/git/flowers.git example.net

If the production machine would also be on a different machine, the git clone command would look like the one used on the development machine.

Can I call an overloaded constructor from another constructor of the same class in C#?

No, You can't do that, the only place you can call the constructor from another constructor in C# is immediately after ":" after the constructor. for example

class foo
{
    public foo(){}
    public foo(string s ) { }
    public foo (string s1, string s2) : this(s1) {....}

}

Cannot install packages using node package manager in Ubuntu

for me problem was solved by,

sudo apt-get remove node
sudo apt-get remove nodejs
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo ln -s /usr/bin/nodejs /usr/bin/node
alias node=nodejs
rm -r /usr/local/lib/python2.7/dist-packages/localstack/node_modules
npm install -g npm@latest || sudo npm install -g npm@latest

How to add google-services.json in Android?

google-services.json file work like API keys means it store your project_id and api key with json format for all google services(Which enable by you at google console) so no need manage all at different places.

Important process when uses google-services.json

at application gradle you should add

apply plugin: 'com.google.gms.google-services'.

at top level gradle you should add below dependency

  dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

Check if an element is present in an array

I benchmarked it multiple times on Google Chrome 52, but feel free to copypaste it into any other browser's console.


~ 1500 ms, includes (~ 2700 ms when I used the polyfill)

var array = [0,1,2,3,4,5,6,7,8,9]; 
var result = 0;

var start = new Date().getTime();
for(var i = 0; i < 10000000; i++)
{
  if(array.includes("test") === true){ result++; }
}
console.log(new Date().getTime() - start);

~ 1050 ms, indexOf

var array = [0,1,2,3,4,5,6,7,8,9]; 
var result = 0;

var start = new Date().getTime();
for(var i = 0; i < 10000000; i++)
{
  if(array.indexOf("test") > -1){ result++; }
}
console.log(new Date().getTime() - start);

~ 650 ms, custom function

function inArray(target, array)
{

/* Caching array.length doesn't increase the performance of the for loop on V8 (and probably on most of other major engines) */

  for(var i = 0; i < array.length; i++) 
  {
    if(array[i] === target)
    {
      return true;
    }
  }

  return false; 
}

var array = [0,1,2,3,4,5,6,7,8,9]; 
var result = 0;

var start = new Date().getTime();
for(var i = 0; i < 10000000; i++)
{
  if(inArray("test", array) === true){ result++; }
}
console.log(new Date().getTime() - start);

Cannot read property length of undefined

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

Dynamically Add Images React Webpack

If you are bundling your code at the server-side, then there is nothing stopping you from requiring assets directly from jsx:

<div>
  <h1>Image</h1>
  <img src={require('./assets/image.png')} />
</div>

How do I associate file types with an iPhone application?

BIG WARNING: Make ONE HUNDRED PERCENT sure that your extension is not already tied to some mime type.

We used the extension '.icz' for our custom files for, basically, ever, and Safari just never would let you open them saying "Safari cannot open this file." no matter what we did or tried with the UT stuff above.

Eventually I realized that there are some UT* C functions you can use to explore various things, and while .icz gives the right answer (our app):

In app did load at top, just do this...

NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, 
                                                                   (CFStringRef)@"icz", 
                                                                   NULL);
CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);

and put break after that line and see what UTI and ur are -- in our case, it was our identifier as we wanted), and the bundle url (ur) was pointing to our app's folder.

But the MIME type that Dropbox gives us back for our link, which you can check by doing e.g.

$ curl -D headers THEURLGOESHERE > /dev/null
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 27393  100 27393    0     0  24983      0  0:00:01  0:00:01 --:--:-- 28926
$ cat headers
HTTP/1.1 200 OK
accept-ranges: bytes
cache-control: max-age=0
content-disposition: attachment; filename="123.icz"
Content-Type: text/calendar
Date: Fri, 24 May 2013 17:41:28 GMT
etag: 872926d
pragma: public
Server: nginx
x-dropbox-request-id: 13bd327248d90fde
X-RequestId: bf9adc56934eff0bfb68a01d526eba1f
x-server-response-time: 379
Content-Length: 27393
Connection: keep-alive

The Content-Type is what we want. Dropbox claims this is a text/calendar entry. Great. But in my case, I've ALREADY TRIED PUTTING text/calendar into my app's mime types, and it still doesn't work. Instead, when I try to get the UTI and bundle url for the text/calendar mimetype,

NSString * UTI = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType,
                                                                   (CFStringRef)@"text/calendar", 
                                                                   NULL);

CFURLRef ur =UTTypeCopyDeclaringBundleURL(UTI);

I see "com.apple.ical.ics" as the UTI and ".../MobileCoreTypes.bundle/" as the bundle URL. Not our app, but Apple. So I try putting com.apple.ical.ics into the LSItemContentTypes alongside my own, and into UTConformsTo in the export, but no go.

So basically, if Apple thinks they want to at some point handle some form of file type (that could be created 10 years after your app is live, mind you), you will have to change extension cause they'll simply not let you handle the file type.

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

Can I access a form in the controller?

Definitely you can't access form in scope bec. it is not created. The DOM from html template is loaded little bit slowly like controller constructor. the solution is to watch until DOM loaded and all the scope defined!

in controller:

$timeout(function(){
    console.log('customerForm:', $scope.customerForm);
    // everything else what you need
});

How to kill an application with all its activities?

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "LoginActivity".

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.

    if (getIntent().getBooleanExtra("EXIT", false)) {
         finish();
    }

The answer you get to this question from the Android platform is: "Don't make an exit button. Finish activities the user no longer wants, and the Activity manager will clean them up as it sees fit."

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

The supplied link has a very simply example of the n + 1 problem. If you apply it to Hibernate it's basically talking about the same thing. When you query for an object, the entity is loaded but any associations (unless configured otherwise) will be lazy loaded. Hence one query for the root objects and another query to load the associations for each of these. 100 objects returned means one initial query and then 100 additional queries to get the association for each, n + 1.

http://pramatr.com/2009/02/05/sql-n-1-selects-explained/

What I can do to resolve "1 commit behind master"?

If the message is "n commits behind master."

You need to rebase your dev branch with master. You got the above message because after checking out dev branch from master, the master branch got new commit and has moved ahead. You need to get those new commits to your dev branch.

Steps:

git checkout master
git pull        #this will update your local master
git checkout yourDevBranch
git rebase master

there can be some merge conflicts which you have to resolve.

Using two values for one switch case statement

The case values are just codeless "goto" points that can share the same entry point:

case text1:
case text4: 
    //blah
    break;

Note that the braces are redundant.

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

os.path.dirname(__file__) returns empty

import os.path

dirname = os.path.dirname(__file__) or '.'

How to set a Javascript object values dynamically?

When you create an object myObj as you have, think of it more like a dictionary. In this case, it has two keys, name, and age.

You can access these dictionaries in two ways:

  • Like an array (e.g. myObj[name]); or
  • Like a property (e.g. myObj.name); do note that some properties are reserved, so the first method is preferred.

You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.

myObj["name"]

Otherwise, javascript will assume that name is a variable, and since you haven't created a variable called name, it won't be able to access the key you're expecting.

How do check if a PHP session is empty?

I know this is old, but I ran into an issue where I was running a function after checking if there was a session. It would throw an error everytime I tried loading the page after logging out, still worked just logged an error page. Make sure you use exit(); if you are running into the same problem.

     function sessionexists(){
        if(!empty($_SESSION)){
     return true;
         }else{
     return false;
         }
      }


        if (!sessionexists()){
           redirect("https://www.yoursite.com/");
           exit();
           }else{call_user_func('check_the_page');
         } 

How to expire a cookie in 30 minutes using jQuery?

If you're using jQuery Cookie (https://plugins.jquery.com/cookie/), you can use decimal point or fractions.

As one day is 1, one minute would be 1 / 1440 (there's 1440 minutes in a day).

So 30 minutes is 30 / 1440 = 0.02083333.

Final code:

$.cookie("example", "foo", { expires: 30 / 1440, path: '/' });

I've added path: '/' so that you don't forget that the cookie is set on the current path. If you're on /my-directory/ the cookie is only set for this very directory.

How can I copy data from one column to another in the same table?

This will update all the rows in that columns if safe mode is not enabled.

UPDATE table SET columnB = columnA;

If safe mode is enabled then you will need to use a where clause. I use primary key as greater than 0 basically all will be updated

UPDATE table SET columnB = columnA where table.column>0;

sqlalchemy: how to join several tables by one query?

Try this

q = Session.query(
         User, Document, DocumentPermissions,
    ).filter(
         User.email == Document.author,
    ).filter(
         Document.name == DocumentPermissions.document,
    ).filter(
        User.email == 'someemail',
    ).all()

Unable to set variables in bash script

folder = "ABC" tries to run a command named folder with arguments = and "ABC". The format of command in bash is:

command arguments separated with space

while assignment is done with:

variable=something

  • In [ -f $newfoldername/Primetime.eyetv], [ is a command (test) and -f and $newfoldername/Primetime.eyetv] are two arguments. It expects a third argument (]) which it can't find (arguments must be separated with space) and thus will show error.
  • [-f $newfoldername/Primetime.eyetv] tries to run a command [-f with argument $newfoldername/Primetime.eyetv]

Generally for cases like this, paste your code in shellcheck and see the feedback.

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

Using COALESCE to handle NULL values in PostgreSQL

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

COALESCE( NULLIF(yourField,'') , '0' )

The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

mysql alphabetical order

MySQL solution:

select Name from Employee order by Name ;

Order by will order the names from a to z.

Creating a procedure in mySql with parameters

(IN @brugernavn varchar(64)**)**,IN @password varchar(64))

The problem is the )

Convert to date format dd/mm/yyyy

There is also the DateTime object if you want to go that way: http://www.php.net/manual/en/datetime.construct.php

Python module for converting PDF to text

slate is a project that makes it very simple to use PDFMiner from a library:

>>> with open('example.pdf') as f:
...    doc = slate.PDF(f)
...
>>> doc
[..., ..., ...]
>>> doc[1]
'Text from page 2...'   

Switch case with fallthrough?

Try this:

case $VAR in
normal)
    echo "This doesn't do fallthrough"
    ;;
special)
    echo -n "This does "
    ;&
fallthrough)
    echo "fall-through"
    ;;
esac

error: RPC failed; curl transfer closed with outstanding read data remaining

It happens more often than not, I am on a slow internet connection and I have to clone a decently-huge git repository. The most common issue is that the connection closes and the whole clone is cancelled.

Cloning into 'large-repository'...
remote: Counting objects: 20248, done.
remote: Compressing objects: 100% (10204/10204), done.
error: RPC failed; curl 18 transfer closed with outstanding read data remaining 
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed

After a lot of trial and errors and a lot of “remote end hung up unexpectedly” I have a way that works for me. The idea is to do a shallow clone first and then update the repository with its history.

$ git clone http://github.com/large-repository --depth 1
$ cd large-repository
$ git fetch --unshallow

Controlling Spacing Between Table Cells

Use border-collapse and border-spacing to get spaces between the table cells. I would not recommend using floating cells as suggested by QQping.

JSFiddle

Comparing two .jar files

Use Java Decompiler to turn the jar file into source code file, and then use WinMerge to perform comparison.

You should consult the copyright holder of the source code, to see whether it is OK to do so.

Function vs. Stored Procedure in SQL Server

Functions are computed values and cannot perform permanent environmental changes to SQL Server (i.e., no INSERT or UPDATE statements allowed).

A function can be used inline in SQL statements if it returns a scalar value or can be joined upon if it returns a result set.

A point worth noting from comments, which summarize the answer. Thanks to @Sean K Anderson:

Functions follow the computer-science definition in that they MUST return a value and cannot alter the data they receive as parameters (the arguments). Functions are not allowed to change anything, must have at least one parameter, and they must return a value. Stored procs do not have to have a parameter, can change database objects, and do not have to return a value.

Is it possible in Java to catch two exceptions in the same catch block?

Before the launch of Java SE 7 we were habitual of writing code with multiple catch statements associated with a try block. A very basic Example:

 try {
  // some instructions
} catch(ATypeException e) {
} catch(BTypeException e) {
} catch(CTypeException e) {
}

But now with the latest update on Java, instead of writing multiple catch statements we can handle multiple exceptions within a single catch clause. Here is an example showing how this feature can be achieved.

try {
// some instructions
} catch(ATypeException|BTypeException|CTypeException ex) {
   throw e;
}

So multiple Exceptions in a single catch clause not only simplifies the code but also reduce the redundancy of code. I found this article which explains this feature very well along with its implementation. Improved and Better Exception Handling from Java 7 This may help you too.

Remove decimal values using SQL query

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

Othewise, you of course remove it using SQL query:

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

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

Another option is where you have tables like 'type' or 'status', for example, OrderStatus, where you always want to control the Id value, create the Id (Primary Key) column without it being an Identity column is the first place.

How do you get centered content using Twitter Bootstrap?

The best way to do this is define a css style:

.centered-text {
    text-align:center
}    

Then where ever you need centered text you add it like so:

<div class="row">
    <div class="span12 centered-text">
        <h1>Bootstrap starter template</h1>
        <p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
    </div>
</div>

or if you just want the p tag centered:

<div class="row">
    <div class="span12 centered-text">
        <h1>Bootstrap starter template</h1>
        <p class="centered-text">Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
    </div>
</div>

The less inline css you use the better.

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

SDK tools required build tool version installation helped me. You just need to install required build tool version from,

SDK Manager -> SDK tool -> Show Package details -> Select required build tool version and install it.

Explanation of <script type = "text/template"> ... </script>

By setting script tag type other than text/javascript, browser will not execute the internal code of script tag. This is called micro template. This concept is widely used in Single page application(aka SPA).

<script type="text/template">I am a Micro template. 
  I am going to make your web page faster.</script>

For micro template, type of the script tag is text/template. It is very well explained by Jquery creator John Resig http://ejohn.org/blog/javascript-micro-templating/

How do I change db schema to dbo

You can run the following, which will generate a set of ALTER sCHEMA statements for all your talbes:

SELECT 'ALTER SCHEMA dbo TRANSFER ' + TABLE_SCHEMA + '.' + TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'jonathan'

You then have to copy and run the statements in query analyzer.

Here's an older script that will do that for you, too, I think by changing the object owner. Haven't tried it on 2008, though.

DECLARE @old sysname, @new sysname, @sql varchar(1000)

SELECT
  @old = 'jonathan'
  , @new = 'dbo'
  , @sql = '
  IF EXISTS (SELECT NULL FROM INFORMATION_SCHEMA.TABLES
  WHERE
      QUOTENAME(TABLE_SCHEMA)+''.''+QUOTENAME(TABLE_NAME) = ''?''
      AND TABLE_SCHEMA = ''' + @old + '''
  )
  EXECUTE sp_changeobjectowner ''?'', ''' + @new + ''''

EXECUTE sp_MSforeachtable @sql

Got it from this site.

It also talks about doing the same for stored procs if you need to.

How to concatenate a std::string and an int?

In alphabetical order:

std::string name = "John";
int age = 21;
std::string result;

// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);

// 2. with C++11
result = name + std::to_string(age);

// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);

// 4. with FastFormat.Write
fastformat::write(result, name, age);

// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);

// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();

// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);

// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);

// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);

// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);
  1. is safe, but slow; requires Boost (header-only); most/all platforms
  2. is safe, requires C++11 (to_string() is already included in #include <string>)
  3. is safe, and fast; requires FastFormat, which must be compiled; most/all platforms
  4. (ditto)
  5. is safe, and fast; requires the {fmt} library, which can either be compiled or used in a header-only mode; most/all platforms
  6. safe, slow, and verbose; requires #include <sstream> (from standard C++)
  7. is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms
  8. is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms
  9. is brittle (you must supply a large enough buffer), probably the fastest-possible conversion, verbose; requires STLSoft (header-only); most/all platforms
  10. safe-ish (you don't use more than one int_to_string() call in a single statement), fast; requires STLSoft (header-only); Windows-only
  11. is safe, but slow; requires Poco C++ ; most/all platforms

What is the command to truncate a SQL Server log file?

backup log logname with truncate_only followed by a dbcc shrinkfile command

Angularjs on page load call function

Instead of using onload, use Angular's ng-init.

<article id="showSelector" ng-controller="CinemaCtrl" ng-init="myFunction()">

Note: This requires that myFunction is a property of the CinemaCtrl scope.

How to clear cache of Eclipse Indigo

I think you can find the answer you want in these two posts. They are mentioning Flash Builder, but essentially, the talk is about its Eclipse base.

Clear improperly cached compile errors in FlexBuilder: http://blog.aherrman.com/2010/05/clear-improperly-cached-compile-errors.html

How to fix Flash Builder broken workspace: http://va.lent.in/how-to-fix-flash-builder-broken-workspace/

Using UPDATE in stored procedure with optional parameters

Try this.

ALTER PROCEDURE [dbo].[sp_ClientNotes_update]
    @id uniqueidentifier,
    @ordering smallint = NULL,
    @title nvarchar(20) = NULL,
    @content text = NULL
AS
BEGIN
    SET NOCOUNT ON;
    UPDATE tbl_ClientNotes
    SET ordering=ISNULL(@ordering,ordering), 
        title=ISNULL(@title,title), 
        content=ISNULL(@content, content)
    WHERE id=@id
END

It might also be worth adding an extra part to the WHERE clause, if you use transactional replication then it will send another update to the subscriber if all are NULL, to prevent this.

WHERE id=@id AND (@ordering IS NOT NULL OR
                  @title IS NOT NULL OR
                  @content IS NOT NULL)

WARNING: Exception encountered during context initialization - cancelling refresh attempt

  1. To closed ideas,
  2. To remove all folder and file C:/Users/UserName/.m2/org/*,
  3. Open ideas and update Maven project,(right click on project -> maven->update maven project)
  4. After that update the project.

Extracting time from POSIXct

You can use strftime to convert datetimes to any character format:

> t <- strftime(times, format="%H:%M:%S")
> t
 [1] "02:06:49" "03:37:07" "00:22:45" "00:24:35" "03:09:57" "03:10:41"
 [7] "05:05:57" "07:39:39" "06:47:56" "07:56:36"

But that doesn't help very much, since you want to plot your data. One workaround is to strip the date element from your times, and then to add an identical date to all of your times:

> xx <- as.POSIXct(t, format="%H:%M:%S")
> xx
 [1] "2012-03-23 02:06:49 GMT" "2012-03-23 03:37:07 GMT"
 [3] "2012-03-23 00:22:45 GMT" "2012-03-23 00:24:35 GMT"
 [5] "2012-03-23 03:09:57 GMT" "2012-03-23 03:10:41 GMT"
 [7] "2012-03-23 05:05:57 GMT" "2012-03-23 07:39:39 GMT"
 [9] "2012-03-23 06:47:56 GMT" "2012-03-23 07:56:36 GMT"

Now you can use these datetime objects in your plot:

plot(xx, rnorm(length(xx)), xlab="Time", ylab="Random value")

enter image description here


For more help, see ?DateTimeClasses

What are the advantages of NumPy over regular Python lists?

Alex mentioned memory efficiency, and Roberto mentions convenience, and these are both good points. For a few more ideas, I'll mention speed and functionality.

Functionality: You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. And really, who can live without FFTs?

Speed: Here's a test on doing a sum over a list and a NumPy array, showing that the sum on the NumPy array is 10x faster (in this test -- mileage may vary).

from numpy import arange
from timeit import Timer

Nelements = 10000
Ntimeits = 10000

x = arange(Nelements)
y = range(Nelements)

t_numpy = Timer("x.sum()", "from __main__ import x")
t_list = Timer("sum(y)", "from __main__ import y")
print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
print("list:  %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))

which on my systems (while I'm running a backup) gives:

numpy: 3.004e-05
list:  5.363e-04

How to start an Android application from the command line?

Example here.

Pasted below:

This is about how to launch android application from the adb shell.

Command: am

Look for invoking path in AndroidManifest.xml

Browser app::

# am start -a android.intent.action.MAIN -n com.android.browser/.BrowserActivity
Starting: Intent { action=android.intent.action.MAIN comp={com.android.browser/com.android.browser.BrowserActivity} }
Warning: Activity not started, its current task has been brought to the front

Settings app::

# am start -a android.intent.action.MAIN -n com.android.settings/.Settings
Starting: Intent { action=android.intent.action.MAIN comp={com.android.settings/com.android.settings.Settings} }

How do I create a singleton service in Angular 2?

  1. If you want to make service singleton at application level you should define it in app.module.ts

    providers: [ MyApplicationService ] (you can define the same in child module as well to make it that module specific)

    • Do not add this service in provider which creates an instance for that component which breaks the singleton concept, just inject through constructor.
  2. If you want to define singleton service at component level create service, add that service in app.module.ts and add in providers array inside specific component as shown in below snipet.

    @Component({ selector: 'app-root', templateUrl: './test.component.html', styleUrls: ['./test.component.scss'], providers : [TestMyService] })

  3. Angular 6 provide new way to add service at application level. Instead of adding a service class to the providers[] array in AppModule , you can set the following config in @Injectable() :

    @Injectable({providedIn: 'root'}) export class MyService { ... }

The "new syntax" does offer one advantage though: Services can be loaded lazily by Angular (behind the scenes) and redundant code can be removed automatically. This can lead to a better performance and loading speed - though this really only kicks in for bigger services and apps in general.

How to make div follow scrolling smoothly with jQuery?

This one is same on facebook:

_x000D_
_x000D_
<script>_x000D_
var valX = $(window).scrollTop();_x000D_
function syncScroll(target){_x000D_
 var valY = $(window).scrollTop();_x000D_
 var difYX = valY - valX;_x000D_
 var targetX = $(target).scrollTop();_x000D_
 if(valY > valX){_x000D_
  $(target).scrollTop(difYX);_x000D_
 }_x000D_
 if(difYX <= 0){_x000D_
  $(target).scrollTop(-20);_x000D_
 }_x000D_
}_x000D_
_x000D_
$(window).scroll(function(){_x000D_
 syncScroll('#demo');_x000D_
})_x000D_
</script>
_x000D_
body{_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
  height:100%;_x000D_
}_x000D_
#demo{_x000D_
  position:fixed;_x000D_
  height:100vh;_x000D_
  overflow:hidden;_x000D_
  width:40%;_x000D_
}_x000D_
#content{_x000D_
  position:relative;_x000D_
  float:right;_x000D_
  width:60%;_x000D_
  color:red; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
  <div id="demo">_x000D_
    <ul>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
    <ul>_x000D_
  </div>_x000D_
  <div id="content">_x000D_
    <ul>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
    <ul>_x000D_
   </div>   _x000D_
</body
_x000D_
_x000D_
_x000D_

How to transform currentTimeMillis to a readable date format?

There is a simpler way in Android

 DateFormat.getInstance().format(currentTimeMillis);

Moreover, Date is deprecated, so use DateFormat class.

   DateFormat.getDateInstance().format(new Date(0));  
   DateFormat.getDateTimeInstance().format(new Date(0));  
   DateFormat.getTimeInstance().format(new Date(0));  

The above three lines will give:

Dec 31, 1969  
Dec 31, 1969 4:00:00 PM  
4:00:00 PM  12:00:00 AM

How to pass parameters to a Script tag?

Thanks to the jQuery, a simple HTML5 compliant solution is to create an extra HTML tag, like div, to store the data.

HTML:

<div id='dataDiv' data-arg1='content1' data-arg2='content2'>
  <button id='clickButton'>Click me</button>
</div>

JavaScript:

$(document).ready(function() {
    var fetchData = $("#dataDiv").data('arg1') + 
                    $("#dataDiv").data('arg2') ;

    $('#clickButton').click(function() {
      console.log(fetchData);
    })
});

Live demo with the code above: http://codepen.io/anon/pen/KzzNmQ?editors=1011#0

On the live demo, one can see the data from HTML5 data-* attributes to be concatenated and printed to the log.

Source: https://api.jquery.com/data/

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

Import Excel to Datagridview

Since you have not replied to my comment above, I am posting a solution for both.

You are missing ' in Extended Properties

For Excel 2003 try this (TRIED AND TESTED)

    private void button1_Click(object sender, EventArgs e)
    {
        String name = "Items";
        String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                        "C:\\Sample.xls" + 
                        ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();
        sda.Fill(data);
        grid_items.DataSource = data;
    }

BTW, I stopped working with Jet longtime ago. I use ACE now.

    private void button1_Click(object sender, EventArgs e)
    {
        String name = "Items";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        "C:\\Sample.xls" + 
                        ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();
        sda.Fill(data);
        grid_items.DataSource = data;
    }

enter image description here

For Excel 2007+

    private void button1_Click(object sender, EventArgs e)
    {
        String name = "Items";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        "C:\\Sample.xlsx" + 
                        ";Extended Properties='Excel 12.0 XML;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();
        sda.Fill(data);
        grid_items.DataSource = data;
    }

Logging best practices

What frameworks do you use?

We use a mix of the logging application block, and a custom logging helper that works around the .Net framework bits. The LAB is configured to output fairly extensive log files included seperate general trace files for service method entry/exit and specific error files for unexpected issues. The configuration includes date/time, thread, pId etc. for debug assistance as well as the full exception detail and stack (in the case of an unexpected exception).

The custom logging helper makes use of the Trace.Correlation and is particularly handy in the context of logging in WF. For example we have a state machine that invokes a series of sequential workflows. At each of these invoke activities we log the start (using StartLogicalOperation) and then at the end we stop the logical operation with a gereric return event handler.

This has proven useful a few times when attempting to debug failures in complex business sequences as it allows us to determine things like If/Else branch decisions etc. more quickly based on the activity execution sequence.

What log outputs do you use?

We use text files and XML files. Text files are configured through the app block but we've got XML outputs as well from our WF service. This enables us to capture the runtime events (persistence etc.) as well as generic business type exceptions. The text files are rolling logs that are rolled by day and size (I believe total size of 1MB is a rollover point).

What tools to you use for viewing the logs?

We are using Notepad and WCF Service Trace Viewer depending on which output group we're looking at. The WCF Service Trace Viewer is really really handy if you've got your output setup correctly and can make reading the output much simpler. That said, if I know roughly where the error is anyway - just reading a well annotated text file is good as well.

The logs are sent to a single directory which is then split into sub-dirs based on the source service. The root dir is exposed via a website which has it's access controlled by a support user group. This allows us to take a look at production logs without having to put in requests and go through lengthy red tape processes for production data.

How can I make my match non greedy in vim?

What's wrong with

%s/style="[^"]*"//g

One-line list comprehension: if-else variants

I was able to do this

>>> [x if x % 2 != 0 else x * 100 for x in range(1,10)]
    [1, 200, 3, 400, 5, 600, 7, 800, 9]
>>>

Can I bind an array to an IN() condition?

When you have other parameter, you may do like this:

$ids = array(1,2,3,7,8,9);
$db = new PDO(...);
$query = 'SELECT *
            FROM table
           WHERE X = :x
             AND id IN(';
$comma = '';
for($i=0; $i<count($ids); $i++){
  $query .= $comma.':p'.$i;       // :p0, :p1, ...
  $comma = ',';
}
$query .= ')';

$stmt = $db->prepare($query);
$stmt->bindValue(':x', 123);  // some value
for($i=0; $i<count($ids); $i++){
  $stmt->bindValue(':p'.$i, $ids[$i]);
}
$stmt->execute();

add maven repository to build.gradle

Add the maven repository outside the buildscript configuration block of your main build.gradle file as follows:

repositories {
        maven {
            url "https://github.com/jitsi/jitsi-maven-repository/raw/master/releases"
        }
    }

Make sure that you add them after the following:

apply plugin: 'com.android.application'

How can I represent an 'Enum' in Python?

I prefer to define enums in Python like so:

class Animal:
  class Dog: pass
  class Cat: pass

x = Animal.Dog

It's more bug-proof than using integers since you don't have to worry about ensuring that the integers are unique (e.g. if you said Dog = 1 and Cat = 1 you'd be screwed).

It's more bug-proof than using strings since you don't have to worry about typos (e.g. x == "catt" fails silently, but x == Animal.Catt is a runtime exception).

Does C# support multiple inheritance?

As an additional suggestion to what has been suggested, another clever way to provide functionality similar to multiple inheritance is implement multiple interfaces BUT then to provide extension methods on these interfaces. This is called mixins. It's not a real solution but it sometimes handles the issues that would prompt you to want to perform multiple inheritance.

How to automatically redirect HTTP to HTTPS on Apache servers?

I have actually followed this example and it worked for me :)

NameVirtualHost *:80
<VirtualHost *:80>
   ServerName mysite.example.com
   Redirect permanent / https://mysite.example.com/
</VirtualHost>

<VirtualHost _default_:443>
   ServerName mysite.example.com
  DocumentRoot /usr/local/apache2/htdocs
  SSLEngine On
 # etc...
</VirtualHost>

Then do:

/etc/init.d/httpd restart

Getting Current date, time , day in laravel

use DateTime;

$now = new DateTime();

How to enable/disable bluetooth programmatically in android

The solution of prijin worked perfectly for me. It is just fair to mention that two additional permissions are needed:

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

When these are added, enabling and disabling works flawless with the default bluetooth adapter.

Using Tempdata in ASP.NET MVC - Best practice

TempData is a bucket where you can dump data that is only needed for the following request. That is, anything you put into TempData is discarded after the next request completes. This is useful for one-time messages, such as form validation errors. The important thing to take note of here is that this applies to the next request in the session, so that request can potentially happen in a different browser window or tab.

To answer your specific question: there's no right way to use it. It's all up to usability and convenience. If it works, makes sense and others are understanding it relatively easy, it's good. In your particular case, the passing of a parameter this way is fine, but it's strange that you need to do that (code smell?). I'd rather keep a value like this in resources (if it's a resource) or in the database (if it's a persistent value). From your usage, it seems like a resource, since you're using it for the page title.

Hope this helps.

Can anyone recommend a simple Java web-app framework?

I found a really light weight Java web framework the other day.

It's called Jodd and gives you many of the basics you'd expect from Spring, but in a really light package that's <1MB.

http://jodd.org/

JOptionPane YES/No Options Confirm Dialog Box Issue

Try this,

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
  System.out.println("Yes option");
} else {
  System.out.println("No Option");
} 

How to make the window full screen with Javascript (stretching all over the screen)

This code also includes how to enable full screen for Internet Explorer 9, and probably older versions, as well as very recent versions of Google Chrome. The accepted answer may also be used for other browsers.

var el = document.documentElement
    , rfs = // for newer Webkit and Firefox
           el.requestFullscreen
        || el.webkitRequestFullScreen
        || el.mozRequestFullScreen
        || el.msRequestFullscreen
;
if(typeof rfs!="undefined" && rfs){
  rfs.call(el);
} else if(typeof window.ActiveXObject!="undefined"){
  // for Internet Explorer
  var wscript = new ActiveXObject("WScript.Shell");
  if (wscript!=null) {
     wscript.SendKeys("{F11}");
  }
}

Sources:

What is the difference between a data flow diagram and a flow chart?

Data flow diagram shows the flow of data between the different entities and datastores in a system while a flow chart shows the steps involved to carried out a task. In a sense, data flow diagram provides a very high level view of the system, while a flow chart is a lower level view (basically showing the algorithm).

Whether you use data flow diagram or flow charts depends on figuring out what is it that you are trying to show.

Android LinearLayout : Add border with shadow around a LinearLayout

As an alternative, you might use a 9 patch image as the background for your layout, allowing for more "natural" shadows:

enter image description here

Result:

enter image description here

Put the image in your /res/drawable folder.
Make sure the file extension is .9.png, not .png

By the way, this is a modified (reduced to the minimum square size) of an existing resource found in the API 19 sdk resources folder.
I left the red markers, since they don't seem to be harmful, as shown in the draw9patch tool.

[EDIT]

About 9 patches, in case you never had anything to do with them.

Simply add it as the background of your View.

The black-marked areas (left and top) will stretch (vertically, horizontally).
The black-marked areas (right, bottom) define the "content area" (where it's possible to add text or Views - you can call the unmarked regions "padding", if you like to).

Tutorial: http://radleymarx.com/blog/simple-guide-to-9-patch/

Get width/height of SVG element

FireFox have problemes for getBBox(), i need to do this in vanillaJS.

I've a better Way and is the same result as real svg.getBBox() function !

With this good post : Get the real size of a SVG/G element

var el   = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle

console.log( rect.width );
console.log( rect.height);

composer laravel create project

  1. Create project
  2. Open: Root (htdocs)\
  3. Press: Shift + Open command windows here
  4. Type: php composer.phar create-project --prefer-dist laravel/laravel lar-project "5.7.*"

json_decode() expects parameter 1 to be string, array given

json_decode() is used to decode a json string to an array/data object. json_encode() creates a json string from an array or data. You are using the wrong function my friend, try json_encode();

Excel - find cell with same value in another worksheet and enter the value to the left of it

The easiest way is probably with VLOOKUP(). This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.

For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:

=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)

Then simply fill this formula down the rest of column D.

Explanation:

  • The first argument $D2 specifies the value to search for.
  • The second argument Sheet2!$A$2:$B$65535 specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535). Note I am assuming you have a header cell in row 1.
  • The third argument 2 specifies a 1-based index of the column to return from within the searched range. The value of 2 will return the second column in the range Sheet2!$A$2:$B$65535, namely the value of the B column.
  • The fourth argument FALSE says to only return exact matches.

Angular: conditional class with *ngClass

Additionally, you can add with method function:

In HTML

<div [ngClass]="setClasses()">...</div>

In component.ts

// Set Dynamic Classes
  setClasses() {
    let classes = {
      constantClass: true,
      'conditional-class': this.item.id === 1
    }

    return classes;
  }

How do I add an image to a JButton

public class ImageButton extends JButton {

    protected ImageButton(){
    }

    @Override
        public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Image img = Toolkit.getDefaultToolkit().getImage("water.bmp");

        g2.drawImage(img, 45, 35, this);
        g2.finalize();
    }
}

OR use this code

class MyButton extends JButton {

    Image image;
    ImageObserver imageObserver;


    MyButtonl(String filename) {
            super();
            ImageIcon icon = new ImageIcon(filename);
            image = icon.getImage();
            imageObserver = icon.getImageObserver();
        }

     public void paint( Graphics g ) {
            super.paint( g );
            g.drawImage(image,  0 , 0 , getWidth() , getHeight() , imageObserver);
        }
    }

how I can show the sum of in a datagridview column?

int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
    sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
}
label1.Text = sum.ToString();

Converting HTML files to PDF

Check out iText; it is a pure Java PDF toolkit which has support for reading data from HTML. I used it recently in a project when I needed to pull content from our CMS and export as PDF files, and it was all rather straightforward. The support for CSS and style tags is pretty limited, but it does render tables without any problems (I never managed to set column width though).

Creating a PDF from HTML goes something like this:

Document doc = new Document(PageSize.A4);
PdfWriter.getInstance(doc, out);
doc.open();
HTMLWorker hw = new HTMLWorker(doc);
hw.parse(new StringReader(html));
doc.close();

Bootstrap 3 Horizontal and Vertical Divider

Add the right lines this way and and the horizontal borders using HR or border-bottom or .col-right-line:after. Don't forget media queries to get rid of the lines on small devices.

.col-right-line:before {
  position: absolute;
  content: " ";
  top: 0;
  right: 0;
  height: 100%;
  width: 1px;
  background-color: @color-neutral;
}

Why is synchronized block better than synchronized method?

Although not usually a concern, from a security perspective, it is better to use synchronized on a private object, rather than putting it on a method.

Putting it on the method means you are using the lock of the object itself to provide thread safety. With this kind of mechanism, it is possible for a malicious user of your code to also obtain the lock on your object, and hold it forever, effectively blocking other threads. A non-malicious user can effectively do the same thing inadvertently.

If you use the lock of a private data member, you can prevent this, since it is impossible for a malicious user to obtain the lock on your private object.

private final Object lockObject = new Object();

public void getCount() {
    synchronized( lockObject ) {
        ...
    }
}

This technique is mentioned in Bloch's Effective Java (2nd Ed), Item #70

Get Android shared preferences value in activity/normal class

You use uninstall the app and change the sharedPreferences name then run this application. I think it will resolve the issue.

A sample code to retrieve values from sharedPreferences you can use the following set of code,

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyValue, ""));

HTTP GET with request body

IMHO you could just send the JSON encoded (ie. encodeURIComponent) in the URL, this way you do not violate the HTTP specs and get your JSON to the server.

How to debug external class library projects in visual studio?

I was having a similar issue as my breakpoints in project(B) were not being hit. My solution was to rebuild project(B) then debug project(A) as the dlls needed to be updated.

Visual studio should allow you to debug into an external library.

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

or

TypeError: 'numpy.float64' object is not iterable

The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:

def MinMax(x, mini=0, maxi=1)
    return max(min(x,mini), maxi)

The solution was avoid numpy or math:

def MinMax(x, mini=0, maxi=1)
    x = [x_aux if x_aux > mini else mini for x_aux in x]
    x = [x_aux if x_aux < maxi else maxi for x_aux in x]
    return max(min(x,mini), maxi)

Then, everything calm again. It was like one library possessed max and min!

Best way to encode text data for XML

In the past I have used HttpUtility.HtmlEncode to encode text for xml. It performs the same task, really. I havent ran into any issues with it yet, but that's not to say I won't in the future. As the name implies, it was made for HTML, not XML.

You've probably already read it, but here is an article on xml encoding and decoding.

EDIT: Of course, if you use an xmlwriter or one of the new XElement classes, this encoding is done for you. In fact, you could just take the text, place it in a new XElement instance, then return the string (.tostring) version of the element. I've heard that SecurityElement.Escape will perform the same task as your utility method as well, but havent read much about it or used it.

EDIT2: Disregard my comment about XElement, since you're still on 2.0

How to extract one column of a csv file

Many answers for this questions are great and some have even looked into the corner cases. I would like to add a simple answer that can be of daily use... where you mostly get into those corner cases (like having escaped commas or commas in quotes etc.,).

FS (Field Separator) is the variable whose value is dafaulted to space. So awk by default splits at space for any line.

So using BEGIN (Execute before taking input) we can set this field to anything we want...

awk 'BEGIN {FS = ","}; {print $3}'

The above code will print the 3rd column in a csv file.

How to delete multiple values from a vector?

There is also subset which might be useful sometimes:

a <- sample(1:10)
bad <- c(2, 3, 5)

> subset(a, !(a %in% bad))
[1]  9  7 10  6  8  1  4

Check if one list contains element from the other

There is one method of Collection named retainAll but having some side effects for you reference

Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

true if this list changed as a result of the call

Its like

boolean b = list1.retainAll(list2);

Get list of all tables in Oracle?

select * from all_all_tables

this additional 'all' at the beginning gives extra 3 columns which are:

OBJECT_ID_TYPE
TABLE_TYPE_OWNER
TABLE_TYPE

Posting form to different MVC post action depending on the clicked submit button

This sounds to me like what you have is one command with 2 outputs, I would opt for making the change in both client and server for this.

At the client, use JS to build up the URL you want to post to (use JQuery for simplicity) i.e.

<script type="text/javascript">
    $(function() {
        // this code detects a button click and sets an `option` attribute
        // in the form to be the `name` attribute of whichever button was clicked
        $('form input[type=submit]').click(function() {
            var $form = $('form');
            form.removeAttr('option');
            form.attr('option', $(this).attr('name'));
        });
        // this code updates the URL before the form is submitted
        $("form").submit(function(e) { 
            var option = $(this).attr("option");
            if (option) {
                e.preventDefault();
                var currentUrl = $(this).attr("action");
                $(this).attr('action', currentUrl + "/" + option).submit();     
            }
        });
    });
</script>
...
<input type="submit" ... />
<input type="submit" name="excel" ... />

Now at the server side we can add a new route to handle the excel request

routes.MapRoute(
    name: "ExcelExport",
    url: "SearchDisplay/Submit/excel",
    defaults: new
    {
        controller = "SearchDisplay",
        action = "SubmitExcel",
    });

You can setup 2 distinct actions

public ActionResult SubmitExcel(SearchCostPage model)
{
   ...
}

public ActionResult Submit(SearchCostPage model)
{
   ...
}

Or you can use the ActionName attribute as an alias

public ActionResult Submit(SearchCostPage model)
{
   ...
}

[ActionName("SubmitExcel")]
public ActionResult Submit(SearchCostPage model)
{
   ...
}

Determine if running on a rooted device

Many of the answers listed here have inherent issues:

  • Checking for test-keys is correlated with root access but doesn't necessarily guarantee it
  • "PATH" directories should be derived from the actual "PATH" environment variable instead of being hard coded
  • The existence of the "su" executable doesn't necessarily mean the device has been rooted
  • The "which" executable may or may not be installed, and you should let the system resolve its path if possible
  • Just because the SuperUser app is installed on the device does not mean the device has root access yet

The RootTools library from Stericson seems to be checking for root more legitimately. It also has lots of extra tools and utilities so I highly recommend it. However, there's no explanation of how it specifically checks for root, and it may be a bit heavier than most apps really need.

I've made a couple of utility methods that are loosely based on the RootTools library. If you simply want to check if the "su" executable is on the device you can use the following method:

public static boolean isRootAvailable(){
    for(String pathDir : System.getenv("PATH").split(":")){
        if(new File(pathDir, "su").exists()) {
            return true;
        }
    }
    return false;
}

This method simply loops through the directories listed in the "PATH" environment variable and checks if a "su" file exists in one of them.

In order to truly check for root access the "su" command must actually be run. If an app like SuperUser is installed, then at this point it may ask for root access, or if its already been granted/denied a toast may be shown indicating whether access was granted/denied. A good command to run is "id" so that you can verify that the user id is in fact 0 (root).

Here's a sample method to determine whether root access has been granted:

public static boolean isRootGiven(){
    if (isRootAvailable()) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(new String[]{"su", "-c", "id"});
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String output = in.readLine();
            if (output != null && output.toLowerCase().contains("uid=0"))
                return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (process != null)
                process.destroy();
        }
    }

    return false;
}

It's important to actually test running the "su" command because some emulators have the "su" executable pre-installed, but only allow certain users to access it like the adb shell.

It's also important to check for the existence of the "su" executable before trying to run it, because android has been known to not properly dispose of processes that try to run missing commands. These ghost processes can run up memory consumption over time.

How to run stored procedures in Entity Framework Core?

We should create a property with DbQuery not DbSet in the model for the db context like below...

public class MyContextContext : DbContext
{
    public virtual DbQuery<CheckoutInvoiceModel> CheckoutInvoice { get; set; } 
}

After than a method that can be used to return result

public async Task<IEnumerable<CheckoutInvoiceModel>> GetLabReceiptByReceiptNo(string labReceiptNo)
{
    var listing = new List<CheckoutInvoiceModel>();
    try
    {
        var sqlCommand = $@"[dbo].[Checkout_GetLabReceiptByReceiptNo] {labReceiptNo}";
        
        listing = await db.Set<CheckoutInvoiceModel>().FromSqlRaw(sqlCommand).ToListAsync();                       
                        
    }
    catch (Exception ex)
    {
        return null;
    }
    return listing;
}

From above example, we can use any one option you like.

Hope this helpful for you!

What's the difference between '$(this)' and 'this'?

Yes, you need $(this) for jQuery functions, but when you want to access basic javascript methods of the element that don't use jQuery, you can just use this.

Else clause on Python while statement

The else clause is only executed when the while-condition becomes false.

Here are some examples:

Example 1: Initially the condition is false, so else-clause is executed.

i = 99999999

while i < 5:
    print(i)
    i += 1
else:
    print('this')

OUTPUT:

this

Example 2: The while-condition i < 5 never became false because i == 3 breaks the loop, so else-clause was not executed.

i = 0

while i < 5:
    print(i)
    if i == 3:
        break
    i += 1
else:
    print('this')

OUTPUT:

0
1
2
3

Example 3: The while-condition i < 5 became false when i was 5, so else-clause was executed.

i = 0

while i < 5:
    print(i)
    i += 1
else:
    print('this')

OUTPUT:

0
1
2
3
4
this

How can I delete all of my Git stashes at once?

this command enables you to look all stashed changes.

git stash list

Here is the following command use it to clear all of your stashed Changes

git stash clear

Now if you want to delete one of the stashed changes from stash area

git stash drop stash@{index}   // here index will be shown after getting stash list.

Note : git stash list enables you to get index from stash area of git.

How to Copy Text to Clip Board in Android?

use this method:

 ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
 ClipData clip = ClipData.newPlainText(label, text);
 clipboard.setPrimaryClip(clip);

at the place of setPrimaryClip we can also use the following methods:

void    clearPrimaryClip()

Clears any current primary clip on the clipboard.

ClipData    getPrimaryClip()

Returns the current primary clip on the clipboard.

ClipDescription getPrimaryClipDescription()

Returns a description of the current primary clip on the clipboard but not a copy of its data.

CharSequence    getText()

This method is deprecated. Use getPrimaryClip() instead. This retrieves the primary clip and tries to coerce it to a string.

boolean hasPrimaryClip()

Returns true if there is currently a primary clip on the clipboard.

Negative weights using Dijkstra's Algorithm

Note, that Dijkstra works even for negative weights, if the Graph has no negative cycles, i.e. cycles whose summed up weight is less than zero.

Of course one might ask, why in the example made by templatetypedef Dijkstra fails even though there are no negative cycles, infact not even cycles. That is because he is using another stop criterion, that holds the algorithm as soon as the target node is reached (or all nodes have been settled once, he did not specify that exactly). In a graph without negative weights this works fine.

If one is using the alternative stop criterion, which stops the algorithm when the priority-queue (heap) runs empty (this stop criterion was also used in the question), then dijkstra will find the correct distance even for graphs with negative weights but without negative cycles.

However, in this case, the asymptotic time bound of dijkstra for graphs without negative cycles is lost. This is because a previously settled node can be reinserted into the heap when a better distance is found due to negative weights. This property is called label correcting.

How to reference Microsoft.Office.Interop.Excel dll?

You can also try installing it in Visual Studio via Package Manager.

Run Install-Package Microsoft.Office.Interop.Excel in the Package Console. This will automatically add it as a project reference.

Use is like this:

Using Excel=Microsoft.Office.Interop.Excel;

JavaScript: How to get parent element by selector?

You may use closest() in modern browsers:

var div = document.querySelector('div#myDiv');
div.closest('div[someAtrr]');

Use object detection to supply a polyfill or alternative method for backwards compatability with IE.

What's the difference between abstraction and encapsulation?

I know there are lot's of answers before me with variety of examples.
Well here is my opinion abstraction is getting interested from reality .

In abstraction we hide something to reduce the complexity of it and In encapsulation we hide something to protect the data.

So we define encapsulation as wrapping of data and methods in single entity referred as class.

In java we achieve encapsulation using getters and setters not just by wrapping data and methods in it. we also define a way to access that data. and while accessing data we protect it also.

Techinical e.g would be to define a private data variable call weight.Now we know that weight can't be zero or less than zero in real world scenario.
Imagine if there are no getters and setters someone could have easily set it to a negative value being public member of class.

Now final difference using one real world example,
Consider a circuit board consisting of switches and buttons. We wrap all the wires into a a circuit box, so that we can protect someone by not getting in contact directly(encapsulation).

We don't care how those wires are connected to each other we just want an interface to turn on and off switch. That interface is provided by buttons(abstraction)

Convert string to title case with JavaScript

First, convert your string into array by splitting it by spaces:

var words = str.split(' ');

Then use array.map to create a new array containing the capitalized words.

var capitalized = words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1, word.length);
});

Then join the new array with spaces:

capitalized.join(" ");

_x000D_
_x000D_
function titleCase(str) {
  str = str.toLowerCase(); //ensure the HeLlo will become Hello at the end
  var words = str.split(" ");

  var capitalized = words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1, word.length);
  });
  return capitalized.join(" ");
}

console.log(titleCase("I'm a little tea pot"));
_x000D_
_x000D_
_x000D_

NOTE:

This of course has a drawback. This will only capitalize the first letter of every word. By word, this means that it treats every string separated my spaces as 1 word.

Supposedly you have:

str = "I'm a little/small tea pot";

This will produce

I'm A Little/small Tea Pot

compared to the expected

I'm A Little/Small Tea Pot

In that case, using Regex and .replace will do the trick:

with ES6:

_x000D_
_x000D_
const capitalize = str => str.length
  ? str[0].toUpperCase() +
    str.slice(1).toLowerCase()
  : '';

const escape = str => str.replace(/./g, c => `\\${c}`);
const titleCase = (sentence, seps = ' _-/') => {
  let wordPattern = new RegExp(`[^${escape(seps)}]+`, 'g');
  
  return sentence.replace(wordPattern, capitalize);
};
console.log( titleCase("I'm a little/small tea pot.") );
_x000D_
_x000D_
_x000D_

or without ES6:

_x000D_
_x000D_
function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.substring(1, str.length).toLowerCase();
}

function titleCase(str) {
  return str.replace(/[^\ \/\-\_]+/g, capitalize);
}

console.log(titleCase("I'm a little/small tea pot."));
_x000D_
_x000D_
_x000D_

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

What do numbers using 0x notation mean?

Literals that start with 0x are hexadecimal integers. (base 16)

The number 0x6400 is 25600.

6 * 16^3 + 4 * 16^2 = 25600

For an example including letters (also used in hexadecimal notation where A = 10, B = 11 ... F = 15)

The number 0x6BF0 is 27632.

6 * 16^3 + 11 * 16^2 + 15 * 16^1 = 27632
24576    + 2816      + 240       = 27632

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

index.html should be inside templates, as I know. So, your second attempt looks correct.

But, as the error message says, index.html looks like having some errors. E.g. the in the third line, the meta tag should be actually head tag, I think.

jQuery - Follow the cursor with a DIV

This works for me. Has a nice delayed action going on.

var $mouseX = 0, $mouseY = 0;
var $xp = 0, $yp =0;

$(document).mousemove(function(e){
    $mouseX = e.pageX;
    $mouseY = e.pageY;    
});

var $loop = setInterval(function(){
// change 12 to alter damping higher is slower
$xp += (($mouseX - $xp)/12);
$yp += (($mouseY - $yp)/12);
$("#moving_div").css({left:$xp +'px', top:$yp +'px'});  
}, 30);

Nice and simples

Remove everything after a certain character

Worked for me:

      var first = regexLabelOut.replace(/,.*/g, "");

How to run specific test cases in GoogleTest

Finally I got some answer, ::test::GTEST_FLAG(list_tests) = true; //From your program, not w.r.t console.

If you would like to use --gtest_filter =*; /* =*, =xyz*... etc*/ // You need to use them in Console.

So, my requirement is to use them from the program not from the console.

Updated:-

Finally I got the answer for updating the same in from the program.

 ::testing::GTEST_FLAG(filter) = "*Counter*:*IsPrime*:*ListenersTest.DoesNotLeak*";//":-:*Counter*";
      InitGoogleTest(&argc, argv);
RUN_ALL_TEST();

So, Thanks for all the answers.

You people are great.

Force "git push" to overwrite remote files

git push -f is a bit destructive because it resets any remote changes that had been made by anyone else on the team. A safer option is {git push --force-with-lease}.

What {--force-with-lease} does is refuse to update a branch unless it is the state that we expect; i.e. nobody has updated the branch upstream. In practice this works by checking that the upstream ref is what we expect, because refs are hashes, and implicitly encode the chain of parents into their value. You can tell {--force-with-lease} exactly what to check for, but by default will check the current remote ref. What this means in practice is that when Alice updates her branch and pushes it up to the remote repository, the ref pointing head of the branch will be updated. Now, unless Bob does a pull from the remote, his local reference to the remote will be out of date. When he goes to push using {--force-with-lease}, git will check the local ref against the new remote and refuse to force the push. {--force-with-lease} effectively only allows you to force-push if no-one else has pushed changes up to the remote in the interim. It's {--force} with the seatbelt on.

How to get the current date and time

Just construct a new Date object without any arguments; this will assign the current date and time to the new object.

import java.util.Date;

Date d = new Date();

In the words of the Javadocs for the zero-argument constructor:

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

Make sure you're using java.util.Date and not java.sql.Date -- the latter doesn't have a zero-arg constructor, and has somewhat different semantics that are the topic of an entirely different conversation. :)

SQL: Alias Column Name for Use in CASE Statement

I think that MySql and MsSql won't allow this because they will try to find all columns in the CASE clause as columns of the tables in the WHERE clause.

I don't know what DBMS you are talking about, but I guess you could do something like this in any DBMS:

SELECT *, CASE WHEN a = 'test' THEN 'yes' END as value FROM (
   SELECT col1 as a FROM table
) q

How to normalize an array in NumPy to a unit vector?

You can specify ord to get the L1 norm. To avoid zero division I use eps, but that's maybe not great.

def normalize(v):
    norm=np.linalg.norm(v, ord=1)
    if norm==0:
        norm=np.finfo(v.dtype).eps
    return v/norm

How to run jenkins as a different user

you can integrate to LDAP or AD as well. It works well.

How to download file from database/folder using php

You can use html5 tag to download the image directly

<?php
$file = "Bang.png"; //Let say If I put the file name Bang.png
echo "<a href='download.php?nama=".$file."' download>donload</a> ";
?>

For more information, check this link http://www.w3schools.com/tags/att_a_download.asp

Syntax for a for loop in ruby

I keep hitting this as a top link for google "ruby for loop", so I wanted to add a solution for loops where the step wasn't simply '1'. For these cases, you can use the 'step' method that exists on Numerics and Date objects. I think this is a close approximation for a 'for' loop.

start = Date.new(2013,06,30)
stop = Date.new(2011,06,30)
# step back in time over two years, one week at a time
start.step(stop, -7).each do |d| 
    puts d
end

Initialize Array of Objects using NSArray

NSMutableArray *persons = [NSMutableArray array];
for (int i = 0; i < myPersonsCount; i++) {
   [persons addObject:[[Person alloc] init]];
}
NSArray *arrayOfPersons = [NSArray arrayWithArray:persons]; // if you want immutable array

also you can reach this without using NSMutableArray:

NSArray *persons = [NSArray array];
for (int i = 0; i < myPersonsCount; i++) {
   persons = [persons arrayByAddingObject:[[Person alloc] init]];
}

One more thing - it's valid for ARC enabled environment, if you going to use it without ARC don't forget to add autoreleased objects into array!

[persons addObject:[[[Person alloc] init] autorelease];

Using success/error/finally/catch with Promises in AngularJS

What type of granularity are you looking for? You can typically get by with:

$http.get(url).then(
  //success function
  function(results) {
    //do something w/results.data
  },
  //error function
  function(err) {
    //handle error
  }
);

I've found that "finally" and "catch" are better off when chaining multiple promises.

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

There are two problems with your attempt.

First, you've used n+1 instead of i+1, so you're going to return something like [5, 5, 5, 5] instead of [1, 2, 3, 4].

Second, you can't for-loop over a number like n, you need to loop over some kind of sequence, like range(n).

So:

def naturalNumbers(n):
    return [i+1 for i in range(n)]

But if you already have the range function, you don't need this at all; you can just return range(1, n+1), as arshaji showed.

So, how would you build this yourself? You don't have a sequence to loop over, so instead of for, you have to build it yourself with while:

def naturalNumbers(n):
    results = []
    i = 1
    while i <= n:
        results.append(i)
        i += 1
    return results

Of course in real-life code, you should always use for with a range, instead of doing things manually. In fact, even for this exercise, it might be better to write your own range function first, just to use it for naturalNumbers. (It's already pretty close.)


There is one more option, if you want to get clever.

If you have a list, you can slice it. For example, the first 5 elements of my_list are my_list[:5]. So, if you had an infinitely-long list starting with 1, that would be easy. Unfortunately, you can't have an infinitely-long list… but you can have an iterator that simulates one very easily, either by using count or by writing your own 2-liner equivalent. And, while you can't slice an iterator, you can do the equivalent with islice. So:

from itertools import count, islice
def naturalNumbers(n):
    return list(islice(count(1), n))

What is the equivalent of the C++ Pair<L,R> in Java?

Spring data has a Pair and can be used like below,

Pair<S, T> pair = Pair.of(S type data, T type data)

.htaccess mod_rewrite - how to exclude directory from rewrite rule

add a condition to check for the admin directory, something like:

RewriteCond %{REQUEST_URI} !^/?(admin|user)/
RewriteRule ^([^/] )/([^/] )\.html$ index.php?lang=$1&mod=$2 [L]

RewriteCond %{REQUEST_URI} !^/?(admin|user)/
RewriteRule ^([^/] )/$ index.php?lang=$1&mod=home [L]

JavaScript Loading Screen while page loads

If in your site you have ajax calls loading some data, and this is the reason the page is loading slow, the best solution I found is with

$(document).ajaxStop(function(){
    alert("All AJAX requests completed");
});

https://jsfiddle.net/44t5a8zm/ - here you can add some ajax calls and test it.

Android activity life cycle - what are all these methods for?

I like this question and the answers to it, but so far there isn't coverage of less frequently used callbacks like onPostCreate() or onPostResume(). Steve Pomeroy has attempted a diagram including these and how they relate to Android's Fragment life cycle, at https://github.com/xxv/android-lifecycle. I revised Steve's large diagram to include only the Activity portion and formatted it for letter size one-page printout. I've posted it as a text PDF at https://github.com/code-read/android-lifecycle/blob/master/AndroidActivityLifecycle1.pdf and below is its image:

Android Activity Lifecycle

How do I install ASP.NET MVC 5 in Visual Studio 2012?

Microsoft has provided for you on their MSDN blogs: MVC 5 for VS2012. From that blog:

We have released ASP.NET and Web Tools 2013.1 for Visual Studio 2012. This release brings a ton of great improvements, and include some fantastic enhancements to ASP.NET MVC 5, Web API 2, Scaffolding and Entity Framework to users of Visual Studio 2012 and Visual Studio 2012 Express for Web.

You can download and start using these features now.

The download link is to a Web Platform Installer that will allow you to start a new MVC5 project from VS2012.

Extract the last substring from a cell

Simpler would be: =TRIM(RIGHT(SUBSTITUTE(TRIM(A2)," ",REPT(" ",99)),99))

You can use A2 in place of TRIM(A2) if you are sure that your data doesn't contain any unwanted spaces.

Based on concept explained by Rick Rothstein: http://www.excelfox.com/forum/showthread.php/333-Get-Field-from-Delimited-Text-String

Sorry for being necroposter!

How do I get a file's directory using the File object?

I found this more useful for getting the absolute file location.

File file = new File("\\TestHello\\test.txt");
System.out.println(file.getAbsoluteFile());

Overriding css style?

You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important.

#zoomTarget .slikezamenjanje img {
    max-height: auto;
    padding-right: 0px;
}

Hatting

I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.

For example, all CSS height and width attributes default to auto.

Change Select List Option background colour on hover in html

No, it's not possible.

It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".

Getting the index of the returned max or min item using max()/min() on a list

Use a numpy array and the argmax() function

 a=np.array([1,2,3])
 b=np.argmax(a)
 print(b) #2

Drop all data in a pandas dataframe

If your goal is to drop the dataframe, then you need to pass all columns. For me: the best way is to pass a list comprehension to the columns kwarg. This will then work regardless of the different columns in a df.

import pandas as pd

web_stats = {'Day': [1, 2, 3, 4, 2, 6],
             'Visitors': [43, 43, 34, 23, 43, 23],
             'Bounce_Rate': [3, 2, 4, 3, 5, 5]}
df = pd.DataFrame(web_stats)

df.drop(columns=[i for i in check_df.columns])

Align an element to bottom with flexbox

You can use display: flex to position an element to the bottom, but I do not think you want to use flex in this case, as it will affect all of your elements.

To position an element to the bottom using flex try this:

.container {
  display: flex;
}

.button {
  align-self: flex-end;
}

Your best bet is to set position: absolute to the button and set it to bottom: 0, or you can place the button outside the container and use negative transform: translateY(-100%) to bring it in the container like this:

.content {
    height: 400px;
    background: #000;
    color: #fff;
}
.button {
    transform: translateY(-100%);
    display: inline-block;
}

Check this JSFiddle

How to write a link like <a href="#id"> which link to the same page in PHP?

Edit:

Are you trying to do sth like this? See: http://twitter.github.com/bootstrap/javascript.html#tabs


See the working example: http://jsfiddle.net/U6aKT/

<a href="#id">go to id</a>
<div style="margin-top:2000px;"></div>
<a id="id">id</a>

How do I execute a file in Cygwin?

just type ./a in the shell

How to match "any character" in regular expression?

The most common way I have seen to encode this is with a character class whose members form a partition of the set of all possible characters.

Usually people write that as [\s\S] (whitespace or non-whitespace), though [\w\W], [\d\D], etc. would all work.

How to determine the current shell I'm working on

ps -p $$

should work anywhere that the solutions involving ps -ef and grep do (on any Unix variant which supports POSIX options for ps) and will not suffer from the false positives introduced by grepping for a sequence of digits which may appear elsewhere.

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

Are you running this on the Cassini (vs dev server) or on IIS with a cert installed? I have had issues in the past trying to hook up secure endpoints on the dev web server.

Here is the binding configuration that has worked for me in the past. Instead of basicHttpBinding, it uses wsHttpBinding. I don't know if that is a problem for you.

<!-- Binding settings for HTTPS endpoint -->
<binding name="WsSecured">
    <security mode="Transport">
        <transport clientCredentialType="None" />
        <message clientCredentialType="None"
            negotiateServiceCredential="false"
            establishSecurityContext="false" />
    </security>
</binding>

and the endpoint

<endpoint address="..." binding="wsHttpBinding"
    bindingConfiguration="WsSecured" contract="IYourContract" />

Also, make sure you change the client configuration to enable Transport security.

jquery, find next element by class

Given a first selector: SelectorA, you can find the next match of SelectorB as below:

Example with mouseover to change border-with:

$("SelectorA").on("mouseover", function() {
    var i = $(this).find("SelectorB")[0];
    $(i).css({"border" : "1px"});
    });
}

General use example to change border-with:

var i = $("SelectorA").find("SelectorB")[0];
$(i).css({"border" : "1px"});

Cannot install packages inside docker Ubuntu image

Make sure you don't have any syntax errors in your Dockerfile as this can cause this error as well. A correct example is:

RUN apt-get update \
    && apt-get -y install curl \
    another-package

It was a combination of fixing a syntax error and adding apt-get update that solved the problem for me.

Change span text?

document.getElementById("serverTime").innerHTML = ...;

How do I parse JSON into an int?

I use a combination of json.get() and instanceof to read in values that might be either integers or integer strings.

These three test cases illustrate:

int val;
Object obj;
JSONObject json = new JSONObject();
json.put("number", 1);
json.put("string", "10");
json.put("other", "tree");

obj = json.get("number");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);

obj = json.get("string");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);

try {
    obj = json.get("other");
    val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
} catch (Exception e) {
    // throws exception
}

Checking something isEmpty in Javascript?

const isEmpty = val => val == null || !(Object.keys(val) || val).length;

Rails :include vs. :joins

'joins' just used to join tables and when you called associations on joins then it will again fire query (it mean many query will fire)

lets suppose you have tow model, User and Organisation
User has_many organisations
suppose you have 10 organisation for a user 
@records= User.joins(:organisations).where("organisations.user_id = 1")
QUERY will be 
 select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1

it will return all records of organisation related to user
and @records.map{|u|u.organisation.name}
it run QUERY like 
select * from organisations where organisations.id = x then time(hwo many organisation you have)

total number of SQL is 11 in this case

But with 'includes' will eager load the included associations and add them in memory(load all associations on first load) and not fire query again

when you get records with includes like @records= User.includes(:organisations).where("organisations.user_id = 1") then query will be

select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1
and 


 select * from organisations where organisations.id IN(IDS of organisation(1, to 10)) if 10 organisation
and when you run this 

@records.map{|u|u.organisation.name} no query will fire

C# LINQ find duplicates in List

there is an answer but i did not understand why is not working;

var anyDuplicate = enumerable.GroupBy(x => x.Key).Any(g => g.Count() > 1);

my solution is like that in this situation;

var duplicates = model.list
                    .GroupBy(s => s.SAME_ID)
                    .Where(g => g.Count() > 1).Count() > 0;
if(duplicates) {
    doSomething();
}

IN Clause with NULL or IS NULL

SELECT *
FROM tbl_name
WHERE coalesce(id_field,'unik_null_value') 
IN ('value1', 'value2', 'value3', 'unik_null_value')

So that you eliminate the null from the check. Given a null value in id_field, the coalesce function would instead of null return 'unik_null_value', and by adding 'unik_null_value to the IN-list, the query would return posts where id_field is value1-3 or null.

Is there a method to generate a UUID with go language

For Windows, I did recently this:

// +build windows

package main

import (
    "syscall"
    "unsafe"
)

var (
    modrpcrt4 = syscall.NewLazyDLL("rpcrt4.dll")
    procUuidCreate = modrpcrt4.NewProc("UuidCreate")
)

const (
    RPC_S_OK = 0
)

func NewUuid() ([]byte, error) {
    var uuid [16]byte
    rc, _, e := syscall.Syscall(procUuidCreate.Addr(), 1,
             uintptr(unsafe.Pointer(&uuid[0])), 0, 0)
    if int(rc) != RPC_S_OK {
        if e != 0 {
            return nil, error(e)
        } else {
            return nil, syscall.EINVAL
        }
    }
    return uuid[:], nil
}

How to test REST API using Chrome's extension "Advanced Rest Client"

in the header section you have to write

Authorization: Basic aG9sY67890vbGNpbQ==

where string after basic is the 64bit encoding value of your username:password. php example of getting the header values is: echo "Authorization: Basic " . base64_encode("myUser:myPassword");

n.b: I assumed your authentication method as basic. which can be different as well.

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

plt.axis('off')
plt.savefig(file_path, bbox_inches="tight", pad_inches = 0)

plt.savefig has those options in itself, just need to set axes off before

Command line input in Python

Start your script with the following line. The script will first run and then you will get the python command prompt. At this point all variables and functions will be available for interactive use and invocations.

#!/usr/bin/env python -i

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Firstly, you need to be aware that UTC isn't a format, it's a time zone, effectively. So "converting from ISO8601 to UTC" doesn't really make sense as a concept.

However, here's a sample program using Joda Time which parses the text into a DateTime and then formats it. I've guessed at a format you may want to use - you haven't really provided enough information about what you're trying to do to say more than that. You may also want to consider time zones... do you want to display the local time at the specified instant? If so, you'll need to work out the user's time zone and convert appropriately.

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        String text = "2011-03-10T11:54:30.207Z";
        DateTimeFormatter parser = ISODateTimeFormat.dateTime();
        DateTime dt = parser.parseDateTime(text);

        DateTimeFormatter formatter = DateTimeFormat.mediumDateTime();
        System.out.println(formatter.print(dt));
    }
}

What good are SQL Server schemas?

In SQL Server 2000, objects created were linked to that particular user, like if a user, say Sam creates an object, say, Employees, that table would appear like: Sam.Employees. What about if Sam is leaving the compnay or moves to so other business area. As soon you delete the user Sam, what would happen to Sam.Employees table? Probably, you would have to change the ownership first from Sam.Employees to dbo.Employess. Schema provides a solution to overcome this problem. Sam can create all his object within a schemam such as Emp_Schema. Now, if he creates an object Employees within Emp_Schema then the object would be referred to as Emp_Schema.Employees. Even if the user account Sam needs to be deleted, the schema would not be affected.

Plot different DataFrames in the same figure

Although Chang's answer explains how to plot multiple times on the same figure, in this case you might be better off in this case using a groupby and unstacking:

(Assuming you have this in dataframe, with datetime index already)

In [1]: df
Out[1]:
            value  
datetime                         
2010-01-01      1  
2010-02-01      1  
2009-01-01      1  

# create additional month and year columns for convenience
df['Month'] = map(lambda x: x.month, df.index)
df['Year'] = map(lambda x: x.year, df.index)    

In [5]: df.groupby(['Month','Year']).mean().unstack()
Out[5]:
       value      
Year    2009  2010
Month             
1          1     1
2        NaN     1

Now it's easy to plot (each year as a separate line):

df.groupby(['Month','Year']).mean().unstack().plot()

How to respond to clicks on a checkbox in an AngularJS directive?

This is the way I've been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that's the way I've been playing with it).

The markup

<table class="table">
  <thead>
    <tr>
      <th>
        <input type="checkbox" 
          ng-click="selectAll($event)"
          ng-checked="isSelectedAll()">
      </th>
      <th>Title</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
      <td>
        <input type="checkbox" name="selected"
          ng-checked="isSelected(e.id)"
          ng-click="updateSelection($event, e.id)">
      </td>
      <td>{{e.title}}</td>
    </tr>
  </tbody>
</table>

And in the controller

var updateSelected = function(action, id) {
  if (action === 'add' && $scope.selected.indexOf(id) === -1) {
    $scope.selected.push(id);
  }
  if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
    $scope.selected.splice($scope.selected.indexOf(id), 1);
  }
};

$scope.updateSelection = function($event, id) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  updateSelected(action, id);
};

$scope.selectAll = function($event) {
  var checkbox = $event.target;
  var action = (checkbox.checked ? 'add' : 'remove');
  for ( var i = 0; i < $scope.entities.length; i++) {
    var entity = $scope.entities[i];
    updateSelected(action, entity.id);
  }
};

$scope.getSelectedClass = function(entity) {
  return $scope.isSelected(entity.id) ? 'selected' : '';
};

$scope.isSelected = function(id) {
  return $scope.selected.indexOf(id) >= 0;
};

//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
  return $scope.selected.length === $scope.entities.length;
};

EDIT: getSelectedClass() expects the entire entity but it was being called with the id of the entity only, which is now corrected