Programs & Examples On #Reshape

In R, Matlab and Numpy, reshape functions allow data to be transformed into more convenient forms.

Compute mean and standard deviation by group for multiple variables in a data.frame

I add the dplyr solution.

set.seed(1)
df <- data.frame(ID=rep(1:3, 3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))

library(dplyr)
df %>% group_by(ID) %>% summarise_each(funs(mean, sd))

#      ID Obs_1_mean Obs_2_mean Obs_3_mean  Obs_1_sd  Obs_2_sd  Obs_3_sd
#   (int)      (dbl)      (dbl)      (dbl)     (dbl)     (dbl)     (dbl)
# 1     1  0.4854187 -0.3238542  0.7410611 1.1108687 0.2885969 0.1067961
# 2     2  0.4171586 -0.2397030  0.2041125 0.2875411 1.8732682 0.3438338
# 3     3 -0.3601052  0.8195368 -0.4087233 0.8105370 0.3829833 1.4705692

What does -1 mean in numpy reshape?

According to the documentation:

newshape : int or tuple of ints

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

load csv into 2D matrix with numpy for plotting

I think using dtype where there is a name row is confusing the routine. Try

>>> r = np.genfromtxt(fname, delimiter=',', names=True)
>>> r
array([[  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29111196e+12],
       [  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29111311e+12],
       [  6.11882430e+02,   9.08956010e+03,   5.13300000e+03,
          8.64075140e+02,   1.71537476e+03,   7.65227770e+02,
          1.29112065e+12]])
>>> r[:,0]    # Slice 0'th column
array([ 611.88243,  611.88243,  611.88243])

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

Reshaping data.frame from wide to long format

With tidyr_1.0.0, another option is pivot_longer

library(tidyr)
pivot_longer(df1, -c(Code, Country), values_to = "Value", names_to = "Year")
# A tibble: 10 x 4
#   Code  Country     Year  Value 
#   <fct> <fct>       <chr> <fct> 
# 1 AFG   Afghanistan 1950  20,249
# 2 AFG   Afghanistan 1951  21,352
# 3 AFG   Afghanistan 1952  22,532
# 4 AFG   Afghanistan 1953  23,557
# 5 AFG   Afghanistan 1954  24,555
# 6 ALB   Albania     1950  8,097 
# 7 ALB   Albania     1951  8,986 
# 8 ALB   Albania     1952  10,058
# 9 ALB   Albania     1953  11,123
#10 ALB   Albania     1954  12,246

data

df1 <- structure(list(Code = structure(1:2, .Label = c("AFG", "ALB"), class = "factor"), 
    Country = structure(1:2, .Label = c("Afghanistan", "Albania"
    ), class = "factor"), `1950` = structure(1:2, .Label = c("20,249", 
    "8,097"), class = "factor"), `1951` = structure(1:2, .Label = c("21,352", 
    "8,986"), class = "factor"), `1952` = structure(2:1, .Label = c("10,058", 
    "22,532"), class = "factor"), `1953` = structure(2:1, .Label = c("11,123", 
    "23,557"), class = "factor"), `1954` = structure(2:1, .Label = c("12,246", 
    "24,555"), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))

Gather multiple sets of columns

In case you are like me, and cannot work out how to use "regular expression with capturing groups" for extract, the following code replicates the extract(...) line in Hadleys' answer:

df %>% 
    gather(question_number, value, starts_with("Q3.")) %>%
    mutate(loop_number = str_sub(question_number,-2,-2), question_number = str_sub(question_number,1,4)) %>%
    select(id, time, loop_number, question_number, value) %>% 
    spread(key = question_number, value = value)

The problem here is that the initial gather forms a key column that is actually a combination of two keys. I chose to use mutate in my original solution in the comments to split this column into two columns with equivalent info, a loop_number column and a question_number column. spread can then be used to transform the long form data, which are key value pairs (question_number, value) to wide form data.

Reshape an array in NumPy

a = np.arange(18).reshape(9,2)
b = a.reshape(3,3,2).swapaxes(0,2)

# a: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15],
       [16, 17]])


# b:
array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

How to reshape data from long to wide format

The new (in 2014) tidyr package also does this simply, with gather()/spread() being the terms for melt/cast.

Edit: Now, in 2019, tidyr v 1.0 has launched and set spread and gather on a deprecation path, preferring instead pivot_wider and pivot_longer, which you can find described in this answer. Read on if you want a brief glimpse into the brief life of spread/gather.

library(tidyr)
spread(dat1, key = numbers, value = value)

From github,

tidyr is a reframing of reshape2 designed to accompany the tidy data framework, and to work hand-in-hand with magrittr and dplyr to build a solid pipeline for data analysis.

Just as reshape2 did less than reshape, tidyr does less than reshape2. It's designed specifically for tidying data, not the general reshaping that reshape2 does, or the general aggregation that reshape did. In particular, built-in methods only work for data frames, and tidyr provides no margins or aggregation.

Python reshape list to ndim array

You can think of reshaping that the new shape is filled row by row (last dimension varies fastest) from the flattened original list/array.

An easy solution is to shape the list into a (100, 28) array and then transpose it:

x = np.reshape(list_data, (100, 28)).T

Update regarding the updated example:

np.reshape([0, 0, 1, 1, 2, 2, 3, 3], (4, 2)).T
# array([[0, 1, 2, 3],
#        [0, 1, 2, 3]])

np.reshape([0, 0, 1, 1, 2, 2, 3, 3], (2, 4))
# array([[0, 0, 1, 1],
#        [2, 2, 3, 3]])

How to use linux command line ftp with a @ sign in my username?

I've never seen the -u parameter. But if you want to use an "@", how about stating it as "\@"?

That way it should be interpreted as you intend. You know something like

ftp -u user\@[email protected]

Merging 2 branches together in GIT

Case: If you need to ignore the merge commit created by default, follow these steps.

Say, a new feature branch is checked out from master having 2 commits already,

  • "Added A" , "Added B"

Checkout a new feature_branch

  • "Added C" , "Added D"

Feature branch then adds two commits-->

  • "Added E", "Added F"

enter image description here

Now if you want to merge feature_branch changes to master, Do git merge feature_branch sitting on the master.

This will add all commits into master branch (4 in master + 2 in feature_branch = total 6) + an extra merge commit something like 'Merge branch 'feature_branch'' as the master is diverged.

If you really need to ignore these commits (those made in FB) and add the whole changes made in feature_branch as a single commit like 'Integrated feature branch changes into master', Run git merge feature_merge --no-commit.

With --no-commit, it perform the merge and stop just before creating a merge commit, We will have all the added changes in feature branch now in master and get a chance to create a new commit as our own.

Read here for more : https://git-scm.com/docs/git-merge

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

If you are having this problem and are using Qt - you need to link qtmain.lib or qtmaind.lib

Cast object to T

try

if (readData is T)
    return (T)(object)readData;

Convert integer to hex and hex to integer

Convert INT to hex:

SELECT CONVERT(VARBINARY(8), 16777215)

Convert hex to INT:

SELECT CONVERT(INT, 0xFFFFFF)

Update 2015-03-16

The above example has the limitation that it only works when the HEX value is given as an integer literal. For completeness, if the value to convert is a hexadecimal string (such as found in a varchar column) use:

-- If the '0x' marker is present:
SELECT CONVERT(INT, CONVERT(VARBINARY, '0x1FFFFF', 1))

-- If the '0x' marker is NOT present:
SELECT CONVERT(INT, CONVERT(VARBINARY, '1FFFFF', 2))

Note: The string must contain an even number of hex digits. An odd number of digits will yield an error.

More details can be found in the "Binary Styles" section of CAST and CONVERT (Transact-SQL). I believe SQL Server 2008 or later is required.

Hide axis and gridlines Highcharts

This has always worked well for me:

yAxes: [{
         ticks: {
                 display: false;
                },

How to convert int to Integer

int iInt = 10;
Integer iInteger = new Integer(iInt);

Disable button in jQuery

Try this

function disable(i){
    $("#rbutton_"+i).attr("disabled",true);
}

docker command not found even though installed with apt-get

sudo apt-get install docker # DO NOT do this

is a different library on ubuntu.

Use sudo apt-get install docker-ce to install the correct docker.

Ruby capitalize every word first letter

In Rails:

"kirk douglas".titleize => "Kirk Douglas"
#this also works for 'kirk_douglas'

w/o Rails:

"kirk douglas".split(/ |\_/).map(&:capitalize).join(" ")

#OBJECT IT OUT
def titleize(str)
  str.split(/ |\_/).map(&:capitalize).join(" ")
end

#OR MONKEY PATCH IT
class String  
  def titleize
    self.split(/ |\_/).map(&:capitalize).join(" ")
  end
end

w/o Rails (load rails's ActiveSupport to patch #titleize method to String)

require 'active_support/core_ext'
"kirk douglas".titleize #=> "Kirk Douglas"

(some) string use cases handled by #titleize

  • "kirk douglas"
  • "kirk_douglas"
  • "kirk-douglas"
  • "kirkDouglas"
  • "KirkDouglas"

#titleize gotchas

Rails's titleize will convert things like dashes and underscores into spaces and can produce other unexpected results, especially with case-sensitive situations as pointed out by @JamesMcMahon:

"hEy lOok".titleize #=> "H Ey Lo Ok"

because it is meant to handle camel-cased code like:

"kirkDouglas".titleize #=> "Kirk Douglas"

To deal with this edge case you could clean your string with #downcase first before running #titleize. Of course if you do that you will wipe out any camelCased word separations:

"kirkDouglas".downcase.titleize #=> "Kirkdouglas"

How does the stack work in assembly language?

You confuse an abstract stack and the hardware implemented stack. The latter is already implemented.

Is it worth using Python's re.compile?

I agree with Honest Abe that the match(...) in the given examples are different. They are not a one-to-one comparisons and thus, outcomes are vary. To simplify my reply, I use A, B, C, D for those functions in question. Oh yes, we are dealing with 4 functions in re.py instead of 3.

Running this piece of code:

h = re.compile('hello')                   # (A)
h.match('hello world')                    # (B)

is same as running this code:

re.match('hello', 'hello world')          # (C)

Because, when looked into the source re.py, (A + B) means:

h = re._compile('hello')                  # (D)
h.match('hello world')

and (C) is actually:

re._compile('hello').match('hello world')

So, (C) is not the same as (B). In fact, (C) calls (B) after calling (D) which is also called by (A). In other words, (C) = (A) + (B). Therefore, comparing (A + B) inside a loop has same result as (C) inside a loop.

George's regexTest.py proved this for us.

noncompiled took 4.555 seconds.           # (C) in a loop
compiledInLoop took 4.620 seconds.        # (A + B) in a loop
compiled took 2.323 seconds.              # (A) once + (B) in a loop

Everyone's interest is, how to get the result of 2.323 seconds. In order to make sure compile(...) only get called once, we need to store the compiled regex object in memory. If we are using a class, we could store the object and reuse when every time our function get called.

class Foo:
    regex = re.compile('hello')
    def my_function(text)
        return regex.match(text)

If we are not using class (which is my request today), then I have no comment. I'm still learning to use global variable in Python, and I know global variable is a bad thing.

One more point, I believe that using (A) + (B) approach has an upper hand. Here are some facts as I observed (please correct me if I'm wrong):

  1. Calls A once, it will do one search in the _cache followed by one sre_compile.compile() to create a regex object. Calls A twice, it will do two searches and one compile (because the regex object is cached).

  2. If the _cache get flushed in between, then the regex object is released from memory and Python need to compile again. (someone suggest that Python won't recompile.)

  3. If we keep the regex object by using (A), the regex object will still get into _cache and get flushed somehow. But our code keep a reference on it and the regex object will not be released from memory. Those, Python need not to compile again.

  4. The 2 seconds differences in George's test compiledInLoop vs compiled is mainly the time required to build the key and search the _cache. It doesn't mean the compile time of regex.

  5. George's reallycompile test show what happen if it really re-do the compile every time: it will be 100x slower (he reduced the loop from 1,000,000 to 10,000).

Here are the only cases that (A + B) is better than (C):

  1. If we can cache a reference of the regex object inside a class.
  2. If we need to calls (B) repeatedly (inside a loop or multiple times), we must cache the reference to regex object outside the loop.

Case that (C) is good enough:

  1. We cannot cache a reference.
  2. We only use it once in a while.
  3. In overall, we don't have too many regex (assume the compiled one never get flushed)

Just a recap, here are the A B C:

h = re.compile('hello')                   # (A)
h.match('hello world')                    # (B)
re.match('hello', 'hello world')          # (C)

Thanks for reading.

Angularjs $http post file and form data

You can also upload using HTML5. You can use this AJAX uploader.

The JS code is basically:

  $scope.doPhotoUpload = function () {
    // ..
    var myUploader = new uploader(document.getElementById('file_upload_element_id'), options);
    myUploader.send();
    // ..
  }

Which reads from an HTML input element

<input id="file_upload_element_id" type="file" onchange="angular.element(this).scope().doPhotoUpload()">

Generate HTML table from 2D JavaScript array

One-liner using es6 reduce

function makeTableHTML(ar) {
  return `<table>${ar.reduce((c, o) => c += `<tr>${o.reduce((c, d) => (c += `<td>${d}</td>`), '')}</tr>`, '')}</table>`
}

How can I get dictionary key as variable directly in Python (not by searching from value)?

For python 3 If you want to get only the keys use this. Replace print(key) with print(values) if you want the values.

for key,value in my_dict:
  print(key)

Are there inline functions in java?

No, there is no inline function in java. Yes, you can use a public static method anywhere in the code when placed in a public class. The java compiler may do inline expansion on a static or final method, but that is not guaranteed.

Typically such code optimizations are done by the compiler in combination with the JVM/JIT/HotSpot for code segments used very often. Also other optimization concepts like register declaration of parameters are not known in java.

Optimizations cannot be forced by declaration in java, but done by compiler and JIT. In many other languages these declarations are often only compiler hints (you can declare more register parameters than the processor has, the rest is ignored).

Declaring java methods static, final or private are also hints for the compiler. You should use it, but no garantees. Java performance is dynamic, not static. First call to a system is always slow because of class loading. Next calls are faster, but depending on memory and runtime the most common calls are optimized withinthe running system, so a server may become faster during runtime!

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

Had the same problem i added compile 'com.google.android.gms:play-services-measurement:8.4.0' and deleted apply plugin: 'com.google.gms.google-services' I was using classpath 'com.google.gms:google-services:2.0.0-alpha6' in the build project.

Why is Android Studio reporting "URI is not registered"?

The new build system in Android Studio creates a build folder. The code inspection barfs on this folder as well as the gradle folder. These folders should proably be ignored when running code inspection.

I have raised an issue with the Android Studio team at:

https://code.google.com/p/android/issues/detail?id=56415

Internal and external fragmentation

First of all the term fragmentation cues there's an entity divided into parts — fragments.

  • Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"

  • External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous

Get changes from master into branch in Git

EDIT:

My answer below documents a way to merge master into aq, where if you view the details of the merge it lists the changes made on aq prior to the merge, not the changes made on master. I've realised that that probably isn't what you want, even if you think it is!

Just:

git checkout aq
git merge master

is fine.

Yes, this simple merge will show that the changes from master were made to aq at that point, not the other way round; but that is okay – since that is what did happen! Later on, when you finally merge your branch into master, that is when a merge will finally show all your changes as made to master (which is exactly what you want, and is the commit where people are going to expect to find that info anyway).

I've checked and the approach below also shows exactly the same changes (all the changes made on aq since the original split between aq and master) as the normal approach above, when you finally merge everything back to master. So I think its only real disadvantage (apart from being over-complex and non-standard... :-/ ) is that if you wind back n recent changes with git reset --hard HEAD~<n> and this goes past the merge, then the version below rolls back down the 'wrong' branch, which you have to fix up by hand (e.g. with git reflog & git reset --hard [sha]).


[So, what I previously thought was that:]

There is a problem with:

git checkout aq
git merge master

because the changes shown in the merge commit (e.g. if you look now or later in Github, Bitbucket or your favourite local git history viewer) are the changes made on master, which may well not be what you want.

On the other hand

git checkout master
git merge aq

shows the changes made in aq, which probably is what you want. (Or, at least, it's often what I want!) But the merge showing the right changes is on the wrong branch!

How to cope?!

The full process, ending up with a merge commit showing the changes made on aq (as per the second merge above), but with the merge affecting the aq branch, is:

git checkout master
git merge aq
git checkout aq
git merge master
git checkout master
git reset --hard HEAD~1
git checkout aq

This: merges aq onto master, fast-forwards that same merge onto aq, undoes it on master, and puts you back on aq again!

I feel like I'm missing something - this seems to be something you'd obviously want, and something that's hard to do.

Also, rebase is NOT equivalent. It loses the timestamps and identity of the commits made on aq, which is also not what I want.

MySQL Stored procedure variables from SELECT statements

I am facing a strange behavior.

SELECT INTO and SET Both works for some variables and not for others. Event syntaxes are the same

SET @Invoice_UserId :=  (SELECT UserId FROM invoice WHERE InvoiceId = @Invoice_Id  LIMIT 1); -- Working
                SET @myamount := (SELECT amount FROM invoice WHERE InvoiceId = @Invoice_Id LIMIT 1); - Not working
SELECT  Amount INTO @myamount FROM invoice WHERE InvoiceId = 29  LIMIT 1; - Not working

If I run these queries directly then works, but not working in stored procedure.

Clone private git repo with dockerfile

For bitbucket repository, generate App Password (Bitbucket settings -> Access Management -> App Password, see the image) with read access to the repo and project.

bitbucket user menu

Then the command that you should use is:

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

How to get current available GPUs in tensorflow?

The accepted answer gives you the number of GPUs but it also allocates all the memory on those GPUs. You can avoid this by creating a session with fixed lower memory before calling device_lib.list_local_devices() which may be unwanted for some applications.

I ended up using nvidia-smi to get the number of GPUs without allocating any memory on them.

import subprocess

n = str(subprocess.check_output(["nvidia-smi", "-L"])).count('UUID')

How to solve munmap_chunk(): invalid pointer error in C++

This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

char *words; // setting this to NULL would have prevented the issue

if (condition) {
    words = malloc( 512 );

    /* calling free sometime later works here */

    free(words)
} else {

    /* do not allocate words in this branch */
}

/* free(words);  -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/

There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer


IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

Getting Excel to refresh data on sheet from within VBA

You might also try

Application.CalculateFull

or

Application.CalculateFullRebuild

if you don't mind rebuilding all open workbooks, rather than just the active worksheet. (CalculateFullRebuild rebuilds dependencies as well.)

Left padding a String with Zeros

Based on @Haroldo Macêdo's answer, I created a method in my custom Utils class such as

/**
 * Left padding a string with the given character
 *
 * @param str     The string to be padded
 * @param length  The total fix length of the string
 * @param padChar The pad character
 * @return The padded string
 */
public static String padLeft(String str, int length, String padChar) {
    String pad = "";
    for (int i = 0; i < length; i++) {
        pad += padChar;
    }
    return pad.substring(str.length()) + str;
}

Then call Utils.padLeft(str, 10, "0");

Time in milliseconds in C

A couple of things might affect the results you're seeing:

  1. You're treating clock_t as a floating-point type, I don't think it is.
  2. You might be expecting (1^4) to do something else than compute the bitwise XOR of 1 and 4., i.e. it's 5.
  3. Since the XOR is of constants, it's probably folded by the compiler, meaning it doesn't add a lot of work at runtime.
  4. Since the output is buffered (it's just formatting the string and writing it to memory), it completes very quickly indeed.

You're not specifying how fast your machine is, but it's not unreasonable for this to run very quickly on modern hardware, no.

If you have it, try adding a call to sleep() between the start/stop snapshots. Note that sleep() is POSIX though, not standard C.

How to disable/enable select field using jQuery?

Just simply use:

var update_pizza = function () {
     $("#pizza_kind").prop("disabled", !$('#pizza').prop('checked'));
};

update_pizza();
$("#pizza").change(update_pizza);

DEMO ?

How do I access (read, write) Google Sheets spreadsheets with Python?

Have a look at GitHub - gspread.

I found it to be very easy to use and since you can retrieve a whole column by

first_col = worksheet.col_values(1)

and a whole row by

second_row = worksheet.row_values(2)

you can more or less build some basic select ... where ... = ... easily.

What's the main difference between int.Parse() and Convert.ToInt32

Have a look in reflector:

int.Parse("32"):

public static int Parse(string s)
{
    return System.Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}

which is a call to:

internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
{
    byte* stackBuffer = stackalloc byte[1 * 0x72];
    NumberBuffer number = new NumberBuffer(stackBuffer);
    int num = 0;
    StringToNumber(s, style, ref number, info, false);
    if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
    {
        if (!HexNumberToInt32(ref number, ref num))
        {
            throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
        }
        return num;
    }
    if (!NumberToInt32(ref number, ref num))
    {
        throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
    }
    return num;
}

Convert.ToInt32("32"):

public static int ToInt32(string value)
{
    if (value == null)
    {
        return 0;
    }
    return int.Parse(value, CultureInfo.CurrentCulture);
}

As the first (Dave M's) comment says.

Number of occurrences of a character in a string

You could do this:

int count = test.Split('&').Length - 1;

Or with LINQ:

test.Count(x => x == '&');

CSS @font-face not working in ie

Change as per below

@font-face {
    font-family: "Futura";
    src: url("../fonts/Futura_Medium_BT.eot"); /* IE */
    src: local("Futura"), url( "../fonts/Futura_Medium_BT.ttf" ) format("truetype"); /* non-IE */  
}

body nav {
     font-family: "Futura";
    font-size:1.2em;
    height: 40px;
}

ORA-00932: inconsistent datatypes: expected - got CLOB

I found that selecting a clob column in CTE caused this explosion. ie

with cte as (
    select
        mytable1.myIntCol,
        mytable2.myClobCol
    from mytable1
    join mytable2 on ...
)
select myIntCol, myClobCol
from cte
where ...

presumably because oracle can't handle a clob in a temporary table.

Because my values were longer than 4K, I couldn't use to_char().
My work around was to select it from the final select, ie

with cte as (
    select
        mytable1.myIntCol
    from mytable1
)
select myIntCol, myClobCol
from cte
join mytable2 on ...
where ...

Too bad if this causes a performance problem.

MySQL: Insert datetime into other datetime field

According to MySQL documentation, you should be able to just enclose that datetime string in single quotes, ('YYYY-MM-DD HH:MM:SS') and it should work. Look here: Date and Time Literals

So, in your case, the command should be as follows:

UPDATE products SET former_date='2011-12-18 13:17:17' WHERE id=1

How can I make git accept a self signed certificate?

I use a windows machine and this article helped me. Basically I opened ca-bundle.crt in notepad and added chain certificates in it (all of them). This issue usually happens for company networks where we have middle men sitting between system and git repo. We need to export all of the certs in cert chain except leaf cert in base 64 format and add all of them to ca-bundle.crt and then configure git for this modified crt file.

Best way to determine user's locale within browser

You said your website has Flash, then, as another option, you can get operation system's language with flash.system.Capabilities.language— see How to determine OS language within browser to guess an operation system locale.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

• A Dockerfile should specify at least one CMD or ENTRYPOINT instruction

• Only the last CMD and ENTRYPOINT in a Dockerfile will be used

• ENTRYPOINT should be defined when using the container as an executable

• You should use the CMD instruction as a way of defining default arguments for the command defined as ENTRYPOINT or for executing an ad-hoc command in a container

• CMD will be overridden when running the container with alternative arguments

• ENTRYPOINT sets the concrete default application that is used every time a container is created using the image

• If you couple ENTRYPOINT with CMD, you can remove an executable from CMD and just leave its arguments which will be passed to ENTRYPOINT

• The best use for ENTRYPOINT is to set the image's main command, allowing that image to be run as though it was that command (and then use CMD as the default flags)

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

HQL "is null" And "!= null" on an Oracle column

No. You have to use is null and is not null in HQL.

How to install xgboost in Anaconda Python (Windows platform)?

Open anaconda prompt and run

pip install xgboost

How to monitor the memory usage of Node.js?

node-memwatch : detect and find memory leaks in Node.JS code. Check this tutorial Tracking Down Memory Leaks in Node.js

Execute JavaScript using Selenium WebDriver in C#

How about a slightly simplified version of @Morten Christiansen's nice extension method idea:

public static object Execute(this IWebDriver driver, string script)
{
    return ((IJavaScriptExecutor)driver).ExecuteScript(script);
}

// usage
var title = (string)driver.Execute("return document.title");

or maybe the generic version:

public static T Execute<T>(this IWebDriver driver, string script)
{
    return (T)((IJavaScriptExecutor)driver).ExecuteScript(script);
}

// usage
var title = driver.Execute<string>("return document.title");

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

I found a solution for ajax issue noted by Lion_cl.

global.asax:

protected void Application_Error()
    {           
        if (HttpContext.Current.Request.IsAjaxRequest())
        {
            HttpContext ctx = HttpContext.Current;
            ctx.Response.Clear();
            RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
            rc.RouteData.Values["action"] = "AjaxGlobalError";

            // TODO: distinguish between 404 and other errors if needed
            rc.RouteData.Values["newActionName"] = "WrongRequest";

            rc.RouteData.Values["controller"] = "ErrorPages";
            IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
            IController controller = factory.CreateController(rc, "ErrorPages");
            controller.Execute(rc);
            ctx.Server.ClearError();
        }
    }

ErrorPagesController

public ActionResult AjaxGlobalError(string newActionName)
    {
        return new AjaxRedirectResult(Url.Action(newActionName), this.ControllerContext);
    }

AjaxRedirectResult

public class AjaxRedirectResult : RedirectResult
{
    public AjaxRedirectResult(string url, ControllerContext controllerContext)
        : base(url)
    {
        ExecuteResult(controllerContext);
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
        {
            JavaScriptResult result = new JavaScriptResult()
            {
                Script = "try{history.pushState(null,null,window.location.href);}catch(err){}window.location.replace('" + UrlHelper.GenerateContentUrl(this.Url, context.HttpContext) + "');"
            };

            result.ExecuteResult(context);
        }
        else
        {
            base.ExecuteResult(context);
        }
    }
}

AjaxRequestExtension

public static class AjaxRequestExtension
{
    public static bool IsAjaxRequest(this HttpRequest request)
    {
        return (request.Headers["X-Requested-With"] != null && request.Headers["X-Requested-With"] == "XMLHttpRequest");
    }
}

Could not open a connection to your authentication agent

To amplify on n3o's answer for Windows 7...

My problem was indeed that some required environment variables weren't set, and n3o is correct that ssh-agent tells you how to set those environment variables, but doesn't actually set them.

Since Windows doesn't let you do "eval," here's what to do instead:

Redirect the output of ssh-agent to a batch file with

ssh-agent > temp.bat

Now use a text editor such as Notepad to edit temp.bat. For each of the first two lines: - Insert the word "set" and a space at the beginning of the line. - Delete the first semicolon and everything that follows.

Now delete the third line. Your temp.bat should look something like this:

set SSH_AUTH_SOCK=/tmp/ssh-EorQv10636/agent.10636
set SSH_AGENT_PID=8608

Run temp.bat. This will set the environment variables that are needed for ssh-add to work.

how to make a full screen div, and prevent size to be changed by content?

Or even just:

<div id="full-size">
  Your contents go here
</div>
html,body{ margin:0; padding:0; height:100%; width:100%; }
#full-size{
  height:100%;
  width:100%;
  overflow:hidden; /* or overflow:auto; if you want scrollbars */
}

(html, body can be set to like.. 95%-99% or some such to account for slight inconsistencies in margins, etc.)

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

How do I analyze a .hprof file?

Just get the Eclipse Memory Analyzer. There's nothing better out there and it's free.

JHAT is only usable for "toy applications"

Adding an image to a PDF using iTextSharp and scale it properly

I solved it using the following:

foreach (var image in images)
{
    iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);

    if (pic.Height > pic.Width)
    {
        //Maximum height is 800 pixels.
        float percentage = 0.0f;
        percentage = 700 / pic.Height;
        pic.ScalePercent(percentage * 100);
    }
    else
    {
        //Maximum width is 600 pixels.
        float percentage = 0.0f;
        percentage = 540 / pic.Width;
        pic.ScalePercent(percentage * 100);
    }

    pic.Border = iTextSharp.text.Rectangle.BOX;
    pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
    pic.BorderWidth = 3f;
    document.Add(pic);
    document.NewPage();
}

C# difference between == and Equals()

==

The == operator can be used to compare two variables of any kind, and it simply compares the bits.

int a = 3;
byte b = 3;
if (a == b) { // true }

Note : there are more zeroes on the left side of the int but we don't care about that here.

int a (00000011) == byte b (00000011)

Remember == operator cares only about the pattern of the bits in the variable.

Use == If two references (primitives) refers to the same object on the heap.

Rules are same whether the variable is a reference or primitive.

Foo a = new Foo();
Foo b = new Foo();
Foo c = a;

if (a == b) { // false }
if (a == c) { // true }
if (b == c) { // false }

a == c is true a == b is false

the bit pattern are the same for a and c, so they are equal using ==.

Equal():

Use the equals() method to see if two different objects are equal.

Such as two different String objects that both represent the characters in "Jane"

FileSystemWatcher Changed event is raised twice

Here is a new solution you can try. Works well for me. In the event handler for the changed event programmatically remove the handler from the designer output a message if desired then programmatically add the handler back. example:

public void fileSystemWatcher1_Changed( object sender, System.IO.FileSystemEventArgs e )
    {            
        fileSystemWatcher1.Changed -= new System.IO.FileSystemEventHandler( fileSystemWatcher1_Changed );
        MessageBox.Show( "File has been uploaded to destination", "Success!" );
        fileSystemWatcher1.Changed += new System.IO.FileSystemEventHandler( fileSystemWatcher1_Changed );
    }

request exceeds the configured maxQueryStringLength when using [Authorize]

i have this error using datatables.net

i fixed changing the default ajax Get to POST in te properties of the DataTable()

"ajax": {
        "url": "../ControllerName/MethodJson",
        "type": "POST"
    },

Python, Matplotlib, subplot: How to set the axis range?

You have pylab.ylim:

pylab.ylim([0,1000])

Note: The command has to be executed after the plot!

Update 2021
Since the use of pylab is now strongly discouraged by matplotlib, you should instead use pyplot:

from matplotlib import pyplot as plt
plt.ylim(0, 100) 
#corresponding function for the x-axis
plt.xlim(1, 1000)

How to place the ~/.composer/vendor/bin directory in your PATH?

For Linux Mint 18: edit ~/.bashrc and add this line to it at the bottom:

export PATH="$PATH:$HOME/.config/composer/vendor/bin"

then resource .bashrc (type in console):

source ~/.bashrc (or close and reopen the terminal)

test it by typing in the console:

echo $PATH

or type in console:

laravel

How can I convert a string to boolean in JavaScript?

Do:

var isTrueSet = (myValue == 'true');

You could make it stricter by using the identity operator (===), which doesn't make any implicit type conversions when the compared variables have different types, instead of the equality operator (==).

var isTrueSet = (myValue === 'true');

Don't:

You should probably be cautious about using these two methods for your specific needs:

var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true

Any string which isn't the empty string will evaluate to true by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.

Separating class code into a header and cpp file

In general your .h contains the class defition, which is all your data and all your method declarations. Like this in your case:

A2DD.h:

class A2DD
{
  private:
  int gx;
  int gy;

  public:
  A2DD(int x,int y);    
  int getSum();
};

And then your .cpp contains the implementations of the methods like this:

A2DD.cpp:

A2DD::A2DD(int x,int y)
{
  gx = x;
  gy = y;
}

int A2DD::getSum()
{
  return gx + gy;
}

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Possible. You can get commercial sport also.

JavaFXPorts is the name of the open source project maintained by Gluon that develops the code necessary for Java and JavaFX to run well on mobile and embedded hardware. The goal of this project is to contribute as much back to the OpenJFX project wherever possible, and when not possible, to maintain the minimal number of changes necessary to enable the goals of JavaFXPorts. Gluon takes the JavaFXPorts source code and compiles it into binaries ready for deployment onto iOS, Android, and embedded hardware. The JavaFXPorts builds are freely available on this website for all developers.

http://gluonhq.com/labs/javafxports/

"relocation R_X86_64_32S against " linking Error

I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:

/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]

This contrary to the fact that I was already passing -fPIC flags though CFLAGS variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf scripts and need --with-pic switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS. Pass the switch to configure script and the dependencies will be correctly compiled with -fPIC.

What is an 'undeclared identifier' error and how do I fix it?

In C and C++ all names have to be declared before they are used. If you try to use the name of a variable or a function that hasn't been declared you will get an "undeclared identifier" error.

However, functions are a special case in C (and in C only) in that you don't have to declare them first. The C compiler will the assume the function exists with the number and type of arguments as in the call. If the actual function definition does not match that you will get another error. This special case for functions does not exist in C++.

You fix these kind of errors by making sure that functions and variables are declared before they are used. In the case of printf you need to include the header file <stdio.h> (or <cstdio> in C++).

For standard functions, I recommend you check e.g. this reference site, and search for the functions you want to use. The documentation for each function tells you what header file you need.

Fixed footer in Bootstrap

Add z-index:-9999; to this method, or it will cover your top bar if you have 1.

Angular-cli from css to scss

In ng6 you need to use this command, according to a similar post:

ng config schematics.@schematics/angular:component '{ styleext: "scss"}'

(WAMP/XAMP) send Mail using SMTP localhost

You can use this library to send email ,if having issue with local xampp,wamp...

class.phpmailer.php,class.smtp.php Write this code in file where your email function calls

    include('class.phpmailer.php');

    $mail = new PHPMailer();  
    $mail->IsHTML(true);
    $mail->IsSMTP();
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = "ssl";
    $mail->Host = "smtp.gmail.com";
    $mail->Port = 465;
    $mail->Username = "your email ID";
    $mail->Password = "your email password";
    $fromname = "From Name in Email";

$To = trim($email,"\r\n");
      $tContent   = '';

      $tContent .="<table width='550px' colspan='2' cellpadding='4'>
            <tr><td align='center'><img src='imgpath' width='100' height='100'></td></tr>
            <tr><td height='20'>&nbsp;</td></tr>
            <tr>
              <td>
                <table cellspacing='1' cellpadding='1' width='100%' height='100%'>
                <tr><td align='center'><h2>YOUR TEXT<h2></td></tr/>
                <tr><td>&nbsp;</td></tr>
                <tr><td align='center'>Name: ".trim(NAME,"\r\n")."</td></tr>
                <tr><td align='center'>ABCD TEXT: ".$abcd."</td></tr>
                <tr><td>&nbsp;</td></tr>                
                </table>
              </td>
            </tr>
            </table>";
      $mail->From = "From email";
      $mail->FromName = $fromname;        
      $mail->Subject = "Your Details."; 
      $mail->Body = $tContent;
      $mail->AddAddress($To); 
      $mail->set('X-Priority', '1'); //Priority 1 = High, 3 = Normal, 5 = low
      $mail->Send();

Oracle SQL update based on subquery between two tables

There are two ways to do what you are trying

One is a Multi-column Correlated Update

UPDATE PRODUCTION a
SET (name, count) = (
  SELECT name, count
  FROM STAGING b
  WHERE a.ID = b.ID);

DEMO

You can use merge

MERGE INTO PRODUCTION a
USING ( select id, name, count 
          from STAGING ) b
ON ( a.id = b.id )
WHEN MATCHED THEN 
UPDATE SET  a.name = b.name,
            a.count = b.count

DEMO

Change CSS properties on click

Try this:

CSS

.style1{
    background-color:red;
    color:white;
    font-size:44px;
}

HTML

<div id="foo">hello world!</div>
<img src="zoom.png" onclick="myFunction()" />

Javascript

function myFunction()
{
    document.getElementById('foo').setAttribute("class", "style1");
}

How to get a matplotlib Axes instance to plot to?

Use the gca ("get current axes") helper function:

ax = plt.gca()

Example:

import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()

enter image description here

Drop data frame columns by name

There's a function called dropNamed() in Bernd Bischl's BBmisc package that does exactly this.

BBmisc::dropNamed(df, "x")

The advantage is that it avoids repeating the data frame argument and thus is suitable for piping in magrittr (just like the dplyr approaches):

df %>% BBmisc::dropNamed("x")

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

Return sql rows where field contains ONLY non-alphanumeric characters

If you have short strings you should be able to create a few LIKE patterns ('[^a-zA-Z0-9]', '[^a-zA-Z0-9][^a-zA-Z0-9]', ...) to match strings of different length. Otherwise you should use CLR user defined function and a proper regular expression - Regular Expressions Make Pattern Matching And Data Extraction Easier.

How do I find which program is using port 80 in Windows?

Right click on "Command prompt" or "PowerShell", in menu click "Run as Administrator" (on Windows XP you can just run it as usual).

As Rick Vanover mentions in See what process is using a TCP port in Windows Server 2008

The following command will show what network traffic is in use at the port level:

Netstat -a -n -o

or

Netstat -a -n -o >%USERPROFILE%\ports.txt

(to open the port and process list in a text editor, where you can search for information you want)

Then,

with the PIDs listed in the netstat output, you can follow up with the Windows Task Manager (taskmgr.exe) or run a script with a specific PID that is using a port from the previous step. You can then use the "tasklist" command with the specific PID that corresponds to a port in question.

Example:

tasklist /svc /FI "PID eq 1348"

JavaScript/jQuery - "$ is not defined- $function()" error

This may be useful to someone:

If you already got jQuery but still get this error, check you include jQuery before the js that uses it, specially if you use @RenderBody() in ASP.NET C#

You have to include jQuery before the @RenderBody() if you include the js inside the view that @RenderBody() calls.

How to get Android crash logs?

You can try this from the console:

adb logcat --buffer=crash 

More info on this option:

adb logcat --help

...

  -b <buffer>, --buffer=<buffer>         Request alternate ring buffer, 'main',
                  'system', 'radio', 'events', 'crash', 'default' or 'all'.
                  Multiple -b parameters or comma separated list of buffers are
                  allowed. Buffers interleaved. Default -b main,system,crash.

Floating point comparison functions for C#

What about: b - delta < a && a < b + delta

Can I underline text in an Android layout?

If you want to achieve this in XML, declare your string in resource and put that resource value into underline tag (<u></u>) of HTML. in TextView, add

android:text="@string/your_text_reference"

And in string resource value,

<string name="your_text_reference"><u>Underline me</u></string>

If you want to achieve this programmatically, for Kotlin use

textView.paintFlags = textView.paintFlags or Paint.UNDERLINE_TEXT_FLAG

or,

textView.text = Html.fromHtml("<p><u>Underline me</u></p>")

How to create a new text file using Python

    file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
    any_string = "Hello\nWorld"
    file.write(any_string)
    file.close()

Create timestamp variable in bash script

ISO 8601 format (2018-12-23T12:34:56) is more readable than UNIX timestamp. However on some OSs you cannot have : in the filenames. Therefore I recommend using something like this instead:

2018-12-23_12-34-56

You can use the following command to get the timestamp in this format:

TIMESTAMP=`date +%Y-%m-%d_%H-%M-%S`

This is the format I have seen many applications use. Another nice thing about this is that if your file names start with this, you can sort them alphabetically and they would be sorted by date.

How to find a Java Memory Leak

Questioner here, I have got to say getting a tool that does not take 5 minutes to answer any click makes it a lot easier to find potential memory leaks.

Since people are suggesting several tools ( I only tried visual wm since I got that in the JDK and JProbe trial ) I though I should suggest a free / open source tool built on the Eclipse platform, the Memory Analyzer (sometimes referenced as the SAP memory analyzer) available on http://www.eclipse.org/mat/ .

What is really cool about this tool is that it indexed the heap dump when I first opened it which allowed it to show data like retained heap without waiting 5 minutes for each object (pretty much all operations were tons faster than the other tools I tried).

When you open the dump, the first screen shows you a pie chart with the biggest objects (counting retained heap) and one can quickly navigate down to the objects that are to big for comfort. It also has a Find likely leak suspects which I reccon can come in handy, but since the navigation was enough for me I did not really get into it.

How to apply a patch generated with git format-patch?

First you should take a note about difference between git am and git apply

When you are using git am you usually wanna to apply many patches. Thus should use:

git am *.patch

or just:

git am

Git will find patches automatically and apply them in order ;-)

UPD
Here you can find how to generate such patches

Switch focus between editor and integrated terminal in Visual Studio Code

While there are a lot of modal toggles and navigation shortcuts for VS Code, there isn't one specifically for "move from editor to terminal, and back again". However you can compose the two steps by overloading the key and using the when clause.

Open the keybindings.json from the editor: CMD-SHIFT-P -> Preferences: Open Keyboard Shortcuts File and add these entries:

// Toggle between terminal and editor focus
{ "key": "ctrl+`", "command": "workbench.action.terminal.focus"},
{ "key": "ctrl+`", "command": "workbench.action.focusActiveEditorGroup", "when": "terminalFocus"}

With these shortcuts I will focus between the editor and the Integrated Terminal using the same keystroke.

How to convert a list into data table

private DataTable CreateDataTable(IList<T> item)
{
    Type type = typeof(T);
    var properties = type.GetProperties();

    DataTable dataTable = new DataTable();
    foreach (PropertyInfo info in properties)
    {
        dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
    }

    foreach (T entity in item)
    {
        object[] values = new object[properties.Length];
        for (int i = 0; i < properties.Length; i++)
        {
            values[i] = properties[i].GetValue(entity);
        }

        dataTable.Rows.Add(values);
    }
    return dataTable;
}

What's the difference between “mod” and “remainder”?

Modulus, in modular arithmetic as you're referring, is the value left over or remaining value after arithmetic division. This is commonly known as remainder. % is formally the remainder operator in C / C++. Example:

7 % 3 = 1  // dividend % divisor = remainder

What's left for discussion is how to treat negative inputs to this % operation. Modern C and C++ produce a signed remainder value for this operation where the sign of the result always matches the dividend input without regard to the sign of the divisor input.

SHA-256 or MD5 for file integrity

The underlying MD5 algorithm is no longer deemed secure, thus while md5sum is well-suited for identifying known files in situations that are not security related, it should not be relied on if there is a chance that files have been purposefully and maliciously tampered. In the latter case, the use of a newer hashing tool such as sha256sum is highly recommended.

So, if you are simply looking to check for file corruption or file differences, when the source of the file is trusted, MD5 should be sufficient. If you are looking to verify the integrity of a file coming from an untrusted source, or over from a trusted source over an unencrypted connection, MD5 is not sufficient.

Another commenter noted that Ubuntu and others use MD5 checksums. Ubuntu has moved to PGP and SHA256, in addition to MD5, but the documentation of the stronger verification strategies are more difficult to find. See the HowToSHA256SUM page for more details.

HTML Text with tags to formatted text in an Excel cell

To put HTML/Word in an Excel Shape and locate it on an Excel Cell:

  1. Write my HTML to a temp file.
  2. Open temp file via Word Interop.
  3. Copy it from Word to clipboard.
  4. Open Excel via Interop.
  5. Set and Select a cell to a range.
  6. PasteSpecial as a "Microsoft Word Document Object"
  7. Adjust the excel row to the Shape height.

In this way, even HTML with tables and other stuff does not get split over multiple cells.

    private void btnPutHTMLIntoExcelShape_Click(object sender, EventArgs e)
    {
        var fFile = new FileInfo(@"C:\Temp\temp.html");
        StreamWriter SW = fFile.CreateText();
        SW.Write(hecNote.DocumentHtml);
        SW.Close();

        Word.Application wrdApplication;
        Word.Document wrdDocument;
        wrdApplication = new Word.Application();
        wrdApplication.Visible = true;

        wrdDocument = wrdApplication.Documents.Add(@"C:\Temp\temp.html");
        wrdDocument.ActiveWindow.Selection.WholeStory();
        wrdDocument.ActiveWindow.Selection.Copy();

        Excel.Application excApplication;
        Excel.Workbook excWorkbook;
        Excel._Worksheet excWorksheet;
        Excel.Range excRange = null;

        excApplication = new Excel.Application();
        excApplication.Visible = true;
        excWorkbook = excApplication.Workbooks.Add(Type.Missing);
        excWorksheet = (Excel.Worksheet)excWorkbook.Worksheets.get_Item(1);
        excWorksheet.Name = "Work";
        excRange = excWorksheet.get_Range("A1");
        excRange.Select();

        excWorksheet.PasteSpecial("Microsoft Word Document Object");

        Excel.Shape O = excWorksheet.Shapes.Item(1);

        this.Text = $"{O.Height} x {O.Width}";
        ((Excel.Range)excWorksheet.Rows[1, Type.Missing]).RowHeight = O.Height;
    }

Create session factory in Hibernate 4

In earlier versions session factory was created as below:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be like:

Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());

How to remove/ignore :hover css style on touch devices

Try this (i use background and background-color in this example):

var ClickEventType = ((document.ontouchstart !== null) ? 'click' : 'touchstart');

if (ClickEventType == 'touchstart') {
            $('a').each(function() { // save original..
                var back_color = $(this).css('background-color');
                var background = $(this).css('background');
                $(this).attr('data-back_color', back_color);
                $(this).attr('data-background', background);
            });

            $('a').on('touchend', function(e) { // overwrite with original style..
                var background = $(this).attr('data-background');
                var back_color = $(this).attr('data-back_color');
                if (back_color != undefined) {
                    $(this).css({'background-color': back_color});
                }
                if (background != undefined) {
                    $(this).css({'background': background});
                }
            }).on('touchstart', function(e) { // clear added stlye="" elements..
                $(this).css({'background': '', 'background-color': ''});
            });
}

css:

a {
    -webkit-touch-callout: none;
    -webkit-tap-highlight-color: transparent;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

How should I pass an int into stringWithFormat?

Is the snippet you posted just a sample to show what you are trying to do?

The reason I ask is that you've named a method increment, but you seem to be using that to set the value of a text label, rather than incrementing a value.

If you are trying to do something more complicated - such as setting an integer value and having the label display this value, you could consider using bindings. e.g

You declare a property count and your increment action sets this value to whatever, and then in IB, you bind the label's text to the value of count. As long as you follow Key Value Coding (KVC) with count, you don't have to write any code to update the label's display. And from a design perspective you've got looser coupling.

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

Although this an old post, I am sharing another working example.

"COLUMN COUNT AS WELL AS EACH COLUMN DATATYPE MUST MATCH WHEN 'UNION' OR 'UNION ALL' IS USED"

Let us take an example:

1:

In SQL if we write - SELECT 'column1', 'column2' (NOTE: remember to specify names in quotes) In a result set, it will display empty columns with two headers - column1 and column2

2: I share one simple instance I came across.

I had seven columns with few different datatypes in SQL. I.e. uniqueidentifier, datetime, nvarchar

My task was to retrieve comma separated result set with column header. So that when I export the data to CSV I have comma separated rows with first row as header and has respective column names.

SELECT CONVERT(NVARCHAR(36), 'Event ID') + ', ' + 
'Last Name' + ', ' + 
'First Name' + ', ' + 
'Middle Name' + ', ' + 
CONVERT(NVARCHAR(36), 'Document Type') + ', ' + 
'Event Type' + ', ' + 
CONVERT(VARCHAR(23), 'Last Updated', 126)

UNION ALL

SELECT CONVERT(NVARCHAR(36), inspectionid) + ', ' + 
       individuallastname + ', ' + 
       individualfirstname + ', ' + 
       individualmiddlename + ', ' +
       CONVERT(NVARCHAR(36), documenttype) + ', ' + 
       'I' + ', ' +
       CONVERT(VARCHAR(23), modifiedon, 126)
FROM Inspection

Above, columns 'inspectionid' & 'documenttype' has uniqueidentifer datatype and so applied CONVERT(NVARCHAR(36)). column 'modifiedon' is datetime and so applied CONVERT(NVARCHAR(23), 'modifiedon', 126).

Parallel to above 2nd SELECT query matched 1st SELECT query as per datatype of each column.

Setting Timeout Value For .NET Web Service

After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,

client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);

How do I detect if software keyboard is visible on Android Device or not?

In Android you can detect through ADB shell. I wrote and use this method:

{
        JSch jsch = new JSch();
        try {
            Session session = jsch.getSession("<userName>", "<IP>", 22);
            session.setPassword("<Password>");
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            ChannelExec channel = (ChannelExec)session.openChannel("exec");
            BufferedReader in = new BufferedReader(new    
            InputStreamReader(channel.getInputStream()));
            channel.setCommand("C:/Android/android-sdk/platform-tools/adb shell dumpsys window 
            InputMethod | findstr \"mHasSurface\"");
            channel.connect();

            String msg = null;
            String msg2 = " mHasSurface=true";

            while ((msg = in.readLine()) != null) {
                Boolean isContain = msg.contains(msg2);
                log.info(isContain);
                if (isContain){
                    log.info("Hiding keyboard...");
                    driver.hideKeyboard();
                }
                else {
                    log.info("No need to hide keyboard.");
                }
            }

            channel.disconnect();
            session.disconnect();

        } catch (JSchException | IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Multiple actions were found that match the request in Web Api

This solution worked for me.

Please place Route2 first in WebApiConfig. Also Add HttpGet and HttpPost before each method and include controller name and method name in the url.

WebApiConfig =>

config.Routes.MapHttpRoute(
           name: "MapByAction",
           routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional });

Controller =>

public class ValuesController : ApiController
{

    [HttpPost]
    public string GetCustomer([FromBody] RequestModel req)
    {
        return "Customer";
    }

    [HttpPost]
    public string GetCustomerList([FromBody] RequestModel req)
    {
        return "Customer List";
    }
}

Url =>

http://localhost:7050/api/Values/GetCustomer

http://localhost:7050/api/Values/GetCustomerList

cmd line rename file with date and time

I took the above but had to add one more piece because it was putting a space after the hour which gave a syntax error with the rename command. I used:

    set HR=%time:~0,2%
    set HR=%Hr: =0% 
    set HR=%HR: =%
    rename c:\ops\logs\copyinvoices.log copyinvoices_results_%date:~10,4%-%date:~4,2%-%date:~7,2%_%HR%%time:~3,2%.log 

This gave me my format I needed: copyinvoices_results_2013-09-13_0845.log

Creating the Singleton design pattern in PHP5

This is the example of create singleton on Database class

design patterns 1) singleton

class Database{
  public static $instance;
  public static function getInstance(){
    if(!isset(Database::$instance)){
    Database::$instance=new Database();

     return Database::$instance;
    }

  }

  $db=Database::getInstance();
  $db2=Database::getInstance();
  $db3=Database::getInstance();

  var_dump($db);
  var_dump($db2);
  var_dump($db3);

then out put is --

  object(Database)[1]
  object(Database)[1]
  object(Database)[1]

use only single instance not create 3 instance

Error: Cannot find module html

I think you might need to declare a view engine.

If you want to use a view/template engine:

app.set('view engine', 'ejs');

or

app.set('view engine', 'jade');

But to render plain-html, see this post: Render basic HTML view?.

Determine if a String is an Integer in Java

The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.

public static boolean isInteger(String s) {
    return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
    if(s.isEmpty()) return false;
    for(int i = 0; i < s.length(); i++) {
        if(i == 0 && s.charAt(i) == '-') {
            if(s.length() == 1) return false;
            else continue;
        }
        if(Character.digit(s.charAt(i),radix) < 0) return false;
    }
    return true;
}

Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.

public static boolean isInteger(String s, int radix) {
    Scanner sc = new Scanner(s.trim());
    if(!sc.hasNextInt(radix)) return false;
    // we know it starts with a valid int, now make sure
    // there's nothing left!
    sc.nextInt(radix);
    return !sc.hasNext();
}

If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    } catch(NullPointerException e) {
        return false;
    }
    // only got here if we didn't return false
    return true;
}

Is mathematics necessary for programming?

See also Is Programmng == Math? from stackoverflow.

While I don't think it's required for programming, I can't tell you how many times I've been able to use linear algebra concepts to write a clear and short solution to replace a convoluted (and sometimes incorrect) one. When dong any graphics or geometry (and even some solver) work, knowledge of matrices and how to work with them has also been extremely useful.

How to Find Item in Dictionary Collection?

It's possible to find the element in Dictionary collection by using ContainsKey or TryGetValue as follows:

class Program
{
    protected static Dictionary<string, string> _tags = new Dictionary<string,string>();

    static void Main(string[] args)
    {
        string strValue;

        _tags.Add("101", "C#");
        _tags.Add("102", "ASP.NET");

        if (_tags.ContainsKey("101"))
        {
            strValue = _tags["101"];
            Console.WriteLine(strValue);
        }

        if (_tags.TryGetValue("101", out strValue))
        {
            Console.WriteLine(strValue);
        }
    }
}

Android webview slow

If you are binding to the onclick event, it might be slow on touch screens.

To make it faster, I use fastclick, which uses the much faster touch events to mimic the click event.

How to resolve "Could not find schema information for the element/attribute <xxx>"?

I configured the app.config with the tool for EntLib configuration and set up my LoggingConfiguration block. Then I copied this into the DotNetConfig.xsd. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.

<xs:element name="loggingConfiguration">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="listeners">
        <xs:complexType>
          <xs:sequence>
            <xs:element maxOccurs="unbounded" name="add">
              <xs:complexType>
                <xs:attribute name="fileName" type="xs:string" use="required" />
                <xs:attribute name="footer" type="xs:string" use="required" />
                <xs:attribute name="formatter" type="xs:string" use="required" />
                <xs:attribute name="header" type="xs:string" use="required" />
                <xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" />
                <xs:attribute name="rollInterval" type="xs:string" use="required" />
                <xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" />
                <xs:attribute name="timeStampPattern" type="xs:string" use="required" />
                <xs:attribute name="listenerDataType" type="xs:string" use="required" />
                <xs:attribute name="traceOutputOptions" type="xs:string" use="required" />
                <xs:attribute name="filter" type="xs:string" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="formatters">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="add">
              <xs:complexType>
                <xs:attribute name="template" type="xs:string" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="logFilters">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="add">
              <xs:complexType>
                <xs:attribute name="enabled" type="xs:boolean" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="categorySources">
        <xs:complexType>
          <xs:sequence>
            <xs:element maxOccurs="unbounded" name="add">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="listeners">
                    <xs:complexType>
                      <xs:sequence>
                        <xs:element name="add">
                          <xs:complexType>
                            <xs:attribute name="name" type="xs:string" use="required" />
                          </xs:complexType>
                        </xs:element>
                      </xs:sequence>
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="specialSources">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="allEvents">
              <xs:complexType>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
            <xs:element name="notProcessed">
              <xs:complexType>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
            <xs:element name="errors">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="listeners">
                    <xs:complexType>
                      <xs:sequence>
                        <xs:element name="add">
                          <xs:complexType>
                            <xs:attribute name="name" type="xs:string" use="required" />
                          </xs:complexType>
                        </xs:element>
                      </xs:sequence>
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
    <xs:attribute name="name" type="xs:string" use="required" />
    <xs:attribute name="tracingEnabled" type="xs:boolean" use="required" />
    <xs:attribute name="defaultCategory" type="xs:string" use="required" />
    <xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" />
  </xs:complexType>
</xs:element>

How do the post increment (i++) and pre increment (++i) operators work in Java?

Presuming that you meant

int a=5; int i;

i=++a + ++a + a++;

System.out.println(i);

a=5;

i=a++ + ++a + ++a;

System.out.println(i);

a=5;

a=++a + ++a + a++;

System.out.println(a);

This evaluates to:

i = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)

so i is 6 + 7 + 7 = 20 and so 20 is printed.

i = (5, a is now 6) + (7, a is now 7) + (8, a is now 8)

so i is 5 + 7 + 8 = 20 and so 20 is printed again.

a = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)

and after all of the right hand side is evaluated (including setting a to 8) THEN a is set to 6 + 7 + 7 = 20 and so 20 is printed a final time.

Determine the type of an object?

As an aside to the previous answers, it's worth mentioning the existence of collections.abc which contains several abstract base classes (ABCs) that complement duck-typing.

For example, instead of explicitly checking if something is a list with:

isinstance(my_obj, list)

you could, if you're only interested in seeing if the object you have allows getting items, use collections.abc.Sequence:

from collections.abc import Sequence
isinstance(my_obj, Sequence) 

if you're strictly interested in objects that allow getting, setting and deleting items (i.e mutable sequences), you'd opt for collections.abc.MutableSequence.

Many other ABCs are defined there, Mapping for objects that can be used as maps, Iterable, Callable, et cetera. A full list of all these can be seen in the documentation for collections.abc.

How to access SOAP services from iPhone

One word: Don't.

OK obviously that isn't a real answer. But still SOAP should be avoided at all costs. ;-) Is it possible to add a proxy server between the iPhone and the web service? Perhaps something that converts REST into SOAP for you?

You could try CSOAP, a SOAP library that depends on libxml2 (which is included in the iPhone SDK).

I've written my own SOAP framework for OSX. However it is not actively maintained and will require some time to port to the iPhone (you'll need to replace NSXML with TouchXML for a start)

Unsupported major.minor version 52.0 in my app

Gradle Scripts >> build.gradle (Module app)

Change buildToolsVersion "24.0.0" to buildToolsVersion "23.0.3"

source : experience

How to read a HttpOnly cookie using JavaScript

Different Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.

But more importantly why do you want to read an HTTPOnly cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly flag and "secure flag" (which forces the cookie to be sent over https) should always be set.

If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.

People have too much faith in the HTTPOnly flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.

How to Add Date Picker To VBA UserForm

You could try the "Microsoft Date and Time Picker Control". To use it, in the Toolbox, you right-click and choose "Additional Controls...". Then you check "Microsoft Date and Time Picker Control 6.0" and OK. You will have a new control in the Toolbox to do what you need.

I just found some printscreen of this on : http://www.logicwurks.com/CodeExamplePages/EDatePickerControl.html Forget the procedures, just check the printscreens.

How to redirect to Index from another controller?

Use the overloads that take the controller name too...

return RedirectToAction("Index", "MyController");

and

@Html.ActionLink("Link Name","Index", "MyController", null, null)

How to develop Desktop Apps using HTML/CSS/JavaScript?

NOTE: AppJS is deprecated and not recommended anymore.

Take a look at NW.js instead.

Where does Jenkins store configuration files for the jobs it runs?

The best approach would be to keep your job configurations in a Jenkinsfile that live in source control.

passing object by reference in C++

One thing that I have to add is that there is no reference in C.

Secondly, this is the language syntax convention. & - is an address operator but it also mean a reference - all depends on usa case

If there was some "reference" keyword instead of & you could write

int CDummy::isitme (reference CDummy param)

but this is C++ and we should accept it advantages and disadvantages...

How to make a drop down list in yii2?

This is about generating data, and so is more properly done from the model. Imagine if you ever wanted to change the way data is displayed in the drop-down box, say add a surname or something. You'd have to find every drop-down box and change the arrayHelper. I use a function in my models to return the data for a dropdown, so I don't have to repeat code in views. It also has the advantage that I can specify filter here and have them apply to every dropdown created from this model;

/* Model Standard.php */

public function getDropdown(){
      return ArrayHelper::map(self::find()->all(), 's_id', 'name'));
}

You can use this in your view file like this;

echo $form->field($model, 'attribute')
        ->dropDownList(
            $model->dropDown
        );

Change values on matplotlib imshow() graph axis

I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.

Here is an attempt at this with your data:

import matplotlib.pyplot as plt

# ... define 2D array hist as you did

plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case

How to escape "&" in XML?

use &amp; in place of &

change to

<string name="magazine">Newspaper &amp; Magazines</string>

How to create a new column in a select query

It depends what you wanted to do with that column e.g. here's an example of appending a new column to a recordset which can be updated on the client side:

Sub MSDataShape_AddNewCol()

  Dim rs As ADODB.Recordset
  Set rs = CreateObject("ADODB.Recordset")
  With rs
    .ActiveConnection = _
    "Provider=MSDataShape;" & _
    "Data Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=C:\Tempo\New_Jet_DB.mdb"
    .Source = _
    "SHAPE {" & _
    " SELECT ExistingField" & _
    " FROM ExistingTable" & _
    " ORDER BY ExistingField" & _
    "} APPEND NEW adNumeric(5, 4) AS NewField"

    .LockType = adLockBatchOptimistic

    .Open

    Dim i As Long
    For i = 0 To .RecordCount - 1
      .Fields("NewField").Value = Round(.Fields("ExistingField").Value, 4)
      .MoveNext
    Next

    rs.Save "C:\rs.xml", adPersistXML

  End With
End Sub

Convert string to ASCII value python

you can actually do it with numpy:

import numpy as np
a = np.fromstring('hi', dtype=np.uint8)
print(a)

Scrollbar without fixed height/Dynamic height with scrollbar

 <div id="scroll">
    <p>Try to add more text</p>
 </div>

here's the css code

#scroll {
   overflow-y:auto;
   height:auto;
   max-height:200px;
   border:1px solid black;
   width:300px;
 }

here's the demo JSFIDDLE

How do I search for names with apostrophe in SQL Server?

select * from Header where userID like '%''%'

Hope this helps.

What encoding/code page is cmd.exe using?

Command CHCP shows the current codepage. It has three digits: 8xx and is different from Windows 12xx. So typing a English-only text you wouldn't see any difference, but an extended codepage (like Cyrillic) will be printed wrongly.

Building a fat jar using maven

Note: If you are a spring-boot application, read the end of answer

Add following plugin to your pom.xml The latest version can be found at

...
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>CHOOSE LATEST VERSION HERE</version>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
            <executions>
                <execution>
                    <id>assemble-all</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
...

After configuring this plug-in, running mvn package will produce two jars: one containing just the project classes, and a second fat jar with all dependencies with the suffix "-jar-with-dependencies".

if you want correct classpath setup at runtime then also add following plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>fully.qualified.MainClass</mainClass>
            </manifest>
        </archive>
    </configuration>
</plugin>

For spring boot application use just following plugin (choose appropriate version of it)

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <fork>true</fork>
        <mainClass>${start-class}</mainClass>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>

How to convert a String to JsonObject using gson library

Looks like the above answer did not answer the question completely.

I think you are looking for something like below:

class TransactionResponse {

   String Success, Message;
   List<Response> Response;

}

TransactionResponse = new Gson().fromJson(response, TransactionResponse.class);

where my response is something like this:

{"Success":false,"Message":"Invalid access token.","Response":null}

As you can see, the variable name should be same as the Json string representation of the key in the key value pair. This will automatically convert your gson string to JsonObject.

Android: Cancel Async Task

I would like to improve the code. When you canel the aSyncTask the onCancelled() (callback method of aSyncTask) gets automatically called, and there you can hide your progressBarDialog.

You can include this code as well:

public class information extends AsyncTask<String, String, String>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... arg0) {
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            this.cancel(true);
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onCancelled() {
            Toast.makeText(getApplicationContext(), "asynctack cancelled.....", Toast.LENGTH_SHORT).show();
            dialog.hide(); /*hide the progressbar dialog here...*/
            super.onCancelled();
        }

    }

How to generate a range of numbers between two numbers?

SELECT DISTINCT n = number 
FROM master..[spt_values] 
WHERE number BETWEEN @start AND @end

Demo

Note that this table has a maximum of 2048 because then the numbers have gaps.

Here's a slightly better approach using a system view(since from SQL-Server 2005):

;WITH Nums AS
(
  SELECT n = ROW_NUMBER() OVER (ORDER BY [object_id]) 
  FROM sys.all_objects 

)
SELECT n FROM Nums 
WHERE n BETWEEN @start AND @end
ORDER BY n;

Demo

or use a custom a number-table. Credits to Aaron Bertrand, i suggest to read the whole article: Generate a set or sequence without loops

Getting values from query string in an url using AngularJS $location

Very late answer :( but for someone who is in need, this works Angular js works too :) URLSearchParams Let's have a look at how we can use this new API to get values from the location!

// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

FYI: IE is not supported

use this function from instead of URLSearchParams

urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log(urlParam('action')); //edit

Fix columns in horizontal scrolling

Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/

HTML

<h2>TableHeadFixer Fix Left Column</h2>

<div id="parent">
    <table id="fixTable" class="table">
        <thead>
            <tr>
                <th>Ano</th>
                <th>Jan</th>
                <th>Fev</th>
                <th>Mar</th>
                <th>Abr</th>
                <th>Maio</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
            <tr>
                <td>2012</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>110.00</td>
                <td>550.00</td>
            </tr>
        </tbody>
    </table>
</div>

JS

    $(document).ready(function() {
        $("#fixTable").tableHeadFixer({"head" : false, "right" : 1}); 
    });

CSS

    #parent {
        height: 300px;
    }

    #fixTable {
        width: 1800px !important;
    }

https://jsfiddle.net/5gfuqqc4/

How to make PyCharm always show line numbers

Using Search bar

  1. Press 2 times Shift
  2. Paste /editor /appearance/ and then
  3. Click on Show line numbers toggle button

For Windows and Linux

File | Settings | Editor | General | Appearance 

For macOS

IntelliJ IDEA | Preferences | Editor | General | Appearance 

Using shortcut

Ctrl+Alt+S

Then

Editor > General > Appearance

Click on Show line numbers toggle button.


Pycharm Official Doc (Appearance)

Where can I read the Console output in Visual Studio 2015

My problem was that I needed to Reset Window Layout.

Reset Window Layout

How to view the stored procedure code in SQL Server Management Studio

The other answers that recommend using the object explorer and scripting the stored procedure to a new query editor window and the other queries are solid options.

I personally like using the below query to retrieve the stored procedure definition/code in a single row (I'm using Microsoft SQL Server 2014, but looks like this should work with SQL Server 2008 and up)

SELECT definition 
FROM sys.sql_modules 
WHERE object_id = OBJECT_ID('yourSchemaName.yourStoredProcedureName')

More info on sys.sql_modules:

https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-sql-modules-transact-sql

MySQL: ALTER TABLE if column not exists

Add field if not exist:

CALL addFieldIfNotExists ('settings', 'multi_user', 'TINYINT(1) NOT NULL DEFAULT 1');

addFieldIfNotExists code:

DELIMITER $$

DROP PROCEDURE IF EXISTS addFieldIfNotExists 
$$

DROP FUNCTION IF EXISTS isFieldExisting 
$$

CREATE FUNCTION isFieldExisting (table_name_IN VARCHAR(100), field_name_IN VARCHAR(100)) 
RETURNS INT
RETURN (
    SELECT COUNT(COLUMN_NAME) 
    FROM INFORMATION_SCHEMA.columns 
    WHERE TABLE_SCHEMA = DATABASE() 
    AND TABLE_NAME = table_name_IN 
    AND COLUMN_NAME = field_name_IN
)
$$

CREATE PROCEDURE addFieldIfNotExists (
    IN table_name_IN VARCHAR(100)
    , IN field_name_IN VARCHAR(100)
    , IN field_definition_IN VARCHAR(100)
)
BEGIN

    SET @isFieldThere = isFieldExisting(table_name_IN, field_name_IN);
    IF (@isFieldThere = 0) THEN

        SET @ddl = CONCAT('ALTER TABLE ', table_name_IN);
        SET @ddl = CONCAT(@ddl, ' ', 'ADD COLUMN') ;
        SET @ddl = CONCAT(@ddl, ' ', field_name_IN);
        SET @ddl = CONCAT(@ddl, ' ', field_definition_IN);

        PREPARE stmt FROM @ddl;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

    END IF;

END;
$$

How to check if IsNumeric

You could write an extension method:

public static class Extension
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

How to do constructor chaining in C#

What is usage of "Constructor Chain"?
You use it for calling one constructor from another constructor.

How can implement "Constructor Chain"?
Use ": this (yourProperties)" keyword after definition of constructor. for example:

Class MyBillClass
{
    private DateTime requestDate;
    private int requestCount;

    public MyBillClass()
    {
        /// ===== we naming "a" constructor ===== ///
        requestDate = DateTime.Now;
    }
    public MyBillClass(int inputCount) : this()
    {
        /// ===== we naming "b" constructor ===== ///
        /// ===== This method is "Chained Method" ===== ///
        this.requestCount= inputCount;
    }
}

Why is it useful?
Important reason is reduce coding, and prevention of duplicate code. such as repeated code for initializing property Suppose some property in class must be initialized with specific value (In our sample, requestDate). And class have 2 or more constructor. Without "Constructor Chain", you must repeat initializaion code in all constractors of class.

How it work? (Or, What is execution sequence in "Constructor Chain")?
in above example, method "a" will be executed first, and then instruction sequence will return to method "b". In other word, above code is equal with below:

Class MyBillClass
{
    private DateTime requestDate;
    private int requestCount;

    public MyBillClass()
    {
        /// ===== we naming "a" constructor ===== ///
        requestDate = DateTime.Now;
    }
    public MyBillClass(int inputCount) : this()
    {
        /// ===== we naming "b" constructor ===== ///
        // ===== This method is "Chained Method" ===== ///

        /// *** --- > Compiler execute "MyBillClass()" first, And then continue instruction sequence from here
        this.requestCount= inputCount;
    }
}

show/hide a div on hover and hover out

Here are different method of doing this. And i found your code is even working fine.

Your code: http://jsfiddle.net/NKC2j/

Jquery toggle class demo: http://jsfiddle.net/NKC2j/2/

Jquery fade toggle: http://jsfiddle.net/NKC2j/3/

Jquery slide toggle: http://jsfiddle.net/NKC2j/4/

And you can do this with CSS as answered by Sandeep

Facebook Graph API error code list

I was looking for the same thing and I just found this list

https://developers.facebook.com/docs/reference/api/errors/

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

Global Variable from a different file Python

All given answers are wrong. It is impossible to globalise a variable inside a function in a separate file.

Adding a JAR to an Eclipse Java library

In Eclipse Ganymede (3.4.0):

  1. Select the library and click "Edit" (left side of the window)
  2. Click "User Libraries"
  3. Select the library again and click "Add JARs"

jQuery function after .append

Cleanest way is to do it step by step. Use an each funciton to itterate through each element. As soon as that element is appended, pass it to a subsequent function to process that element.

    function processAppended(el){
        //process appended element
    }

    var remove = '<a href="#">remove</a>' ;
    $('li').each(function(){
        $(this).append(remove);   
        processAppended(this);    
    });?

How to split one string into multiple strings separated by at least one space in bash shell?

Just use the shells "set" built-in. For example,

set $text

After that, individual words in $text will be in $1, $2, $3, etc. For robustness, one usually does

set -- junk $text
shift

to handle the case where $text is empty or start with a dash. For example:

text="This is          a              test"
set -- junk $text
shift
for word; do
  echo "[$word]"
done

This prints

[This]
[is]
[a]
[test]

How do I stop Notepad++ from showing autocomplete for all words in the file

The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

Insert current date/time using now() in a field using MySQL/PHP

You forgot to close the mysql_query command:

mysql_query("INSERT INTO users (first, last, whenadded) VALUES ('$first', '$last', now())");

Note that last parentheses.

How to convert an Image to base64 string in java?

The problem is that you are returning the toString() of the call to Base64.encodeBase64(bytes) which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.

Instead, you should do:

encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");

Deleting array elements in JavaScript - delete vs splice

Performance

There are already many nice answer about functional differences - so here I want to focus on performance. Today (2020.06.25) I perform tests for Chrome 83.0, Safari 13.1 and Firefox 77.0 for solutions mention in question and additionally from chosen answers

Conclusions

  • the splice (B) solution is fast for small and big arrays
  • the delete (A) solution is fastest for big and medium fast for small arrays
  • the filter (E) solution is fastest on Chrome and Firefox for small arrays (but slowest on Safari, and slow for big arrays)
  • solution D is quite slow
  • solution C not works for big arrays in Chrome and Safari
    _x000D_
    _x000D_
    function C(arr, idx) {
      var rest = arr.slice(idx + 1 || arr.length);
      arr.length = idx < 0 ? arr.length + idx : idx;
      arr.push.apply(arr, rest);
      return arr;
    }
    
    
    // Crash test
    
    let arr = [...'abcdefghij'.repeat(100000)]; // 1M elements
    
    try {
     C(arr,1)
    } catch(e) {console.error(e.message)}
    _x000D_
    _x000D_
    _x000D_

enter image description here

Details

I perform following tests for solutions A B C D E (my)

  • for small array (4 elements) - you can run test HERE
  • for big array (1M elements) - you can run test HERE

_x000D_
_x000D_
function A(arr, idx) {
  delete arr[idx];
  return arr;
}

function B(arr, idx) {
  arr.splice(idx,1);
  return arr;
}

function C(arr, idx) {
  var rest = arr.slice(idx + 1 || arr.length);
  arr.length = idx < 0 ? arr.length + idx : idx;
  arr.push.apply(arr, rest);
  return arr;
}

function D(arr,idx){
    return arr.slice(0,idx).concat(arr.slice(idx + 1));
}

function E(arr,idx) {
  return arr.filter((a,i) => i !== idx);
}

myArray = ['a', 'b', 'c', 'd'];

[A,B,C,D,E].map(f => console.log(`${f.name} ${JSON.stringify(f([...myArray],1))}`));
_x000D_
This snippet only presents used solutions
_x000D_
_x000D_
_x000D_

Example results for Chrome

enter image description here

How can I uninstall Ruby on ubuntu?

You can use sudo apt remove ruby

Smooth scroll without the use of jQuery

Algorithm

Scrolling an element requires changing its scrollTop value over time. For a given point in time, calculate a new scrollTop value. To animate smoothly, interpolate using a smooth-step algorithm.

Calculate scrollTop as follows:

var point = smooth_step(start_time, end_time, now);
var scrollTop = Math.round(start_top + (distance * point));

Where:

  • start_time is the time the animation started;
  • end_time is when the animation will end (start_time + duration);
  • start_top is the scrollTop value at the beginning; and
  • distance is the difference between the desired end value and the start value (target - start_top).

A robust solution should detect when animating is interrupted, and more. Read my post about Smooth Scrolling without jQuery for details.

Demo

See the JSFiddle.

Implementation

The code:

/**
    Smoothly scroll element to the given target (element.scrollTop)
    for the given duration

    Returns a promise that's fulfilled when done, or rejected if
    interrupted
 */
var smooth_scroll_to = function(element, target, duration) {
    target = Math.round(target);
    duration = Math.round(duration);
    if (duration < 0) {
        return Promise.reject("bad duration");
    }
    if (duration === 0) {
        element.scrollTop = target;
        return Promise.resolve();
    }

    var start_time = Date.now();
    var end_time = start_time + duration;

    var start_top = element.scrollTop;
    var distance = target - start_top;

    // based on http://en.wikipedia.org/wiki/Smoothstep
    var smooth_step = function(start, end, point) {
        if(point <= start) { return 0; }
        if(point >= end) { return 1; }
        var x = (point - start) / (end - start); // interpolation
        return x*x*(3 - 2*x);
    }

    return new Promise(function(resolve, reject) {
        // This is to keep track of where the element's scrollTop is
        // supposed to be, based on what we're doing
        var previous_top = element.scrollTop;

        // This is like a think function from a game loop
        var scroll_frame = function() {
            if(element.scrollTop != previous_top) {
                reject("interrupted");
                return;
            }

            // set the scrollTop for this frame
            var now = Date.now();
            var point = smooth_step(start_time, end_time, now);
            var frameTop = Math.round(start_top + (distance * point));
            element.scrollTop = frameTop;

            // check if we're done!
            if(now >= end_time) {
                resolve();
                return;
            }

            // If we were supposed to scroll but didn't, then we
            // probably hit the limit, so consider it done; not
            // interrupted.
            if(element.scrollTop === previous_top
                && element.scrollTop !== frameTop) {
                resolve();
                return;
            }
            previous_top = element.scrollTop;

            // schedule next frame for execution
            setTimeout(scroll_frame, 0);
        }

        // boostrap the animation process
        setTimeout(scroll_frame, 0);
    });
}

What is the default maximum heap size for Sun's JVM from Java SE 6?

One can ask with some Java code:

long maxBytes = Runtime.getRuntime().maxMemory();
System.out.println("Max memory: " + maxBytes / 1024 / 1024 + "M");

See javadoc.

SELECT DISTINCT on one column

try this:

SELECT 
    t.*
    FROM TestData t
        INNER JOIN (SELECT
                        MIN(ID) as MinID
                        FROM TestData
                        WHERE SKU LIKE 'FOO-%'
                   ) dt ON t.ID=dt.MinID

EDIT
once the OP corrected his samle output (previously had only ONE result row, now has all shown), this is the correct query:

declare @TestData table (ID int, sku char(6), product varchar(15))
insert into @TestData values (1 ,  'FOO-23'      ,'Orange')
insert into @TestData values (2 ,  'BAR-23'      ,'Orange')
insert into @TestData values (3 ,  'FOO-24'      ,'Apple')
insert into @TestData values (4 ,  'FOO-25'      ,'Orange')

--basically the same as @Aaron Alton's answer:
SELECT
    dt.ID, dt.SKU, dt.Product
    FROM (SELECT
              ID, SKU, Product, ROW_NUMBER() OVER (PARTITION BY PRODUCT ORDER BY ID) AS RowID
              FROM @TestData
              WHERE  SKU LIKE 'FOO-%'
         ) AS dt
    WHERE dt.RowID=1
    ORDER BY dt.ID

Where does System.Diagnostics.Debug.Write output appear?

While you are debugging in Visual Studio, display the "Output" window (View->Output). It will show there.

Export table from database to csv file

And when you want all tables for some reason ?

You can generate these commands in SSMS:

SELECT 
CONCAT('sqlcmd -S ',
'Your(local?)SERVERhere'
,' -d',
'YourDB'
,' -E -s, -W -Q "SELECT * FROM ',
TABLE_NAME,
'" >',
TABLE_NAME,
'.csv') FROM INFORMATION_SCHEMA.TABLES

And get again rows like this

sqlcmd -S ... -d... -E -s, -W -Q "SELECT * FROM table1" >table1.csv
sqlcmd -S ... -d... -E -s, -W -Q "SELECT * FROM table2" >table2.csv
...

There is also option to use better TAB as delimiter, but it would need a strange Unicode character - using Alt+9 in CMD, it came like this ? (Unicode CB25), but works only by copy/paste to command line not in batch.

How to pick element inside iframe using document.getElementById

document.getElementById('myframe1').contentWindow.document.getElementById('x')

Fiddle

contentWindow is supported by all browsers including the older versions of IE.

Note that if the iframe's src is from another domain, you won't be able to access its content due to the Same Origin Policy.

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

read complete file without using loop in java

You can try using Scanner if you are using JDK5 or higher.

Scanner scan = new Scanner(file);  
scan.useDelimiter("\\Z");  
String content = scan.next(); 

Or you can also use Guava

String data = Files.toString(new File("path.txt"), Charsets.UTF8);

What's the difference between an Angular component and module

A module in Angular 2 is something which is made from components, directives, services etc. One or many modules combine to make an Application. Modules breakup application into logical pieces of code. Each module performs a single task.

Components in Angular 2 are classes where you write your logic for the page you want to display. Components control the view (html). Components communicate with other components and services.

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

Let's say you're using this HTML5 layout:

<html>
    <body>
        <header>
            <nav><ul>...</ul></nav>
        </header>
        <article>
            <ul>...</ul>
        </article>
        <footer>
            <ul>...</ul>
        </footer>
    </body>
</html>

You could say in your CSS:

header ul, footer ul, nav ul { list-style-type: none; }

If you're using HTML 4, assign IDs to your DIVs (instead of using the new fancy-pants elements) and change this to:

#header ul, #footer ul, #nav ul { list-style-type: none; }

If you're using a CSS reset stylesheet (like Eric Meyer's), you would actually have to give the list style back, since the reset removes the list style from all lists.

#content ul { list-style-type: disc; margin-left: 1.5em; }

How to bind a List to a ComboBox?

As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a BindingList)

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }
    public Country(string _name)
    {
        Cities = new List<City>();
        Name = _name;
    }
}



List<Country> countries = new List<Country> { new Country("UK"), 
                                     new Country("Australia"), 
                                     new Country("France") };

var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;

comboBox1.DataSource = bindingSource1.DataSource;

comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";

To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1.SelectedItem;.

If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the DataSource implements IBindingList; one such structure is BindingList<T>.


Tip: make sure that you are binding the DisplayMember to a Property on the class and not a public field. If you class uses public string Name { get; set; } it will work but if it uses public string Name; it will not be able to access the value and instead will display the object type for each line in the combo box.

Arrays in unix shell?

You can try of the following type :

#!/bin/bash
 declare -a arr

 i=0
 j=0

  for dir in $(find /home/rmajeti/programs -type d)
   do
        arr[i]=$dir
        i=$((i+1))
   done


  while [ $j -lt $i ]
  do
        echo ${arr[$j]}
        j=$((j+1))
  done

How to set DialogFragment's width and height?

Here's a way to set DialogFragment width/height in xml. Just wrap your viewHierarchy in a Framelayout (any layout will work) with a transparent background.

A transparent background seems to be a special flag, because it automatically centers the frameLayout's child in the window when you do that. You will still get the full screen darkening behind your fragment, indicating your fragment is the active element.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/transparent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:background="@color/background_material_light">

      .....

Use and meaning of "in" in an if statement?

Here raw_input is string, so if you wanted to check, if var>3 then you should convert next to double, ie float(next) and do as you would do if float(next)>3:, but in most cases

Multi-Line Comments in Ruby?

#!/usr/bin/env ruby

=begin
Between =begin and =end, any number
of lines may be written. All of these
lines are ignored by the Ruby interpreter.
=end

puts "Hello world!"

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

How to edit one specific row/tuple in Server Management Studio 2008/2012/2014/2016

Step 1: Right button mouse > Select "Edit Top 200 Rows"

Edit top 200 rows

Step 2: Navigate to Query Designer > Pane > SQL (Shortcut: Ctrl+3)

Navigate to Query Designer > Pane > SQL

Step 3: Modify the query

Modify the query

Step 4: Right button mouse > Select "Execute SQL" (Shortcut: Ctrl+R)

enter image description here

SQL sum with condition

With condition HAVING you will eliminate data with cash not ultrapass 0 if you want, generating more efficiency in your query.

SELECT SUM(cash) AS money FROM Table t1, Table2 t2 WHERE t1.branch = t2.branch 
AND t1.transID = t2.transID
AND ValueDate > @startMonthDate HAVING money > 0;

Use a normal link to submit a form

use:

<input type="image" src=".."/>

or:

<button type="send"><img src=".."/> + any html code</button>

plus some CSS

c++ string array initialization

In C++11 and above, you can also initialize std::vector with an initializer list. For example:

using namespace std; // for example only

for (auto s : vector<string>{"one","two","three"} ) 
    cout << s << endl;

So, your example would become:

void foo(vector<string> strArray){
  // some code
}

vector<string> s {"hi", "there"}; // Works
foo(s); // Works

foo(vector<string> {"hi", "there"}); // also works

How to start working with GTest and CMake

Yours and VladLosevs' solutions are probably better than mine. If you want a brute-force solution, however, try this:

SET(CMAKE_EXE_LINKER_FLAGS /NODEFAULTLIB:\"msvcprtd.lib;MSVCRTD.lib\")

FOREACH(flag_var
    CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
    CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
    if(${flag_var} MATCHES "/MD")
        string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
    endif(${flag_var} MATCHES "/MD")
ENDFOREACH(flag_var)

Where can I download JSTL jar

If youre using Maven, here's something for your pom.xml file

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

What is the maximum size of a web browser's cookie's key?

Actually, RFC 2965, the document that defines how cookies work, specifies that there should be no maximum length of a cookie's key or value size, and encourages implementations to support arbitrarily large cookies. Each browser's implementation maximum will necessarily be different, so consult individual browser documentation.

See section 5.3, "Implementation Limits", in the RFC.

Run text file as commands in Bash

you can also just run it with a shell, for example:

bash example.txt

sh example.txt

psycopg2: insert multiple rows with one query

Update with psycopg2 2.7:

The classic executemany() is about 60 times slower than @ant32 's implementation (called "folded") as explained in this thread: https://www.postgresql.org/message-id/20170130215151.GA7081%40deb76.aryehleib.com

This implementation was added to psycopg2 in version 2.7 and is called execute_values():

from psycopg2.extras import execute_values
execute_values(cur,
    "INSERT INTO test (id, v1, v2) VALUES %s",
    [(1, 2, 3), (4, 5, 6), (7, 8, 9)])

Previous Answer:

To insert multiple rows, using the multirow VALUES syntax with execute() is about 10x faster than using psycopg2 executemany(). Indeed, executemany() just runs many individual INSERT statements.

@ant32 's code works perfectly in Python 2. But in Python 3, cursor.mogrify() returns bytes, cursor.execute() takes either bytes or strings, and ','.join() expects str instance.

So in Python 3 you may need to modify @ant32 's code, by adding .decode('utf-8'):

args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x).decode('utf-8') for x in tup)
cur.execute("INSERT INTO table VALUES " + args_str)

Or by using bytes (with b'' or b"") only:

args_bytes = b','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup)
cur.execute(b"INSERT INTO table VALUES " + args_bytes) 

C++ pass an array by reference

Arrays can only be passed by reference, actually:

void foo(double (&bar)[10])
{
}

This prevents you from doing things like:

double arr[20];
foo(arr); // won't compile

To be able to pass an arbitrary size array to foo, make it a template and capture the size of the array at compile time:

template<typename T, size_t N>
void foo(T (&bar)[N])
{
    // use N here
}

You should seriously consider using std::vector, or if you have a compiler that supports c++11, std::array.

What is the "-->" operator in C/C++?

My compiler will print out 9876543210 when I run this code.

#include <iostream>
int main()
{
    int x = 10;

    while( x --> 0 ) // x goes to 0
    {
        std::cout << x;
    }
}

As expected. The while( x-- > 0 ) actually means while( x > 0). The x-- post decrements x.

while( x > 0 ) 
{
    x--;
    std::cout << x;
}

is a different way of writing the same thing.

It is nice that the original looks like "while x goes to 0" though.

referenced before assignment error in python

My Scenario

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] # access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   # these won't

    inner()

How to make a custom LinkedIn share button

You can customize the standard Linkedin button like this, after the page load:

$(".IN-widget span:first-of-type").css({
                'border': '2px solid #DCDCDC',
                '-webkit-border-radius': '3px',
                '-moz-border-radius': '3px',
                'border-radius': '3px'
                });

Ansible date variable

I tried the lookup('pipe,'date') method and got trouble when I push the playbook to the tower. The tower is somehow using UTC timezone. All play executed as early as the + hours of my TZ will give me one day later of the actual date.

For example: if my TZ is Asia/Manila I supposed to have UTC+8. If I execute the playbook earlier than 8:00am in Ansible Tower, the date will follow to what was in UTC+0. It took me a while until I found this case. It let me use the date option '-d \"+8 hours\" +%F'. Now it gives me the exact date that I wanted.

Below is the variable I set in my playbook:

  vars:
    cur_target_wd: "{{ lookup('pipe','date -d \"+8 hours\" +%Y/%m-%b/%d-%a') }}"

That will give me the value of "cur_target_wd = 2020/05-May/28-Thu" even I run it earlier than 8:00am now.

what is the use of $this->uri->segment(3) in codeigniter pagination

Let's say you have a url like this http://www.example.com/controller/action/arg1/arg2

If you want to know what are the arguments that are being passed in this url

$param_offset=0;
$params = array_slice($this->uri->rsegment_array(), $param_offset);
var_dump($params);

Output will be:

array (size=2)
  0 => string 'arg1'
  1 => string 'arg2'

Apply vs transform on a group object

you can use zscore to analyze the data in column C and D for outliers, where zscore is the series - series.mean / series.std(). Use apply too create a user defined function for difference between C and D creating a new resulting dataframe. Apply uses the group result set.

from scipy.stats import zscore

columns = ['A', 'B', 'C', 'D']
records = [
['foo', 'one', 0.162003, 0.087469],
['bar', 'one', -1.156319, -1.5262719999999999],
['foo', 'two', 0.833892, -1.666304],     
['bar', 'three', -2.026673, -0.32205700000000004],
['foo', 'two', 0.41145200000000004, -0.9543709999999999],
['bar', 'two', 0.765878, -0.095968],
['foo', 'one', -0.65489, 0.678091],
['foo', 'three', -1.789842, -1.130922]
]
df = pd.DataFrame.from_records(records, columns=columns)
print(df)

standardize=df.groupby('A')['C','D'].transform(zscore)
print(standardize)
outliersC= (standardize['C'] <-1.1) | (standardize['C']>1.1)
outliersD= (standardize['D'] <-1.1) | (standardize['D']>1.1)

results=df[outliersC | outliersD]
print(results)

   #Dataframe results
   A      B         C         D
   0  foo    one  0.162003  0.087469
   1  bar    one -1.156319 -1.526272
   2  foo    two  0.833892 -1.666304
   3  bar  three -2.026673 -0.322057
   4  foo    two  0.411452 -0.954371
   5  bar    two  0.765878 -0.095968
   6  foo    one -0.654890  0.678091
   7  foo  three -1.789842 -1.130922
 #C and D transformed Z score
           C         D
 0  0.398046  0.801292
 1 -0.300518 -1.398845
 2  1.121882 -1.251188
 3 -1.046514  0.519353
 4  0.666781 -0.417997
 5  1.347032  0.879491
 6 -0.482004  1.492511
 7 -1.704704 -0.624618

 #filtering using arbitrary ranges -1 and 1 for the z-score
      A      B         C         D
 1  bar    one -1.156319 -1.526272
 2  foo    two  0.833892 -1.666304
 5  bar    two  0.765878 -0.095968
 6  foo    one -0.654890  0.678091
 7  foo  three -1.789842 -1.130922


 >>>>>>>>>>>>> Part 2

 splitting = df.groupby('A')

 #look at how the data is grouped
 for group_name, group in splitting:
     print(group_name)

 def column_difference(gr):
      return gr['C']-gr['D']

 grouped=splitting.apply(column_difference)
 print(grouped)

 A     
 bar  1    0.369953
      3   -1.704616
      5    0.861846
 foo  0    0.074534
      2    2.500196
      4    1.365823
      6   -1.332981
      7   -0.658920

What is content-type and datatype in an AJAX request?

See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.

They are both used in the request to the server so the server knows what kind of data to receive/send.

How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service

user334291's answer was a life saver for me. Just want to add how you can add what the OP originally intended to do (what I ended up using):

Overriding the GetWebRequest function on the generated webservice code:

protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
    System.Net.WebRequest request = base.GetWebRequest(uri);          
    string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(this.Credentials.GetCredential(uri, "Basic").UserName + ":" + this.Credentials.GetCredential(uri, "Basic").Password));
    request.Headers.Add("Authorization", auth);
    return request;
}

and setting the credentials before calling the webservice:

  client.Credentials = new NetworkCredential(user, password);       

What is duck typing?

I know I am not giving generalized answer. In Ruby, we don’t declare the types of variables or methods— everything is just some kind of object. So Rule is "Classes Aren’t Types"

In Ruby, the class is never (OK, almost never) the type. Instead, the type of an object is defined more by what that object can do. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck.

For example, you may be writing a routine to add song information to a string. If you come from a C# or Java background, you may be tempted to write this:

def append_song(result, song)
    # test we're given the right parameters 
    unless result.kind_of?(String)
        fail TypeError.new("String expected") end
    unless song.kind_of?(Song)
        fail TypeError.new("Song expected")
end

result << song.title << " (" << song.artist << ")" end
result = ""

append_song(result, song) # => "I Got Rhythm (Gene Kelly)"

Embrace Ruby’s duck typing, and you’d write something far simpler:

def append_song(result, song)
    result << song.title << " (" << song.artist << ")"
end

result = ""
append_song(result, song) # => "I Got Rhythm (Gene Kelly)"

You don’t need to check the type of the arguments. If they support << (in the case of result) or title and artist (in the case of song), everything will just work. If they don’t, your method will throw an exception anyway (just as it would have done if you’d checked the types). But without the check, your method is suddenly a lot more flexible. You could pass it an array, a string, a file, or any other object that appends using <<, and it would just work.

Send an Array with an HTTP Get

That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3).[4][5]

Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.

foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]

The request.getParameter("foo") will also work on it, but it'll return only the first value.

String foo = request.getParameter("foo"); // value1

And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces [] in order to trigger the language to return an array of values instead of a single value.

foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true

In case you still use foo=value1&foo=value2&foo=value3, then it'll return only the first value.

$foo = $_GET["foo"]; // value1
echo is_array($foo); // false

Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3 to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.

String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]

Does HTML5 <video> playback support the .avi format?

The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. User agents are free to support any video formats they feel are appropriate.

http://en.wikipedia.org/wiki/HTML5_video

How to round up the result of integer division?

For records == 0, rjmunro's solution gives 1. The correct solution is 0. That said, if you know that records > 0 (and I'm sure we've all assumed recordsPerPage > 0), then rjmunro solution gives correct results and does not have any of the overflow issues.

int pageCount = 0;
if (records > 0)
{
    pageCount = (((records - 1) / recordsPerPage) + 1);
}
// no else required

All the integer math solutions are going to be more efficient than any of the floating point solutions.

How to check if a column is empty or null using SQL query select statement?

Here is my preferred way to check for "if null or empty":

SELECT * 
FROM UserProfile 
WHERE PropertydefinitionID in (40, 53) 
AND NULLIF(PropertyValue, '') is null

Since it modifies the search argument (SARG) it might have performance issues because it might not use an existing index on the PropertyValue column.

Vue 'export default' vs 'new Vue'

export default is used to create local registration for Vue component.

Here is a great article that explain more about components https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e

Why does an image captured using camera intent gets rotated on some devices on Android?

I solved it using a different method. All you have to do is check if the width is greater than height

            Matrix rotationMatrix = new Matrix();
        if(finalBitmap.getWidth() >= finalBitmap.getHeight())
        {
            rotationMatrix.setRotate(-90);
        }
        else
        {
            rotationMatrix.setRotate(0);
        }

        Bitmap rotatedBitmap = Bitmap.createBitmap(finalBitmap,0,0,finalBitmap.getWidth(),finalBitmap.getHeight(),rotationMatrix,true);

"OverflowError: Python int too large to convert to C long" on windows but not mac

You'll get that error once your numbers are greater than sys.maxsize:

>>> p = [sys.maxsize]
>>> preds[0] = p
>>> p = [sys.maxsize+1]
>>> preds[0] = p
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

You can confirm this by checking:

>>> import sys
>>> sys.maxsize
2147483647

To take numbers with larger precision, don't pass an int type which uses a bounded C integer behind the scenes. Use the default float:

>>> preds = np.zeros((1, 3))

Eclipse copy/paste entire line keyboard shortcut

We can assign any command to any action(given) in Eclipse From Menu Bar go to Window > Preferences then search for the keys then search copy line then click on copy line and then click on command in Binding and peform a command which you wish to use for duplicating line i use ctrl+shift+d you can choose whatever you want enter image description here

Copying files using rsync from remote server to local machine

I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).

If you have configured ssh key to connect to your remote server, you could use the following command:

rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/

Where v option is --verbose, a option is --archive - archive mode, P option same as --partial - keep partially transferred files, e option is --rsh=COMMAND - specifying the remote shell to use.

rsync man page

What does enumerate() mean?

I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate instead. I know you asked what enumerate means, but when I understood the following, I also understood how enumerate makes iterating over a list while knowing the index of the current item easier (and more readable).

list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
    letter = list_of_letters[i]
    print (i, letter)

The output is:

0 a
1 b
2 c

I also used to do something, even sillier before I read about the enumerate function.

i = 0
for n in list_of_letters:
    print (i, n)
    i += 1

It produces the same output.

But with enumerate I just have to write:

list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
    print (i, letter)

How to get height of Keyboard?

Swift 5

override func viewDidLoad() {
    //  Registering for keyboard notification.
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}


/*  UIKeyboardWillShowNotification. */
    @objc internal func keyboardWillShow(_ notification : Notification?) -> Void {
        
        var _kbSize:CGSize!
        
        if let info = notification?.userInfo {

            let frameEndUserInfoKey = UIResponder.keyboardFrameEndUserInfoKey
            
            //  Getting UIKeyboardSize.
            if let kbFrame = info[frameEndUserInfoKey] as? CGRect {
                
                let screenSize = UIScreen.main.bounds
                
                //Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381)
                let intersectRect = kbFrame.intersection(screenSize)
                
                if intersectRect.isNull {
                    _kbSize = CGSize(width: screenSize.size.width, height: 0)
                } else {
                    _kbSize = intersectRect.size
                }
                print("Your Keyboard Size \(_kbSize)")
            }
        }
    }

how to compare the Java Byte[] array?

why a[] doesn't equals b[]? Because equals function really called on Byte[] or byte[] is Object.equals(Object obj). This functions only compares object identify , don't compare the contents of the array.

Proper use of const for defining functions in JavaScript

Although using const to define functions seems like a hack, but it comes with some great advantages that make it superior (in my opinion)

  1. It makes the function immutable, so you don't have to worry about that function being changed by some other piece of code.

  2. You can use fat arrow syntax, which is shorter & cleaner.

  3. Using arrow functions takes care of this binding for you.

example with function

_x000D_
_x000D_
// define a function_x000D_
function add(x, y) { return x + y; }_x000D_
_x000D_
// use it_x000D_
console.log(add(1, 2)); // 3_x000D_
_x000D_
// oops, someone mutated your function_x000D_
add = function (x, y) { return x - y; };_x000D_
_x000D_
// now this is not what you expected_x000D_
console.log(add(1, 2)); // -1
_x000D_
_x000D_
_x000D_

same example with const

_x000D_
_x000D_
// define a function (wow! that is 8 chars shorter)_x000D_
const add = (x, y) => x + y;_x000D_
_x000D_
// use it_x000D_
console.log(add(1, 2)); // 3_x000D_
_x000D_
// someone tries to mutate the function_x000D_
add = (x, y) => x - y; // Uncaught TypeError: Assignment to constant variable._x000D_
// the intruder fails and your function remains unchanged
_x000D_
_x000D_
_x000D_

How can I define an array of objects?

Array<T>

person: Array<{
  name: string;
  age: number;
}>

How to use an arraylist as a prepared statement parameter

You may want to use setArray method as mentioned in the javadoc below:

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)

Sample Code:

PreparedStatement pstmt = 
                conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", new Object[]{"1", "2","3"});
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();

Error: expected type-specifier before 'ClassName'

First of all, let's try to make your code a little simpler:

// No need to create a circle unless it is clearly necessary to
// demonstrate the problem

// Your Rect2f defines a default constructor, so let's use it for simplicity.
shared_ptr<Shape> rect(new Rect2f());

Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:

int main() {
    delete new T();
}

This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:

In function 'int main()':
Line 2: error: expected type-specifier before 'T'

Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f.

What is the difference between a hash join and a merge join (Oracle RDBMS )?

I just want to edit this for posterity that the tags for oracle weren't added when I answered this question. My response was more applicable to MS SQL.

Merge join is the best possible as it exploits the ordering, resulting in a single pass down the tables to do the join. IF you have two tables (or covering indexes) that have their ordering the same such as a primary key and an index of a table on that key then a merge join would result if you performed that action.

Hash join is the next best, as it's usually done when one table has a small number (relatively) of items, its effectively creating a temp table with hashes for each row which is then searched continuously to create the join.

Worst case is nested loop which is order (n * m) which means there is no ordering or size to exploit and the join is simply, for each row in table x, search table y for joins to do.

How do I copy a 2 Dimensional array in Java?

I am using this function:

public static int[][] copy(final int[][] array) {
    if (array != null) {
        final int[][] copy = new int[array.length][];

        for (int i = 0; i < array.length; i++) {
            final int[] row = array[i];

            copy[i] = new int[row.length];
            System.arraycopy(row, 0, copy[i], 0, row.length);
        }

        return copy;
    }

    return null;
}

The big advantage of this approach is that it can also copy arrays that don't have the same row count such as:

final int[][] array = new int[][] { { 5, 3, 6 }, { 1 } };

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

Please try with the below code snippet.

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.common.min.css" rel="stylesheet" />
    <link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.default.min.css" rel="stylesheet" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://cdn.kendostatic.com/2014.1.318/js/kendo.all.min.js"></script>
    <script>
        function onDataBound(e) {
            var grid = $("#grid").data("kendoGrid");
            $(grid.tbody).find('tr').removeClass('k-alt');
        }

        $(document).ready(function () {
            $("#grid").kendoGrid({
                dataSource: {
                    type: "odata",
                    transport: {
                        read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
                    },
                    schema: {
                        model: {
                            fields: {
                                OrderID: { type: "number" },
                                Freight: { type: "number" },
                                ShipName: { type: "string" },
                                OrderDate: { type: "date" },
                                ShipCity: { type: "string" }
                            }
                        }
                    },
                    pageSize: 20,
                    serverPaging: true,
                    serverFiltering: true,
                    serverSorting: true
                },
                height: 430,
                filterable: true,
                dataBound: onDataBound,
                sortable: true,
                pageable: true,
                columns: [{
                    field: "OrderID",
                    filterable: false
                },
                            "Freight",
                            {
                                field: "OrderDate",
                                title: "Order Date",
                                width: 120,
                                format: "{0:MM/dd/yyyy}"
                            }, {
                                field: "ShipName",
                                title: "Ship Name",
                                width: 260
                            }, {
                                field: "ShipCity",
                                title: "Ship City",
                                width: 150
                            }
                        ]
            });
        });
    </script>
</head>
<body>
    <div id="grid">
    </div>
</body>
</html>

I have implemented same thing with different way.

What does elementFormDefault do in XSD?

elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).

By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.

It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.

How do I add a user when I'm using Alpine as a base image?

The commands are adduser and addgroup.

Here's a template for Docker you can use in busybox environments (alpine) as well as Debian-based environments (Ubuntu, etc.):

ENV USER=docker
ENV UID=12345
ENV GID=23456

RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "$(pwd)" \
    --ingroup "$USER" \
    --no-create-home \
    --uid "$UID" \
    "$USER"

Note the following:

  • --disabled-password prevents prompt for a password
  • --gecos "" circumvents the prompt for "Full Name" etc. on Debian-based systems
  • --home "$(pwd)" sets the user's home to the WORKDIR. You may not want this.
  • --no-create-home prevents cruft getting copied into the directory from /etc/skel

The usage description for these applications is missing the long flags present in the code for adduser and addgroup.

The following long-form flags should work both in alpine as well as debian-derivatives:

adduser

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        --home DIR           Home directory
        --gecos GECOS        GECOS field
        --shell SHELL        Login shell
        --ingroup GRP        Group (by name)
        --system             Create a system user
        --disabled-password  Don't assign a password
        --no-create-home     Don't create home directory
        --uid UID            User id

One thing to note is that if --ingroup isn't set then the GID is assigned to match the UID. If the GID corresponding to the provided UID already exists adduser will fail.

addgroup

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.

Usage: addgroup [-g GID] [-S] [USER] GROUP

Add a group or add a user to a group

        --gid GID  Group id
        --system   Create a system group

I discovered all of this while trying to write my own alternative to the fixuid project for running containers as the hosts UID/GID.

My entrypoint helper script can be found on GitHub.

The intent is to prepend that script as the first argument to ENTRYPOINT which should cause Docker to infer UID and GID from a relevant bind mount.

An environment variable "TEMPLATE" may be required to determine where the permissions should be inferred from.

(At the time of writing I don't have documentation for my script. It's still on the todo list!!)

Environment Variable with Maven

You could wrap your maven command in a bash script:

#!/bin/bash

export YOUR_VAR=thevalue
mvn test
unset YOUR_VAR

How to find array / dictionary value using key?

It looks like you're writing PHP, in which case you want:

<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>

Notice that the ('us'=>'United', 'ca'=>'canada') needs to be a parameter to the array function in PHP.

Most programming languages that support associative arrays or dictionaries use arr['key'] to retrieve the item specified by 'key'

For instance:

Ruby

ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
 => {"us"=>"USA", "ca"=>"Canada"} 
ruby-1.9.1-p378 > h['ca']
 => "Canada" 

Python

>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'

C#

class P
{
    static void Main()
    {
        var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
        System.Console.WriteLine(d["ca"]);
    }
}

Lua

t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables

Vue JS mounted()

Abstract your initialization into a method, and call the method from mounted and wherever else you want.

new Vue({
  methods:{
    init(){
      //call API
      //Setup game
    }
  },
  mounted(){
    this.init()
  }
})

Then possibly have a button in your template to start over.

<button v-if="playerWon" @click="init">Play Again</button>

In this button, playerWon represents a boolean value in your data that you would set when the player wins the game so the button appears. You would set it back to false in init.

How to align iframe always in the center

If all you want to do is display an iframe on a page, the simplest solution I was able to come up with doesn't require divs or flex stuff is:

html {
    width: 100%;
    height: 100%;
    display: table;
}

body {
    text-align: center;
    vertical-align: middle;
    display: table-cell;
}

And then the HTML is just:

<html>
  <body>
     <iframe ...></iframe>
  </body>
</html>

If this is all you need you don't need wrapper divs to do it. This works for text content and stuff, too.

Fiddle.

Also this looks even simpler.