Programs & Examples On #Vertical text

ignoring any 'bin' directory on a git project

If you're looking for a great global .gitignore file for any Visual Studio ( .NET ) solution - I recommend you to use this one: https://github.com/github/gitignore/blob/master/VisualStudio.gitignore

AFAIK it has the most comprehensive .gitignore for .NET projects.

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

Strangely enough, I wrote some code to do this back when 1.1 came out (what was that, seven years ago?) and tweaked it a little when 2.0 came out. I haven't looked at it in years as we no longer manage our servers.

It's not foolproof, but I'm posting it anyway because I find it humorous; in that it's easier to do in .NET and easier still in power shell.

bool GetFileVersion(LPCTSTR filename,WORD *majorPart,WORD *minorPart,WORD *buildPart,WORD *privatePart)
{
    DWORD dwHandle;
    DWORD dwLen = GetFileVersionInfoSize(filename,&dwHandle);
    if (dwLen) {
        LPBYTE lpData = new BYTE[dwLen];
        if (lpData) {
            if (GetFileVersionInfo(filename,0,dwLen,lpData)) {
                UINT uLen;  
                VS_FIXEDFILEINFO *lpBuffer;  
                VerQueryValue(lpData,_T("\\"),(LPVOID*)&lpBuffer,&uLen);  
                *majorPart = HIWORD(lpBuffer->dwFileVersionMS);
                *minorPart = LOWORD(lpBuffer->dwFileVersionMS);
                *buildPart = HIWORD(lpBuffer->dwFileVersionLS);
                *privatePart = LOWORD(lpBuffer->dwFileVersionLS);
                delete[] lpData;
                return true;
            }
        }
    }
    return false;
}

int _tmain(int argc,_TCHAR* argv[])
{
    _TCHAR filename[MAX_PATH];
    _TCHAR frameworkroot[MAX_PATH];
    if (!GetEnvironmentVariable(_T("systemroot"),frameworkroot,MAX_PATH))
        return 1;
    _tcscat_s(frameworkroot,_T("\\Microsoft.NET\\Framework\\*"));
    WIN32_FIND_DATA FindFileData;
    HANDLE hFind = FindFirstFile(frameworkroot,&FindFileData);
    if (hFind == INVALID_HANDLE_VALUE)
        return 2;
    do {
        if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
            _tcslen(FindFileData.cAlternateFileName) != 0) {
            _tcsncpy_s(filename,frameworkroot,_tcslen(frameworkroot)-1);
            filename[_tcslen(frameworkroot)] = 0;
            _tcscat_s(filename,FindFileData.cFileName);
            _tcscat_s(filename,_T("\\mscorlib.dll"));
            WORD majorPart,minorPart,buildPart,privatePart;
            if (GetFileVersion(filename,&majorPart,&minorPart,&buildPart,&privatePart )) {
                _tprintf(_T("%d.%d.%d.%d\r\n"),majorPart,minorPart,buildPart,privatePart);
            }
        }
    } while (FindNextFile(hFind,&FindFileData) != 0);
    FindClose(hFind);
    return 0;
}

If Cell Starts with Text String... Formula

I'm not sure lookup is the right formula for this because of multiple arguments. Maybe hlookup or vlookup but these require you to have tables for values. A simple nested series of if does the trick for a small sample size

Try =IF(A1="a","pickup",IF(A1="b","collect",IF(A1="c","prepaid","")))

Now incorporate your left argument

=IF(LEFT(A1,1)="a","pickup",IF(LEFT(A1,1)="b","collect",IF(LEFT(A1,1)="c","prepaid","")))

Also note your usage of left, your argument doesn't specify the number of characters, but a set.


7/8/15 - Microsoft KB articles for the above mentioned functions. I don't think there's anything wrong with techonthenet, but I rather link to official sources.

How can I see the size of a GitHub repository before cloning it?

If you own the repository, you can find the exact size by opening your Account Settings ? Repositories (https://github.com/settings/repositories), and the repository size is displayed next to its designation.

If you do not own the repository, you can fork it and then check the in the same place.

Note: You might be the owner of the organization that hosts multiple repositories and yet not have a role in a specific repository inside the organization. By default, even if you create a repository in the organization you own, you are not added to the repo and hence not see that repo in settings/repositories. So add yourself in the repository Setting(https://github.com/org-name/repo-name/settings) to see it in https://github.com/settings/repositories

Somewhat hacky: use the download as a zip file option, read the file size indicated and then cancel it.

I do not remember if downloading as a zip ever worked, but in any case, doing so now only downloads the currently selected branch with no history.

Remove Top Line of Text File with PowerShell

Inspired by AASoft's answer, I went out to improve it a bit more:

  1. Avoid the loop variable $i and the comparison with 0 in every loop
  2. Wrap the execution into a try..finally block to always close the files in use
  3. Make the solution work for an arbitrary number of lines to remove from the beginning of the file
  4. Use a variable $p to reference the current directory

These changes lead to the following code:

$p = (Get-Location).Path

(Measure-Command {
    # Number of lines to skip
    $skip = 1
    $ins = New-Object System.IO.StreamReader ($p + "\test.log")
    $outs = New-Object System.IO.StreamWriter ($p + "\test-1.log")
    try {
        # Skip the first N lines, but allow for fewer than N, as well
        for( $s = 1; $s -le $skip -and !$ins.EndOfStream; $s++ ) {
            $ins.ReadLine()
        }
        while( !$ins.EndOfStream ) {
            $outs.WriteLine( $ins.ReadLine() )
        }
    }
    finally {
        $outs.Close()
        $ins.Close()
    }
}).TotalSeconds

The first change brought the processing time for my 60 MB file down from 5.3s to 4s. The rest of the changes is more cosmetic.

C# Inserting Data from a form into an access Database

My Code to insert data is not working. It showing no error but data is not showing in my database.

public partial class Form1 : Form { OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString); public Form1() { InitializeComponent(); }

    private void Form1_Load(object sender, EventArgs e)
    {
        
    }

    private void btn_add_Click(object sender, EventArgs e)
    {
        OleDbDataAdapter items = new OleDbDataAdapter();
        connection.Open();
        OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName,  SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
        command.CommandType = CommandType.Text;
        command.ExecuteReader();
        connection.Close();
        MessageBox.Show("Insertd!");
    }
}

Replace string within file contents

Something like

file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')

<do stuff with the result>

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

In your Project open Global.asax.cs then right click on Method RouteConfig.RegisterRoutes(RouteTable.Routes); then click Go To Definition then at defaults: new { controller = "Home", action = "Index", id =UrlParameter.Optional} then change then Names of "Home" to your own controller Name and Index to your own View Name if you have changed the Names other then "HomeController" and "Index" Hope your Problem will be Solved.

IF Statement multiple conditions, same statement

Pretty old question but check this for a more clustered way of checking conditions:

private bool IsColumn(string col, params string[] names) => names.Any(n => n == col);

usage:

private void CheckColumn()
{
     if(!IsColumn(ColName, "Column A", "Column B", "Column C"))
    {
     //not A B C column
    }

}

Key Shortcut for Eclipse Imports

Some useful shortcuts. You're looking for the 1st one...

  1. Ctrl + Shift + O : Organize imports
  2. Ctrl + Shift + T : Open Type
  3. Ctrl + Shift + F4 : Close all Opened Editors
  4. Ctrl + O : Open declarations
  5. Ctrl + E : Open Editor
  6. Ctrl + / : Line Comment
  7. Alt + Shift + R : Rename
  8. Alt + Shift + L : extract to Local Variable
  9. Alt + Shift + M : extract to Method
  10. F3 : Open Declaration

Source Here

MySQL "WITH" clause

Building on the answer from @Mosty Mostacho, here's how you might do something equivalent in MySQL,for a specific case of determining what entries don't exist in a table, and are not in any other database.

select col1 from (
   select 'value1' as col1 union
   select 'value2' as col1 union
   select 'value3' as col1
) as subquery
left join mytable as mytable.mycol = col1
where mytable.mycol is null
order by col1

You may want to use a text editor with macro capabilities to convert a list of values to the quoted select union clause.

Repository Pattern Step by Step Explanation

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

jQuery iframe load() event?

use iframe onload event

$('#theiframe').on("load", function() {
    alert(1);
});

Print multiple arguments in Python

Use f-string:

print(f'Total score for {name} is {score}')

Or

Use .format:

print("Total score for {} is {}".format(name, score))

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

In case it helps others, I got this error when the service the task was running at didn't have write permission to the executable location. It was attempting to write a log file there.

How do I parse a HTML page with Node.js

Htmlparser2 by FB55 seems to be a good alternative.

How do I perform a Perl substitution on a string while keeping the original?

The statement:

(my $newstring = $oldstring) =~ s/foo/bar/g;

Which is equivalent to:

my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;

Alternatively, as of Perl 5.13.2 you can use /r to do a non destructive substitution:

use 5.013;
#...
my $newstring = $oldstring =~ s/foo/bar/gr;

Error when deploying an artifact in Nexus

I had the same problem today with the addition "Return code is: 400, ReasonPhrase: Bad Request." which turned out to be the "artifact is already deployed with that version if it is a release" problem from answer above enter link description here

One solution not mentioned yet is to configure Nexus to allow redeployment into a Release repository. Maybe not a best practice, because this is set for a reason, you nevertheless could go to "Access Settings" in your Nexus repositories´ "Configuration"-Tab and set the "Deployment Policy" to "Allow Redeploy".

Random number between 0 and 1 in python

RTM

From the docs for the Python random module:

Functions for integers:

random.randrange(stop)
random.randrange(start, stop[, step])

    Return a randomly selected element from range(start, stop, step).
    This is equivalent to choice(range(start, stop, step)), but doesn’t
    actually build a range object.

That explains why it only gives you 0, doesn't it. range(0,1) is [0]. It is choosing from a list consisting of only that value.

Also from those docs:

random.random()    
    Return the next random floating point number in the range [0.0, 1.0).

But if your inclusion of the numpy tag is intentional, you can generate many random floats in that range with one call using a np.random function.

How to pass command line arguments to a rake task

Actually @Nick Desjardins answered perfect. But just for education: you can use dirty approach: using ENV argument

task :my_task do
  myvar = ENV['myvar']
  puts "myvar: #{myvar}"
end 

rake my_task myvar=10
#=> myvar: 10

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

Select where count of one field is greater than one

Here you go:

SELECT Field1, COUNT(Field1)
  FROM Table1 
 GROUP BY Field1
HAVING COUNT(Field1) > 1
ORDER BY Field1 desc

.NET DateTime to SqlDateTime Conversion

-To compare only the date part, you can do:

var result = db.query($"SELECT * FROM table WHERE date >= '{fromDate.ToString("yyyy-MM-dd")}' and date <= '{toDate.ToString("yyyy-MM-dd"}'");

Prevent scroll-bar from adding-up to the Width of page on Chrome

body {
    width: calc( 100% );
    max-width: calc( 100vw - 1em );
}

works with default scroll bars as well. could add:

overflow-x: hidden;

to ensure horizontal scroll bars remain hidden for the parent frame. unless this is desired from your clients.

What are the date formats available in SimpleDateFormat class?

Date and time formats are well described below

SimpleDateFormat (Java Platform SE 7) - Date and Time Patterns

There could be n Number of formats you can possibly make. ex - dd/MM/yyyy or YYYY-'W'ww-u or you can mix and match the letters to achieve your required pattern. Pattern letters are as follow.

  • G - Era designator (AD)
  • y - Year (1996; 96)
  • Y - Week Year (2009; 09)
  • M - Month in year (July; Jul; 07)
  • w - Week in year (27)
  • W - Week in month (2)
  • D - Day in year (189)
  • d - Day in month (10)
  • F - Day of week in month (2)
  • E - Day name in week (Tuesday; Tue)
  • u - Day number of week (1 = Monday, ..., 7 = Sunday)
  • a - AM/PM marker
  • H - Hour in day (0-23)
  • k - Hour in day (1-24)
  • K - Hour in am/pm (0-11)
  • h - Hour in am/pm (1-12)
  • m - Minute in hour (30)
  • s - Second in minute (55)
  • S - Millisecond (978)
  • z - General time zone (Pacific Standard Time; PST; GMT-08:00)
  • Z - RFC 822 time zone (-0800)
  • X - ISO 8601 time zone (-08; -0800; -08:00)

To parse:

2000-01-23T04:56:07.000+0000

Use: new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

How to delete columns in pyspark dataframe

Consider 2 dataFrames:

>>> aDF.show()
+---+----+
| id|datA|
+---+----+
|  1|  a1|
|  2|  a2|
|  3|  a3|
+---+----+

and

>>> bDF.show()
+---+----+
| id|datB|
+---+----+
|  2|  b2|
|  3|  b3|
|  4|  b4|
+---+----+

To accomplish what you are looking for, there are 2 ways:

1. Different joining condition. Instead of saying aDF.id == bDF.id

aDF.join(bDF, aDF.id == bDF.id, "outer")

Write this:

aDF.join(bDF, "id", "outer").show()
+---+----+----+
| id|datA|datB|
+---+----+----+
|  1|  a1|null|
|  3|  a3|  b3|
|  2|  a2|  b2|
|  4|null|  b4|
+---+----+----+

This will automatically get rid of the extra the dropping process.

2. Use Aliasing: You will lose data related to B Specific Id's in this.

>>> from pyspark.sql.functions import col
>>> aDF.alias("a").join(bDF.alias("b"), aDF.id == bDF.id, "outer").drop(col("b.id")).show()

+----+----+----+
|  id|datA|datB|
+----+----+----+
|   1|  a1|null|
|   3|  a3|  b3|
|   2|  a2|  b2|
|null|null|  b4|
+----+----+----+

How do I combine two data-frames based on two columns?

You can also use the join command (dplyr).

For example:

new_dataset <- dataset1 %>% right_join(dataset2, by=c("column1","column2"))

HashMap get/put complexity

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

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

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

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

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

How to remove error about glyphicons-halflings-regular.woff2 not found

I tried all the suggestions above, but my actual issue was that my application was looking for the /font folder and its contents (.woff etc) in app/fonts, but my /fonts folder was on the same level as /app. I moved /fonts under /app, and it works fine now. I hope this helps someone else roaming the web for an answer.

How do you change text to bold in Android?

In my case, Passing value through string.xml worked out with html Tag..

<string name="your_string_tag"> <b> your_text </b></string>

How do I generate a random integer between min and max in Java?

As the solutions above do not consider the possible overflow of doing max-min when min is negative, here another solution (similar to the one of kerouac)

public static int getRandom(int min, int max) {
    if (min > max) {
        throw new IllegalArgumentException("Min " + min + " greater than max " + max);
    }      
    return (int) ( (long) min + Math.random() * ((long)max - min + 1));
}

this works even if you call it with:

getRandom(Integer.MIN_VALUE, Integer.MAX_VALUE) 

How to install latest version of openssl Mac OS X El Capitan

Try creating a symlink, make sure you have openssl installed in /usr/local/include first.

ln -s /usr/local/Cellar/openssl/{version}/include/openssl /usr/local/include/openssl

More info at Openssl with El Capitan.

How to convert a file into a dictionary?

Simple Option

Most methods for storing a dictionary use JSON, Pickle, or line reading. Providing you're not editing the dictionary outside of Python, this simple method should suffice for even complex dictionaries. Although Pickle will be better for larger dictionaries.

x = {1:'a', 2:'b', 3:'c'}
f = 'file.txt'
print(x, file=open(f,'w'))    # file.txt >>> {1:'a', 2:'b', 3:'c'}
y = eval(open(f,'r').read())
print(x==y)                   # >>> True

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

Make sure to invoke done(); on callbacks or it simply won't pass the test.

beforeAll((done /* Call it or remove it */ ) => {
  done(); // Calling it
});

It applies to all other functions that have a done() callback.

Difference between ${} and $() in Bash

The syntax is token-level, so the meaning of the dollar sign depends on the token it's in. The expression $(command) is a modern synonym for `command` which stands for command substitution; it means run command and put its output here. So

echo "Today is $(date). A fine day."

will run the date command and include its output in the argument to echo. The parentheses are unrelated to the syntax for running a command in a subshell, although they have something in common (the command substitution also runs in a separate subshell).

By contrast, ${variable} is just a disambiguation mechanism, so you can say ${var}text when you mean the contents of the variable var, followed by text (as opposed to $vartext which means the contents of the variable vartext).

The while loop expects a single argument which should evaluate to true or false (or actually multiple, where the last one's truth value is examined -- thanks Jonathan Leffler for pointing this out); when it's false, the loop is no longer executed. The for loop iterates over a list of items and binds each to a loop variable in turn; the syntax you refer to is one (rather generalized) way to express a loop over a range of arithmetic values.

A for loop like that can be rephrased as a while loop. The expression

for ((init; check; step)); do
    body
done

is equivalent to

init
while check; do
    body
    step
done

It makes sense to keep all the loop control in one place for legibility; but as you can see when it's expressed like this, the for loop does quite a bit more than the while loop.

Of course, this syntax is Bash-specific; classic Bourne shell only has

for variable in token1 token2 ...; do

(Somewhat more elegantly, you could avoid the echo in the first example as long as you are sure that your argument string doesn't contain any % format codes:

date +'Today is %c. A fine day.'

Avoiding a process where you can is an important consideration, even though it doesn't make a lot of difference in this isolated example.)

Git Server Like GitHub?

In the meantime, the Mercurial hosting site Bitbucket has started to offer Git repositories as well.

So if you don't need a local server, just some central place where you can host private Git repositories for free, IMO Bitbucket is the best choice.

For free, you get unlimited private and public Git and Mercurial repositories.
The only limitation is that in the free plan, no more than five users can access your private repositories (for more, you have to pay).
See https://bitbucket.org/plans for more info!

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

There are two storage areas involved: the stack and the heap.The stack is where the current state of a method call is kept (ie local variables and references), and the heap is where objects are stored. recursion and memory

I gues there are too many keys in the counter dict that will consume too much memory of the heap region, so the Python runtime will raise a OutOfMemory exception.

To save it, don't create a giant object, e.g. the counter.

1.StackOverflow

a program that create too many local variables.

Python 2.7.9 (default, Mar  1 2015, 12:57:24) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('stack_overflow.py','w')
>>> f.write('def foo():\n')
>>> for x in xrange(10000000):
...   f.write('\tx%d = %d\n' % (x, x))
... 
>>> f.write('foo()')
>>> f.close()
>>> execfile('stack_overflow.py')
Killed

2.OutOfMemory

a program that creats a giant dict includes too many keys.

>>> f = open('out_of_memory.py','w')
>>> f.write('def foo():\n')
>>> f.write('\tcounter = {}\n')
>>> for x in xrange(10000000):
...   f.write('counter[%d] = %d\n' % (x, x))
... 
>>> f.write('foo()\n')
>>> f.close()
>>> execfile('out_of_memory.py')
Killed

References

How to compute the sum and average of elements in an array?

A solution I consider more elegant:

const sum = times.reduce((a, b) => a + b, 0);
const avg = (sum / times.length) || 0;

console.log(`The sum is: ${sum}. The average is: ${avg}.`);

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

In my case File > Setting > Kotlin Compiler > Target JVM Version > 1.8

DbEntityValidationException - How can I easily tell what caused the error?

Use try block in your code like

try
{
    // Your code...
    // Could also be before try if you know the exception occurs in SaveChanges

    context.SaveChanges();
}
catch (DbEntityValidationException e)
{
    foreach (var eve in e.EntityValidationErrors)
    {
        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
        {
            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
        }
    }
    throw;
}

You can check the details here as well

  1. http://mattrandle.me/viewing-entityvalidationerrors-in-visual-studio/

  2. Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

  3. http://blogs.infosupport.com/improving-dbentityvalidationexception/

Set HTML dropdown selected option using JSTL

Real simple. You just need to have the string 'selected' added to the right option. In the following code, ${myBean.foo == val ? 'selected' : ' '} will add the string 'selected' if the option's value is the same as the bean value;

<select name="foo" id="foo" value="${myBean.foo}">
    <option value="">ALL</option>
    <c:forEach items="${fooList}" var="val"> 
        <option value="${val}" ${myBean.foo == val ? 'selected' : ' '}><c:out value="${val}" ></c:out></option>   
    </c:forEach>                     
</select>

How to set Oracle's Java as the default Java in Ubuntu?

java 6

export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-amd64

or java 7

export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-amd64

How do I access my webcam in Python?

import cv2 as cv

capture = cv.VideoCapture(0)

while True:
    isTrue,frame = capture.read()
    cv.imshow('Video',frame)
    if cv.waitKey(20) & 0xFF==ord('d'):
        break

capture.release()
cv.destroyAllWindows()

0 <-- refers to the camera , replace it with file path to read a video file

cv.waitKey(20) & 0xFF==ord('d') <-- to destroy window when key is pressed

Passing parameters to a Bash function

If you prefer named parameters, it's possible (with a few tricks) to actually pass named parameters to functions (also makes it possible to pass arrays and references).

The method I developed allows you to define named parameters passed to a function like this:

function example { args : string firstName , string lastName , integer age } {
  echo "My name is ${firstName} ${lastName} and I am ${age} years old."
}

You can also annotate arguments as @required or @readonly, create ...rest arguments, create arrays from sequential arguments (using e.g. string[4]) and optionally list the arguments in multiple lines:

function example {
  args
    : @required string firstName
    : string lastName
    : integer age
    : string[] ...favoriteHobbies

  echo "My name is ${firstName} ${lastName} and I am ${age} years old."
  echo "My favorite hobbies include: ${favoriteHobbies[*]}"
}

In other words, not only you can call your parameters by their names (which makes up for a more readable core), you can actually pass arrays (and references to variables - this feature works only in Bash 4.3 though)! Plus, the mapped variables are all in the local scope, just as $1 (and others).

The code that makes this work is pretty light and works both in Bash 3 and Bash 4 (these are the only versions I've tested it with). If you're interested in more tricks like this that make developing with bash much nicer and easier, you can take a look at my Bash Infinity Framework, the code below is available as one of its functionalities.

shopt -s expand_aliases

function assignTrap {
  local evalString
  local -i paramIndex=${__paramIndex-0}
  local initialCommand="${1-}"

  if [[ "$initialCommand" != ":" ]]
  then
    echo "trap - DEBUG; eval \"${__previousTrap}\"; unset __previousTrap; unset __paramIndex;"
    return
  fi

  while [[ "${1-}" == "," || "${1-}" == "${initialCommand}" ]] || [[ "${#@}" -gt 0 && "$paramIndex" -eq 0 ]]
  do
    shift # First colon ":" or next parameter's comma ","
    paramIndex+=1
    local -a decorators=()
    while [[ "${1-}" == "@"* ]]
    do
      decorators+=( "$1" )
      shift
    done

    local declaration=
    local wrapLeft='"'
    local wrapRight='"'
    local nextType="$1"
    local length=1

    case ${nextType} in
      string | boolean) declaration="local " ;;
      integer) declaration="local -i" ;;
      reference) declaration="local -n" ;;
      arrayDeclaration) declaration="local -a"; wrapLeft= ; wrapRight= ;;
      assocDeclaration) declaration="local -A"; wrapLeft= ; wrapRight= ;;
      "string["*"]") declaration="local -a"; length="${nextType//[a-z\[\]]}" ;;
      "integer["*"]") declaration="local -ai"; length="${nextType//[a-z\[\]]}" ;;
    esac

    if [[ "${declaration}" != "" ]]
    then
      shift
      local nextName="$1"

      for decorator in "${decorators[@]}"
      do
        case ${decorator} in
          @readonly) declaration+="r" ;;
          @required) evalString+="[[ ! -z \$${paramIndex} ]] || echo \"Parameter '$nextName' ($nextType) is marked as required by '${FUNCNAME[1]}' function.\"; " >&2 ;;
          @global) declaration+="g" ;;
        esac
      done

      local paramRange="$paramIndex"

      if [[ -z "$length" ]]
      then
        # ...rest
        paramRange="{@:$paramIndex}"
        # trim leading ...
        nextName="${nextName//\./}"
        if [[ "${#@}" -gt 1 ]]
        then
          echo "Unexpected arguments after a rest array ($nextName) in '${FUNCNAME[1]}' function." >&2
        fi
      elif [[ "$length" -gt 1 ]]
      then
        paramRange="{@:$paramIndex:$length}"
        paramIndex+=$((length - 1))
      fi

      evalString+="${declaration} ${nextName}=${wrapLeft}\$${paramRange}${wrapRight}; "

      # Continue to the next parameter:
      shift
    fi
  done
  echo "${evalString} local -i __paramIndex=${paramIndex};"
}

alias args='local __previousTrap=$(trap -p DEBUG); trap "eval \"\$(assignTrap \$BASH_COMMAND)\";" DEBUG;'

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

It seems that Maven doesn't like the JAVA_HOME variable to have more than one value. In my case, the error was due to the presence of the additional path C:\Program Files\Java\jax-rs (the whole path was C:\Program Files\Java\jdk1.8.0_20;C:\Program Files\Java\jax-rs).

So I deleted the JAVA_HOME variable and re-created it again with the single value C:\Program Files\Java\jdk1.8.0_20.

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

Use the .scrollHeight property of the DOM node: $('#your_div')[0].scrollHeight

How to write and read a file with a HashMap?

The simplest solution that I can think of is using Properties class.

Saving the map:

Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();

for (Map.Entry<String,String> entry : ldapContent.entrySet()) {
    properties.put(entry.getKey(), entry.getValue());
}

properties.store(new FileOutputStream("data.properties"), null);

Loading the map:

Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(new FileInputStream("data.properties"));

for (String key : properties.stringPropertyNames()) {
   ldapContent.put(key, properties.get(key).toString());
}

EDIT:

if your map contains plaintext values, they will be visible if you open file data via any text editor, which is not the case if you serialize the map:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(ldapContent);
out.close();

EDIT2:

instead of for loop (as suggested by OldCurmudgeon) in saving example:

properties.putAll(ldapContent);

however, for the loading example this is the best that can be done:

ldapContent = new HashMap<Object, Object>(properties);

Convert to absolute value in Objective-C

Depending on the type of your variable, one of abs(int), labs(long), llabs(long long), imaxabs(intmax_t), fabsf(float), fabs(double), or fabsl(long double).

Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)

(Alas, there is no habs(short) function. Or scabs(signed char) for that matter...)


Apple's and GNU's Objective-C headers also include an ABS() macro which is type-agnostic. I don't recommend using ABS() however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++) will have an undefined result.


If you're using C++ or Objective-C++, you can bring in the <cmath> header and use std::abs(), which is templated for all the standard integer and floating-point types.

Initializing a two dimensional std::vector

There is no append method in std::vector, but if you want to make a vector containing A_NUMBER vectors of int, each of those containing other_number zeros, then you can do this:

std::vector<std::vector<int>> fog(A_NUMBER, std::vector<int>(OTHER_NUMBER));

How to implement Android Pull-to-Refresh

I've written a pull to refresh component here: https://github.com/guillep/PullToRefresh It works event if the list does not have items, and I've tested it on >=1.6 android phones.

Any suggestion or improvement is appreciated :)

POST Multipart Form Data using Retrofit 2.0 including image

There is a correct way of uploading a file with its name with Retrofit 2, without any hack:

Define API interface:

@Multipart
@POST("uploadAttachment")
Call<MyResponse> uploadAttachment(@Part MultipartBody.Part filePart); 
                                   // You can add other parameters too

Upload file like this:

File file = // initialize file here

MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));

Call<MyResponse> call = api.uploadAttachment(filePart);

This demonstrates only file uploading, you can also add other parameters in the same method with @Part annotation.

How do I see if Wi-Fi is connected on Android?

The following code (in Kotlin) works from API 21 until at least current API version (API 29). The function getWifiState() returns one of 3 possible values for the WiFi network state: Disable, EnabledNotConnected and Connected that were defined in an enum class. This allows to take more granular decisions like informing the user to enable WiFi or, if already enabled, to connect to one of the available networks. But if all that is needed is a boolean indicating if the WiFi interface is connected to a network, then the other function isWifiConnected() will give you that. It uses the previous one and compares the result to Connected.

It's inspired in some of the previous answers but trying to solve the problems introduced by the evolution of Android API's or the slowly increasing availability of IP V6. The trick was to use:

wifiManager.connectionInfo.bssid != null 

instead of:

  1. getIpAddress() == 0 that is only valid for IP V4 or
  2. getNetworkId() == -1 that now requires another special permission (Location)

According to the documentation: https://developer.android.com/reference/kotlin/android/net/wifi/WifiInfo.html#getbssid it will return null if not connected to a network. And even if we do not have permission to get the real value, it will still return something other than null if we are connected.

Also have the following in mind:

On releases before android.os.Build.VERSION_CODES#N, this object should only be obtained from an Context#getApplicationContext(), and not from any other derived context to avoid memory leaks within the calling process.

In the Manifest, do not forget to add:

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

Proposed code is:

class MyViewModel(application: Application) : AndroidViewModel(application) {

   // Get application context
    private val myAppContext: Context = getApplication<Application>().applicationContext

   // Define the different possible states for the WiFi Connection
    internal enum class WifiState {
        Disabled,               // WiFi is not enabled
        EnabledNotConnected,    // WiFi is enabled but we are not connected to any WiFi network
        Connected,              // Connected to a WiFi network
    }

    // Get the current state of the WiFi network
    private fun getWifiState() : WifiState {

        val wifiManager : WifiManager = myAppContext.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

        return if (wifiManager.isWifiEnabled) {
                    if (wifiManager.connectionInfo.bssid != null)
                        WifiState.Connected
                    else
                        WifiState.EnabledNotConnected
               } else {
                    WifiState.Disabled
               }
    }

    // Returns true if we are connected to a WiFi network
    private fun isWiFiConnected() : Boolean {
        return (getWifiState() == WifiState.Connected)
    }
}

How to find reason of failed Build without any error or warning

I had the same issue, I changed Tools -> Options -> Projects and Solutions/Build and Run -> MSBuild project build log file verbosity[Diagnostic]. This option shows error in log, due to some reasons my VS not showing Error in Errors tab!

enter image description here

Do above settings and in output copy in notepad/texteditor and search for error. It will show you all errors.

Append values to query string

I like Bjorn's answer, however the solution he's provided is misleading, as the method updates an existing parameter, rather than adding it if it doesn't exist.. To make it a bit safer, I've adapted it below.

public static class UriExtensions
{
    /// <summary>
    /// Adds or Updates the specified parameter to the Query String.
    /// </summary>
    /// <param name="url"></param>
    /// <param name="paramName">Name of the parameter to add.</param>
    /// <param name="paramValue">Value for the parameter to add.</param>
    /// <returns>Url with added parameter.</returns>
    public static Uri AddOrUpdateParameter(this Uri url, string paramName, string paramValue)
    {
        var uriBuilder = new UriBuilder(url);
        var query = HttpUtility.ParseQueryString(uriBuilder.Query);

        if (query.AllKeys.Contains(paramName))
        {
            query[paramName] = paramValue;
        }
        else
        {
            query.Add(paramName, paramValue);
        }
        uriBuilder.Query = query.ToString();

        return uriBuilder.Uri;
    }
}

Regular expression negative lookahead

If you revise your regular expression like this:

drupal-6.14/(?=sites(?!/all|/default)).*
             ^^

...then it will match all inputs that contain drupal-6.14/ followed by sites followed by anything other than /all or /default. For example:

drupal-6.14/sites/foo
drupal-6.14/sites/bar
drupal-6.14/sitesfoo42
drupal-6.14/sitesall

Changing ?= to ?! to match your original regex simply negates those matches:

drupal-6.14/(?!sites(?!/all|/default)).*
             ^^

So, this simply means that drupal-6.14/ now cannot be followed by sites followed by anything other than /all or /default. So now, these inputs will satisfy the regex:

drupal-6.14/sites/all
drupal-6.14/sites/default
drupal-6.14/sites/all42

But, what may not be obvious from some of the other answers (and possibly your question) is that your regex will also permit other inputs where drupal-6.14/ is followed by anything other than sites as well. For example:

drupal-6.14/foo
drupal-6.14/xsites

Conclusion: So, your regex basically says to include all subdirectories of drupal-6.14 except those subdirectories of sites whose name begins with anything other than all or default.

Detect if user is scrolling

You just said javascript in your tags, so @Wampie Driessen post could helps you.

I want also to contribute, so you can use the following when using jQuery if you need it.

 //Firefox
 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.detail > 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

 //IE, Opera, Safari
 $('#elem').bind('mousewheel', function(e){
     if(e.wheelDelta< 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

Another example:

$(function(){
    var _top = $(window).scrollTop();
    var _direction;
    $(window).scroll(function(){
        var _cur_top = $(window).scrollTop();
        if(_top < _cur_top)
        {
            _direction = 'down';
        }
        else
        {
            _direction = 'up';
        }
        _top = _cur_top;
        console.log(_direction);
    });
});?

Difference between a SOAP message and a WSDL?

We need to define what is a web service before telling what are the difference between the SOAP and WSDL where the two (SOAP and WSDL) are components of a web service

Most applications are developed to interact with users, the user enters or searches for data through an interface and the application then responds to the user's input.

A Web service does more or less the same thing except that a Web service application communicates only from machine to machine or application to application. There is often no direct user interaction.

A Web service basically is a collection of open protocols that is used to exchange data between applications. The use of open protocols enables Web services to be platform independent. Software that are written in different programming languages and that run on different platforms can use Web services to exchange data over computer networks such as the Internet. In other words, Windows applications can talk to PHP, Java and Perl applications and many others, which in normal circumstances would not be possible.

How Do Web Services Work?

Because different applications are written in different programming languages, they often cannot communicate with each other. A Web service enables this communication by using a combination of open protocols and standards, chiefly XML, SOAP and WSDL. A Web service uses XML to tag data, SOAP to transfer a message and finally WSDL to describe the availability of services. Let's take a look at these three main components of a Web service application.

Simple Object Access Protocol (SOAP)

The Simple Object Access Protocol or SOAP is a protocol for sending and receiving messages between applications without confronting interoperability issues (interoperability meaning the platform that a Web service is running on becomes irrelevant). Another protocol that has a similar function is HTTP. It is used to access Web pages or to surf the Net. HTTP ensures that you do not have to worry about what kind of Web server -- whether Apache or IIS or any other -- serves you the pages you are viewing or whether the pages you view were created in ASP.NET or HTML.

Because SOAP is used both for requesting and responding, its contents vary slightly depending on its purpose.

Below is an example of a SOAP request and response message

SOAP Request:

POST /InStock HTTP/1.1 
Host: www.bookshop.org 
Content-Type: application/soap+xml; charset=utf-8 
Content-Length: nnn 
<?xml version="1.0"?> 
<soap:Envelope 
xmlns:soap="http://www.w3.org/2001/12/soap-envelope" 
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> 
<soap:Body xmlns:m="http://www.bookshop.org/prices"> 
    <m:GetBookPrice> 
    <m:BookName>The Fleamarket</m:BookName> 
    </m:GetBookPrice> 
</soap:Body> 
</soap:Envelope>

SOAP Response:

POST /InStock HTTP/1.1 
Host: www.bookshop.org 
Content-Type: application/soap+xml; charset=utf-8 
Content-Length: nnn 
<?xml version="1.0"?> 
<soap:Envelope 
xmlns:soap="http://www.w3.org/2001/12/soap-envelope" 
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> 
<soap:Body xmlns:m="http://www.bookshop.org/prices"> 
    <m:GetBookPriceResponse> 
    <m: Price>10.95</m: Price> 
    </m:GetBookPriceResponse> 
</soap:Body> 
</soap:Envelope> 

Although both messages look the same, they carry out different methods. For instance looking at the above examples you can see that the requesting message uses the GetBookPrice method to get the book price. The response is carried out by the GetBookPriceResponse method, which is going to be the message that you as the "requestor" will see. You can also see that the messages are composed using XML.

Web Services Description Language or WSDL

WSDL is a document that describes a Web service and also tells you how to access and use its methods.

WSDL takes care of how do you know what methods are available in a Web service that you stumble across on the Internet.

Take a look at a sample WSDL file:

<?xml version="1.0" encoding="UTF-8"?> 
<definitions  name ="DayOfWeek"  
  targetNamespace="http://www.roguewave.com/soapworx/examples/DayOfWeek.wsdl" 
  xmlns:tns="http://www.roguewave.com/soapworx/examples/DayOfWeek.wsdl" 
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"  
  xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns="http://schemas.xmlsoap.org/wsdl/">  
  <message name="DayOfWeekInput"> 
    <part name="date" type="xsd:date"/> 
  </message> 
  <message name="DayOfWeekResponse"> 
    <part name="dayOfWeek" type="xsd:string"/> 
  </message> 
  <portType name="DayOfWeekPortType"> 
    <operation name="GetDayOfWeek"> 
      <input message="tns:DayOfWeekInput"/> 
      <output message="tns:DayOfWeekResponse"/> 
    </operation> 
  </portType> 
  <binding name="DayOfWeekBinding" type="tns:DayOfWeekPortType"> 
    <soap:binding style="document"  
      transport="http://schemas.xmlsoap.org/soap/http"/> 
    <operation name="GetDayOfWeek"> 
      <soap:operation soapAction="getdayofweek"/> 
      <input> 
        <soap:body use="encoded"  
          namespace="http://www.roguewave.com/soapworx/examples"  
          encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> 
      </input> 
      <output> 
        <soap:body use="encoded"  
          namespace="http://www.roguewave.com/soapworx/examples"   
            encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> 
      </output> 
    </operation> 
  </binding> 
  <service name="DayOfWeekService" > 
    <documentation> 
      Returns the day-of-week name for a given date 
    </documentation> 
    <port name="DayOfWeekPort" binding="tns:DayOfWeekBinding"> 
      <soap:address location="http://localhost:8090/dayofweek/DayOfWeek"/> 
    </port> 
  </service> 
</definitions> 

The main things to remember about a WSDL file are that it provides you with:

  • A description of a Web service

  • The methods a Web service uses and the parameters that it takes

  • A way to locate Web services

  • Inner join with count() on three tables

    One needs to understand what a JOIN or a series of JOINs does to a set of data. With strae's post, a pe_id of 1 joined with corresponding order and items on pe_id = 1 will give you the following data to "select" from:

    [ table people portion ] [ table orders portion ] [ table items portion ]

    | people.pe_id | people.pe_name | orders.ord_id | orders.pe_id | orders.ord_title | item.item_id | item.ord_id | item.pe_id | item.title |

    | 1 | Foo | 1 | 1 | First order | 1 | 1 | 1 | Apple |
    | 1 | Foo | 1 | 1 | First order | 2 | 1 | 1 | Pear |

    The joins essentially come up with a cartesian product of all the tables. You basically have that data set to select from and that's why you need a distinct count on orders.ord_id and items.item_id. Otherwise both counts will result in 2 - because you effectively have 2 rows to select from.

    How can I switch language in google play?

    Answer below the dotted line below is the original that's now outdated.

    Here is the latest information ( Thank you @deadfish ):

    add &hl=<language> like &hl=pl or &hl=en

    example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

    All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

    ......................................................................

    To change the actual local market:

    Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

    To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

    Changing WPF title bar background color

    Here's an example on how to achieve this:

        <Grid DockPanel.Dock="Right"
          HorizontalAlignment="Right">
    
            <StackPanel Orientation="Horizontal"
                    HorizontalAlignment="Right"
                    VerticalAlignment="Center">
    
                <Button x:Name="MinimizeButton"
                    KeyboardNavigation.IsTabStop="False"
                    Click="MinimizeWindow"
                    Style="{StaticResource MinimizeButton}" 
                    Template="{StaticResource MinimizeButtonControlTemplate}" />
    
                <Button x:Name="MaximizeButton"
                    KeyboardNavigation.IsTabStop="False"
                    Click="MaximizeClick"
                    Style="{DynamicResource MaximizeButton}" 
                    Template="{DynamicResource MaximizeButtonControlTemplate}" />
    
                <Button x:Name="CloseButton"
                    KeyboardNavigation.IsTabStop="False"
                    Command="{Binding ApplicationCommands.Close}"
                    Style="{DynamicResource CloseButton}" 
                    Template="{DynamicResource CloseButtonControlTemplate}"/>
    
            </StackPanel>
        </Grid>
    </DockPanel>
    

    Handle Click Events in the code-behind.

    For MouseDown -

    App.Current.MainWindow.DragMove();
    

    For Minimize Button -

    App.Current.MainWindow.WindowState = WindowState.Minimized;
    

    For DoubleClick and MaximizeClick

    if (App.Current.MainWindow.WindowState == WindowState.Maximized)
    {
        App.Current.MainWindow.WindowState = WindowState.Normal;
    }
    else if (App.Current.MainWindow.WindowState == WindowState.Normal)
    {
        App.Current.MainWindow.WindowState = WindowState.Maximized;
    }
    

    Draw a connecting line between two elements

    Recently, I have tried to develop a simple web app that uses drag and drop components and has lines connecting them. I came across these two simple and amazing javascript libraries:

    1. Plain Draggable: simple and high performance library to allow HTML/SVG element to be dragged.
    2. Leader Line: Draw a leader line in your web page

    Working example link (usage: click on add scene to create a draggable, click on add choice to draw a leader line between two different draggables)

    What's the difference between a temp table and table variable in SQL Server?

    It surprises me that no one mentioned the key difference between these two is that the temp table supports parallel insert while the table variable doesn't. You should be able to see the difference from the execution plan. And here is the video from SQL Workshops on Channel 9.

    This also explains why you should use a table variable for smaller tables, otherwise use a temp table, as SQLMenace answered before.

    How does Google reCAPTCHA v2 work behind the scenes?

    This is speculation, but based on Google's reference to the "risk analysis engine" they use (http://googleonlinesecurity.blogspot.com/2014/12/are-you-robot-introducing-no-captcha.html)

    I would assume it looks at how you behaved prior to clicking, how your cursor moved on its way to the check (organic path/acceleration), which part of the checkbox was clicked (random places, or dead on center every time), browser fingerprint, Google cookies & contents, click location history tied to your fingerprint or account if it detects one etc.

    It's fairly difficult to fake "organic" behavior in such a way that it would fool a continuously learning pattern detection engine. In the cases where it's not sure, it still prompts you to match an actual CAPTCHA string.

    CSS div element - how to show horizontal scroll bars only?

    CSS3 has the overflow-x property, but I wouldn't expect great support for that. In CSS2 all you can do is set a general scroll policy and work your widths and heights not to mess them up.

    Upload file to FTP using C#

    Easiest way

    The most trivial way to upload a file to an FTP server using .NET framework is using WebClient.UploadFile method:

    WebClient client = new WebClient();
    client.Credentials = new NetworkCredential("username", "password");
    client.UploadFile("ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");
    

    Advanced options

    If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, ascii/text transfer mode, active mode, transfer resuming, progress monitoring, etc), use FtpWebRequest. Easy way is to just copy a FileStream to an FTP stream using Stream.CopyTo:

    FtpWebRequest request =
        (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
    request.Credentials = new NetworkCredential("username", "password");
    request.Method = WebRequestMethods.Ftp.UploadFile;  
    
    using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip"))
    using (Stream ftpStream = request.GetRequestStream())
    {
        fileStream.CopyTo(ftpStream);
    }
    

    Progress monitoring

    If you need to monitor an upload progress, you have to copy the contents by chunks yourself:

    FtpWebRequest request =
        (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
    request.Credentials = new NetworkCredential("username", "password");
    request.Method = WebRequestMethods.Ftp.UploadFile;  
    
    using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip"))
    using (Stream ftpStream = request.GetRequestStream())
    {
        byte[] buffer = new byte[10240];
        int read;
        while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            ftpStream.Write(buffer, 0, read);
            Console.WriteLine("Uploaded {0} bytes", fileStream.Position);
        } 
    }
    

    For GUI progress (WinForms ProgressBar), see C# example at:
    How can we show progress bar for upload with FtpWebRequest


    Uploading folder

    If you want to upload all files from a folder, see
    Upload directory of files to FTP server using WebClient.

    For a recursive upload, see
    Recursive upload to FTP server in C#

    Explode string by one or more spaces or tabs

    The author asked for explode, to you can use explode like this

    $resultArray = explode("\t", $inputString);

    Note: you must used double quote, not single.

    Python: Get the first character of the first string in a list?

    You almost had it right. The simplest way is

    mylist[0][0]   # get the first character from the first item in the list
    

    but

    mylist[0][:1]  # get up to the first character in the first item in the list
    

    would also work.

    You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.

    How to create permanent PowerShell Aliases

    I found that I can run this command:

    notepad $((Split-Path $profile -Parent) + "\profile.ps1")
    

    and it opens my default powershell profile (at least when using Terminal for Windows). I found that here.

    Then add an alias. For example, here is my alias of jn for jupyter notebook (I hate typing out the cumbersome jupyter notebook every time):

    Set-Alias -Name jn -Value C:\Users\words\Anaconda3\Scripts\jupyter-notebook.exe
    

    Appending a line to a file only if it does not already exist

    This would be a clean, readable and reusable solution using grep and echo to add a line to a file only if it doesn't already exist:

    LINE='include "/configs/projectname.conf"'
    FILE='lighttpd.conf'
    grep -qF -- "$LINE" "$FILE" || echo "$LINE" >> "$FILE"
    

    If you need to match the whole line use grep -xqF

    Add -s to ignore errors when the file does not exist, creating a new file with just that line.

    release Selenium chromedriver.exe from memory

    Theoretically, calling browser.Quit will close all browser tabs and kill the process.

    However, in my case I was not able to do that - since I running multiple tests in parallel, I didn't wanted to one test to close windows to others. Therefore, when my tests finish running, there are still many "chromedriver.exe" processes left running.

    In order to overcome that, I wrote a simple cleanup code (C#):

    Process[] chromeDriverProcesses =  Process.GetProcessesByName("chromedriver");
    
    foreach(var chromeDriverProcess in chromeDriverProcesses)
    {
         chromeDriverProcess.Kill();
    }
    

    Java String encoding (UTF-8)

    How is this different from the following?

    This line of code here:

    String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
    

    constructs a new String object (i.e. a copy of oldString), while this line of code:

    String newString = oldString;
    

    declares a new variable of type java.lang.String and initializes it to refer to the same String object as the variable oldString.

    Is there any scenario in which the two lines will have different outputs?

    Absolutely:

    String newString = oldString;
    boolean isSameInstance = newString == oldString; // isSameInstance == true
    

    vs.

    String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
     // isSameInstance == false (in most cases)    
    boolean isSameInstance = newString == oldString;
    

    a_horse_with_no_name (see comment) is right of course. The equivalent of

    String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
    

    is

    String newString = new String(oldString);
    

    minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.

    Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

    Both attributes are needed and also recheck all the form elements has "name" attribute. if you are using form submit concept, other wise just use div tag instead of form element.

    <input [(ngModel)]="firstname" name="something">
    

    pandas python how to count the number of records or rows in a dataframe

    Regards to your question... counting one Field? I decided to make it a question, but I hope it helps...

    Say I have the following DataFrame

    import numpy as np
    import pandas as pd
    
    df = pd.DataFrame(np.random.normal(0, 1, (5, 2)), columns=["A", "B"])
    

    You could count a single column by

    df.A.count()
    #or
    df['A'].count()
    

    both evaluate to 5.

    The cool thing (or one of many w.r.t. pandas) is that if you have NA values, count takes that into consideration.

    So if I did

    df['A'][1::2] = np.NAN
    df.count()
    

    The result would be

     A    3
     B    5
    

    Changing the URL in react-router v4 without using Redirect or Link

    This is how I did a similar thing. I have tiles that are thumbnails to YouTube videos. When I click the tile, it redirects me to a 'player' page that uses the 'video_id' to render the correct video to the page.

    <GridTile
      key={video_id}
      title={video_title}
      containerElement={<Link to={`/player/${video_id}`}/>}
     >
    

    ETA: Sorry, just noticed that you didn't want to use the LINK or REDIRECT components for some reason. Maybe my answer will still help in some way. ; )

    Changing factor levels with dplyr mutate

    Can't comment because I don't have enough reputation points, but recode only works on a vector, so the above code in @Stefano's answer should be

    df <- iris %>%
      mutate(Species = recode(Species, 
         setosa = "SETOSA",
         versicolor = "VERSICOLOR",
         virginica = "VIRGINICA")
      )
    

    How to calculate cumulative normal distribution?

    Alex's answer shows you a solution for standard normal distribution (mean = 0, standard deviation = 1). If you have normal distribution with mean and std (which is sqr(var)) and you want to calculate:

    from scipy.stats import norm
    
    # cdf(x < val)
    print norm.cdf(val, m, s)
    
    # cdf(x > val)
    print 1 - norm.cdf(val, m, s)
    
    # cdf(v1 < x < v2)
    print norm.cdf(v2, m, s) - norm.cdf(v1, m, s)
    

    Read more about cdf here and scipy implementation of normal distribution with many formulas here.

    Access multiple viewchildren using @viewchild

    Use @ViewChildren from @angular/core to get a reference to the components

    template

    <div *ngFor="let v of views">
        <customcomponent #cmp></customcomponent>
    </div>
    

    component

    import { ViewChildren, QueryList } from '@angular/core';
    
    /** Get handle on cmp tags in the template */
    @ViewChildren('cmp') components:QueryList<CustomComponent>;
    
    ngAfterViewInit(){
        // print array of CustomComponent objects
        console.log(this.components.toArray());
    }
    

    l?i?v?e? ?d?e?m?o?

    Proper usage of .net MVC Html.CheckBoxFor

    I was looking for the solution to show the label dynamically from database like this:

    checkbox1 : Option 1 text from database
    checkbox2 : Option 2 text from database
    checkbox3 : Option 3 text from database
    checkbox4 : Option 4 text from database
    

    So none of the above solution worked for me so I used like this:

     @Html.CheckBoxFor(m => m.Option1, new { @class = "options" }) 
     <label for="Option1">@Model.Option1Text</label>
    
     @Html.CheckBoxFor(m => m.Option2, new { @class = "options" }) 
     <label for="Option2">@Mode2.Option1Text</label>
    

    In this way when user will click on label, checkbox will be selected.

    Might be it can help someone.

    What does "async: false" do in jQuery.ajax()?

    Does it have something to do with preventing other events on the page from firing?

    Yes.

    Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.

    For more insight see: jQuery ajax success anonymous function scope

    What is a Question Mark "?" and Colon ":" Operator Used for?

    Thats an if/else statement equilavent to

    if(row % 2 == 1){
      System.out.print("<");
    }else{
      System.out.print("\r>");
    }
    

    Typescript: Type 'string | undefined' is not assignable to type 'string'

    As of TypeScript 3.7 you can use nullish coalescing operator ??. You can think of this feature as a way to “fall back” to a default value when dealing with null or undefined

    let name1:string = person.name ?? '';
    

    The ?? operator can replace uses of || when trying to use a default value and can be used when dealing with booleans, numbers, etc. where || cannot be used.

    As of TypeScript 4 you can use ??= assignment operator as a ??= b which is an alternative to a = a ?? b;

    Getting an error "fopen': This function or variable may be unsafe." when compling

    This is a warning for usual. You can either disable it by

    #pragma warning(disable:4996)
    

    or simply use fopen_s like Microsoft has intended.

    But be sure to use the pragma before other headers.

    How to convert a string to lower case in Bash?

    For Bash versions earlier than 4.0, this version should be fastest (as it doesn't fork/exec any commands):

    function string.monolithic.tolower
    {
       local __word=$1
       local __len=${#__word}
       local __char
       local __octal
       local __decimal
       local __result
    
       for (( i=0; i<__len; i++ ))
       do
          __char=${__word:$i:1}
          case "$__char" in
             [A-Z] )
                printf -v __decimal '%d' "'$__char"
                printf -v __octal '%03o' $(( $__decimal ^ 0x20 ))
                printf -v __char \\$__octal
                ;;
          esac
          __result+="$__char"
       done
       REPLY="$__result"
    }
    

    technosaurus's answer had potential too, although it did run properly for mee.

    IE8 support for CSS Media Query

    The best solution I've found is Respond.js especially if your main concern is making sure your responsive design works in IE8. It's pretty lightweight at 1kb when min/gzipped and you can make sure only IE8 clients load it:

    <!--[if lt IE 9]>
    <script src="respond.min.js"></script>
    <![endif]-->
    

    It's also the recommended method if you're using bootstrap: http://getbootstrap.com/getting-started/#support-ie8-ie9

    How can I scroll a div to be visible in ReactJS?

    I'm just adding another bit of info for others searching for a Scroll-To capability in React. I had tied several libraries for doing Scroll-To for my app, and none worked from my use case until I found react-scrollchor, so I thought I'd pass it on. https://github.com/bySabi/react-scrollchor

    How do you overcome the svn 'out of date' error?

    Error is because you didn't updated that particular file, first update then only you can commit the file.

    How to check type of variable in Java?

    None of these answers work if the variable is an uninitialized generic type

    And from what I can find, it's only possible using an extremely ugly workaround, or by passing in an initialized parameter to your function, making it in-place, see here:

    <T> T MyMethod(...){ if(T.class == MyClass.class){...}}
    

    Is NOT valid because you cannot pull the type out of the T parameter directly, since it is erased at runtime time.

    <T> void MyMethod(T out, ...){ if(out.getClass() == MyClass.class){...}}
    

    This works because the caller is responsible to instantiating the variable out before calling. This will still throw an exception if out is null when called, but compared to the linked solution, this is by far the easiest way to do this

    I know this is a kind of specific application, but since this is the first result on google for finding the type of a variable with java (and given that T is a kind of variable), I feel it should be included

    Print current call stack from a method in Python code

    If you use python debugger, not only interactive probing of variables but you can get the call stack with the "where" command or "w".

    So at the top of your program

    import pdb
    

    Then in the code where you want to see what is happening

    pdb.set_trace()
    

    and you get dropped into a prompt

    How can I set the 'backend' in matplotlib in Python?

    You can also try viewing the graph in a browser.

    Use the following:

    matplotlib.use('WebAgg')
    

    How to create a user in Django?

    Have you confirmed that you are passing actual values and not None?

    from django.shortcuts import render
    
    def createUser(request):
        userName = request.REQUEST.get('username', None)
        userPass = request.REQUEST.get('password', None)
        userMail = request.REQUEST.get('email', None)
    
        # TODO: check if already existed
        if userName and userPass and userMail:
           u,created = User.objects.get_or_create(userName, userMail)
           if created:
              # user was created
              # set the password here
           else:
              # user was retrieved
        else:
           # request was empty
    
        return render(request,'home.html')
    

    Running a script inside a docker container using shell script

    In case you don't want (or have) a running container, you can call your script directly with the run command.

    Remove the iterative tty -i -t arguments and use this:

        $ docker run ubuntu:bionic /bin/bash /path/to/script.sh
    

    This will (didn't test) also work for other scripts:

        $ docker run ubuntu:bionic /usr/bin/python /path/to/script.py
    

    git visual diff between branches

    You can also do this easily with gitk.

    > gitk branch1 branch2
    

    First click on the tip of branch1. Now right-click on the tip of branch2 and select Diff this->selected.

    How to execute Python scripts in Windows?

    Additionally, if you want to be able to run your python scripts without typing the .py (or .pyw) on the end of the file name, you need to add .PY (or .PY;.PYW) to the list of extensions in the PATHEXT environment variable.

    In Windows 7:

    right-click on Computer
    left-click Properties
    left-click Advanced system settings
    left-click the Advanced tab
    left-click Environment Variables...
    under "system variables" scroll down until you see PATHEXT
    left-click on PATHEXT to highlight it
    left-click Edit...
    Edit "Variable value" so that it contains ;.PY (the End key will skip to the end)
    left-click OK
    left-click OK
    left-click OK

    Note #1: command-prompt windows won't see the change w/o being closed and reopened.

    Note #2: the difference between the .py and .pyw extensions is that the former opens a command prompt when run, and the latter doesn't.

    On my computer, I added ;.PY;.PYW as the last (lowest-priority) extensions, so the "before" and "after" values of PATHEXT were:

    before: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

    after .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW

    Here are some instructive commands:

    C:\>echo %pathext%
    .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW
    
    C:\>assoc .py
    .py=Python.File
    
    C:\>ftype Python.File
    Python.File="C:\Python32\python.exe" "%1" %*
    
    C:\>assoc .pyw
    .pyw=Python.NoConFile
    
    C:\>ftype Python.NoConFile
    Python.NoConFile="C:\Python32\pythonw.exe" "%1" %*
    
    C:\>type c:\windows\helloworld.py
    print("Hello, world!")  # always use a comma for direct address
    
    C:\>helloworld
    Hello, world!
    
    C:\>
    

    Determining the path that a yum package installed to

    yum uses RPM, so the following command will list the contents of the installed package:

    $ rpm -ql package-name
    

    How to make an installer for my C# application?

    1. Add a new install project to your solution.
    2. Add targets from all projects you want to be installed.
    3. Configure pre-requirements and choose "Check for .NET 3.5 and SQL Express" option. Choose the location from where missing components must be installed.
    4. Configure your installer settings - company name, version, copyright, etc.
    5. Build and go!

    How can I find and run the keytool

    Simply enter these into Windows command prompt.

    cd C:\Program Files\Java\jdk1.7.0_09\bin
    
    keytool -exportcert -alias androiddebugkey -keystore "C:\Users\userName\.android\debug.keystore" -list -v
    

    The base password is android

    You will be presented with the MD5, SHA1, and SHA256 keys; Choose the one you need.

    How to execute mongo commands through shell scripts?

    Recently migrated from mongodb to Postgres. This is how I used the scripts.

    mongo < scripts.js > inserts.sql
    

    Read the scripts.js and output redirect to inserts.sql.

    scripts.js looks like this

    use myDb;
    var string = "INSERT INTO table(a, b) VALUES";
    db.getCollection('collectionName').find({}).forEach(function (object) {
        string += "('" + String(object.description) + "','" + object.name + "'),";
    });
    print(string.substring(0, string.length - 1), ";");
    

    inserts.sql looks like this

    INSERT INTO table(a, b) VALUES('abc', 'Alice'), ('def', 'Bob'), ('ghi', 'Claire');
    

    Define the selected option with the old input in Laravel / Blade

    <select>
        @if(old('value') =={{$key}})
         <option value="value" selected>{{$value}}</option>
        @else
         <option value="value">{{$value}}</option>
        @endif
    </select>
    

    java.time.format.DateTimeParseException: Text could not be parsed at index 21

    The following worked for me

    import java.time.*;
    import java.time.format.*;
    
    public class Times {
    
      public static void main(String[] args) {
        final String dateTime = "2012-02-22T02:06:58.147Z";
        DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
        final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter.withZone(ZoneId.of("UTC")));
        System.out.println(parsed.toLocalDateTime());
      }
    }
    

    and gave me output as

    2012-02-22T02:06:58.147
    

    Import Maven dependencies in IntelliJ IDEA

    I had the same issue and tried all the answers mentioned here, none worked.

    The simple solution is go to your project folder and delete all the .idea and .iml files and restart the IntelliJ ide. It works. No need to do anything with the settings.

    How to properly upgrade node using nvm

    if you have 4.2 and want to install 5.0.0 then

    nvm install v5.0.0 --reinstall-packages-from=4.2
    

    the answer of gabrielperales is right except that he missed the "=" sign at the end. if you don't put the "=" sign then new node version will be installed but the packages won't be installed.

    source: sitepoint

    Reading images in python

    If you just want to read an image in Python using the specified libraries only, I will go with matplotlib

    In matplotlib :

    import matplotlib.image
    read_img = matplotlib.image.imread('your_image.png')
    

    This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer

    You can now update your android studio to 3.4 stable version. Updates for stable version are now available. cheers!!!

    Pair/tuple data type in Go

    There is no tuple type in Go, and you are correct, the multiple values returned by functions do not represent a first-class object.

    Nick's answer shows how you can do something similar that handles arbitrary types using interface{}. (I might have used an array rather than a struct to make it indexable like a tuple, but the key idea is the interface{} type)

    My other answer shows how you can do something similar that avoids creating a type using anonymous structs.

    These techniques have some properties of tuples, but no, they are not tuples.

    prevent iphone default keyboard when focusing an <input>

    Best way to solve this as per my opinion is Using "ignoreReadonly".

    First make the input field readonly then add ignoreReadonly:true. This will make sure that even if the text field is readonly , popup will show.

    $('#txtStartDate').datetimepicker({
                locale: "da",
                format: "DD/MM/YYYY",
                ignoreReadonly: true
            });
            $('#txtEndDate').datetimepicker({
                locale: "da",
                useCurrent: false,
                format: "DD/MM/YYYY",
                ignoreReadonly: true
            });
    });
    

    How to properly set the 100% DIV height to match document/window height?

    I figured it out myself with the help of someone's answer. But he deleted it for some reason.

    Here's the solution:

    1. remove all CSS height hacks and 100% heights
    2. Use 2 nested wrappers, one in another, e.g. #wrapper and #truecontent
    3. Get the height of a browser viewport. IF it's larger than #wrapper, then set inline CSS for #wrapper to match the current browser viewport height (while keeping #truecontent intact)
    4. Listen on (window).resize event and ONLY apply inline CSS height IF the viewport is larger than the height of #truecontent, otherwise keep intact

      $(function(){
          var windowH = $(window).height();
          var wrapperH = $('#wrapper').height();
          if(windowH > wrapperH) {                            
              $('#wrapper').css({'height':($(window).height())+'px'});
          }                                                                               
          $(window).resize(function(){
              var windowH = $(window).height();
              var wrapperH = $('#wrapper').height();
              var differenceH = windowH - wrapperH;
              var newH = wrapperH + differenceH;
              var truecontentH = $('#truecontent').height();
              if(windowH > truecontentH) {
                  $('#wrapper').css('height', (newH)+'px');
              }
      
          })          
      });
      

    How to create a JPA query with LEFT OUTER JOIN

    Write this;

     SELECT f from Student f LEFT JOIN f.classTbls s WHERE s.ClassName = 'abc'
    

    Because your Student entity has One To Many relationship with ClassTbl entity.

    Clear the entire history stack and start a new activity on Android

    Intent i = new Intent(MainPoliticalLogin.this, MainActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(i);
    

    Get file name from URL

    public String getFileNameWithoutExtension(URL url) {
        String path = url.getPath();
    
        if (StringUtils.isBlank(path)) {
            return null;
        }
        if (StringUtils.endsWith(path, "/")) {
            //is a directory ..
            return null;
        }
    
        File file = new File(url.getPath());
        String fileNameWithExt = file.getName();
    
        int sepPosition = fileNameWithExt.lastIndexOf(".");
        String fileNameWithOutExt = null;
        if (sepPosition >= 0) {
            fileNameWithOutExt = fileNameWithExt.substring(0,sepPosition);
        }else{
            fileNameWithOutExt = fileNameWithExt;
        }
    
        return fileNameWithOutExt;
    }
    

    How to fix "unable to open stdio.h in Turbo C" error?

    On most systems, you'd have to be trying fairly hard not to find '<stdio.h>', to the point where the first reaction is "is <stdio.h> installed". So, I'd be looking to see if the file exists in a plausible location. If not, then your installation of Turbo C is broken; reinstall. If you can find it, then you will have to establish why the compiler is not searching for it in the right place - what are the compiler options you've specified and where is the compiler searching for its headers (and why isn't it searching where the header is).

    Save bitmap to file function

    In kotlin :

    private fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat, quality: Int) {
        outputStream().use { out ->
            bitmap.compress(format, quality, out)
            out.flush()
        }
    }
    

    usage example:

    File(exportDir, "map.png").writeBitmap(bitmap, Bitmap.CompressFormat.PNG, 85)
    

    How to change a table name using an SQL query?

    rename table name :

    RENAME TABLE old_tableName TO new_tableName;
    

    for example:

    RENAME TABLE company_name TO company_master;
    

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

    Not an answer to the very question but perhaps an idea for the underlying task:

    When your site logic should not show a certain element, you could insert an invisible "flag" element that you check for.

    if condition
        renderElement()
    else
        renderElementNotShownFlag() // used by Selenium test
    

    how to check for null with a ng-if values in a view with angularjs?

    Here is a simple example that I tried to explain.

    <div>
        <div *ngIf="product">     <!--If "product" exists-->
          <h2>Product Details</h2><hr>
          <h4>Name: {{ product.name }}</h4>
          <h5>Price: {{ product.price | currency }}</h5>
          <p> Description: {{ product.description }}</p>
        </div>
    
        <div *ngIf="!product">     <!--If "product" not exists-->
           *Product not found
        </div>
    </div>
    

    How do I append one string to another in Python?

    If you only have one reference to a string and you concatenate another string to the end, CPython now special cases this and tries to extend the string in place.

    The end result is that the operation is amortized O(n).

    e.g.

    s = ""
    for i in range(n):
        s+=str(i)
    

    used to be O(n^2), but now it is O(n).

    From the source (bytesobject.c):

    void
    PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w)
    {
        PyBytes_Concat(pv, w);
        Py_XDECREF(w);
    }
    
    
    /* The following function breaks the notion that strings are immutable:
       it changes the size of a string.  We get away with this only if there
       is only one module referencing the object.  You can also think of it
       as creating a new string object and destroying the old one, only
       more efficiently.  In any case, don't use this if the string may
       already be known to some other part of the code...
       Note that if there's not enough memory to resize the string, the original
       string object at *pv is deallocated, *pv is set to NULL, an "out of
       memory" exception is set, and -1 is returned.  Else (on success) 0 is
       returned, and the value in *pv may or may not be the same as on input.
       As always, an extra byte is allocated for a trailing \0 byte (newsize
       does *not* include that), and a trailing \0 byte is stored.
    */
    
    int
    _PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
    {
        register PyObject *v;
        register PyBytesObject *sv;
        v = *pv;
        if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) {
            *pv = 0;
            Py_DECREF(v);
            PyErr_BadInternalCall();
            return -1;
        }
        /* XXX UNREF/NEWREF interface should be more symmetrical */
        _Py_DEC_REFTOTAL;
        _Py_ForgetReference(v);
        *pv = (PyObject *)
            PyObject_REALLOC((char *)v, PyBytesObject_SIZE + newsize);
        if (*pv == NULL) {
            PyObject_Del(v);
            PyErr_NoMemory();
            return -1;
        }
        _Py_NewReference(*pv);
        sv = (PyBytesObject *) *pv;
        Py_SIZE(sv) = newsize;
        sv->ob_sval[newsize] = '\0';
        sv->ob_shash = -1;          /* invalidate cached hash value */
        return 0;
    }
    

    It's easy enough to verify empirically.

    $ python -m timeit -s"s=''" "for i in xrange(10):s+='a'"
    1000000 loops, best of 3: 1.85 usec per loop
    $ python -m timeit -s"s=''" "for i in xrange(100):s+='a'"
    10000 loops, best of 3: 16.8 usec per loop
    $ python -m timeit -s"s=''" "for i in xrange(1000):s+='a'"
    10000 loops, best of 3: 158 usec per loop
    $ python -m timeit -s"s=''" "for i in xrange(10000):s+='a'"
    1000 loops, best of 3: 1.71 msec per loop
    $ python -m timeit -s"s=''" "for i in xrange(100000):s+='a'"
    10 loops, best of 3: 14.6 msec per loop
    $ python -m timeit -s"s=''" "for i in xrange(1000000):s+='a'"
    10 loops, best of 3: 173 msec per loop
    

    It's important however to note that this optimisation isn't part of the Python spec. It's only in the cPython implementation as far as I know. The same empirical testing on pypy or jython for example might show the older O(n**2) performance .

    $ pypy -m timeit -s"s=''" "for i in xrange(10):s+='a'"
    10000 loops, best of 3: 90.8 usec per loop
    $ pypy -m timeit -s"s=''" "for i in xrange(100):s+='a'"
    1000 loops, best of 3: 896 usec per loop
    $ pypy -m timeit -s"s=''" "for i in xrange(1000):s+='a'"
    100 loops, best of 3: 9.03 msec per loop
    $ pypy -m timeit -s"s=''" "for i in xrange(10000):s+='a'"
    10 loops, best of 3: 89.5 msec per loop
    

    So far so good, but then,

    $ pypy -m timeit -s"s=''" "for i in xrange(100000):s+='a'"
    10 loops, best of 3: 12.8 sec per loop
    

    ouch even worse than quadratic. So pypy is doing something that works well with short strings, but performs poorly for larger strings.

    LINQ - Left Join, Group By, and Count

    While the idea behind LINQ syntax is to emulate the SQL syntax, you shouldn't always think of directly translating your SQL code into LINQ. In this particular case, we don't need to do group into since join into is a group join itself.

    Here's my solution:

    from p in context.ParentTable
    join c in context.ChildTable on p.ParentId equals c.ChildParentId into joined
    select new { ParentId = p.ParentId, Count = joined.Count() }
    

    Unlike the mostly voted solution here, we don't need j1, j2 and null checking in Count(t => t.ChildId != null)

    How do I pull from a Git repository through an HTTP proxy?

    Set Git credential.helper to wincred.

    git config --global credential.helper wincred
    

    Make sure there is only 1 credential.helper

    git config -l
    

    If there is more than 1 and it's not set to wincred remove it.

    git config --system --unset credential.helper
    

    Now set the proxy with no password.

    git config --global http.proxy http://<YOUR WIN LOGIN NAME>@proxy:80
    

    Check that all the settings that you added looks good....

    git config --global -l
    

    Now you good to go!

    Another Repeated column in mapping for entity error

    @Id
    @Column(name = "COLUMN_NAME", nullable = false)
    public Long getId() {
        return id;
    }
    
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, targetEntity = SomeCustomEntity.class)
    @JoinColumn(name = "COLUMN_NAME", referencedColumnName = "COLUMN_NAME", nullable = false, updatable = false, insertable = false)
    @org.hibernate.annotations.Cascade(value = org.hibernate.annotations.CascadeType.ALL)
    public List<SomeCustomEntity> getAbschreibareAustattungen() {
        return abschreibareAustattungen;
    }
    

    If you have already mapped a column and have accidentaly set the same values for name and referencedColumnName in @JoinColumn hibernate gives the same stupid error

    Error:

    Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.testtest.SomeCustomEntity column: COLUMN_NAME (should be mapped with insert="false" update="false")

    How to parse month full form string using DateFormat in Java?

    LocalDate from java.time

    Use LocalDate from java.time, the modern Java date and time API, for a date

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d, u", Locale.ENGLISH);
        LocalDate date = LocalDate.parse("June 27, 2007", dateFormatter);
        System.out.println(date);
    

    Output:

    2007-06-27

    As others have said already, remember to specify an English-speaking locale when your string is in English. A LocalDate is a date without time of day, so a lot better suitable for the date from your string than the old Date class. Despite its name a Date does not represent a date but a point in time that falls on at least two different dates in different time zones of the world.

    Only if you need an old-fashioned Date for an API that you cannot afford to upgrade to java.time just now, convert like this:

        Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
        Date oldfashionedDate = Date.from(startOfDay);
        System.out.println(oldfashionedDate);
    

    Output in my time zone:

    Wed Jun 27 00:00:00 CEST 2007

    Link

    Oracle tutorial: Date Time explaining how to use java.time.

    Detecting user leaving page with react-router

    For react-router v3.x

    I had the same issue where I needed a confirmation message for any unsaved change on the page. In my case, I was using React Router v3, so I could not use <Prompt />, which was introduced from React Router v4.

    I handled 'back button click' and 'accidental link click' with the combination of setRouteLeaveHook and history.pushState(), and handled 'reload button' with onbeforeunload event handler.

    setRouteLeaveHook (doc) & history.pushState (doc)

    • Using only setRouteLeaveHook was not enough. For some reason, the URL was changed although the page remained the same when 'back button' was clicked.

        // setRouteLeaveHook returns the unregister method
        this.unregisterRouteHook = this.props.router.setRouteLeaveHook(
          this.props.route,
          this.routerWillLeave
        );
      
        ...
      
        routerWillLeave = nextLocation => {
          // Using native 'confirm' method to show confirmation message
          const result = confirm('Unsaved work will be lost');
          if (result) {
            // navigation confirmed
            return true;
          } else {
            // navigation canceled, pushing the previous path
            window.history.pushState(null, null, this.props.route.path);
            return false;
          }
        };
      

    onbeforeunload (doc)

    • It is used to handle 'accidental reload' button

      window.onbeforeunload = this.handleOnBeforeUnload;
      
      ...
      
      handleOnBeforeUnload = e => {
        const message = 'Are you sure?';
        e.returnValue = message;
        return message;
      }
      

    Below is the full component that I have written

    • note that withRouter is used to have this.props.router.
    • note that this.props.route is passed down from the calling component
    • note that currentState is passed as prop to have initial state and to check any change

      import React from 'react';
      import PropTypes from 'prop-types';
      import _ from 'lodash';
      import { withRouter } from 'react-router';
      import Component from '../Component';
      import styles from './PreventRouteChange.css';
      
      class PreventRouteChange extends Component {
        constructor(props) {
          super(props);
          this.state = {
            // initialize the initial state to check any change
            initialState: _.cloneDeep(props.currentState),
            hookMounted: false
          };
        }
      
        componentDidUpdate() {
      
         // I used the library called 'lodash'
         // but you can use your own way to check any unsaved changed
          const unsaved = !_.isEqual(
            this.state.initialState,
            this.props.currentState
          );
      
          if (!unsaved && this.state.hookMounted) {
            // unregister hooks
            this.setState({ hookMounted: false });
            this.unregisterRouteHook();
            window.onbeforeunload = null;
          } else if (unsaved && !this.state.hookMounted) {
            // register hooks
            this.setState({ hookMounted: true });
            this.unregisterRouteHook = this.props.router.setRouteLeaveHook(
              this.props.route,
              this.routerWillLeave
            );
            window.onbeforeunload = this.handleOnBeforeUnload;
          }
        }
      
        componentWillUnmount() {
          // unregister onbeforeunload event handler
          window.onbeforeunload = null;
        }
      
        handleOnBeforeUnload = e => {
          const message = 'Are you sure?';
          e.returnValue = message;
          return message;
        };
      
        routerWillLeave = nextLocation => {
          const result = confirm('Unsaved work will be lost');
          if (result) {
            return true;
          } else {
            window.history.pushState(null, null, this.props.route.path);
            if (this.formStartEle) {
              this.moveTo.move(this.formStartEle);
            }
            return false;
          }
        };
      
        render() {
          return (
            <div>
              {this.props.children}
            </div>
          );
        }
      }
      
      PreventRouteChange.propTypes = propTypes;
      
      export default withRouter(PreventRouteChange);
      

    Please let me know if there is any question :)

    Numpy first occurrence of value greater than existing value

    I would go with

    i = np.min(np.where(V >= x))
    

    where V is vector (1d array), x is the value and i is the resulting index.

    Use FontAwesome or Glyphicons with css :before

    This approach should be avoided. The default value for vertical-align is baseline. Changing the font-family of only the pseudo element will result in elements with differing fonts. Different fonts can have different font metrics and different baselines. In order for different baselines to align, the overall height of the element would have to increase. See this effect in action.

    It is always better to have one element per font icon.

    What does "if (rs.next())" mean?

    The next() method (offcial doc here) simply move the pointer of the result rows set to the next row (if it can). Anyway you can read this from the offcial doc as well:

    Moves the cursor down one row from its current position.

    This method return true if there's another row or false otherwise.

    I can't access http://localhost/phpmyadmin/

    You should use localhost:portnumber/phpmyadmin Here the Portnumber is the number which you set for your web server or if you have not set it until now it is by Default - 80.

    Plotting 4 curves in a single plot, with 3 y-axes

    One possibility you can try is to create 3 axes stacked one on top of the other with the 'Color' properties of the top two set to 'none' so that all the plots are visible. You would have to adjust the axes width, position, and x-axis limits so that the 3 y axes are side-by-side instead of on top of one another. You would also want to remove the x-axis tick marks and labels from 2 of the axes since they will lie on top of one another.

    Here's a general implementation that computes the proper positions for the axes and offsets for the x-axis limits to keep the plots lined up properly:

    %# Some sample data:
    x = 0:20;
    N = numel(x);
    y1 = rand(1,N);
    y2 = 5.*rand(1,N)+5;
    y3 = 50.*rand(1,N)-50;
    
    %# Some initial computations:
    axesPosition = [110 40 200 200];  %# Axes position, in pixels
    yWidth = 30;                      %# y axes spacing, in pixels
    xLimit = [min(x) max(x)];         %# Range of x values
    xOffset = -yWidth*diff(xLimit)/axesPosition(3);
    
    %# Create the figure and axes:
    figure('Units','pixels','Position',[200 200 330 260]);
    h1 = axes('Units','pixels','Position',axesPosition,...
              'Color','w','XColor','k','YColor','r',...
              'XLim',xLimit,'YLim',[0 1],'NextPlot','add');
    h2 = axes('Units','pixels','Position',axesPosition+yWidth.*[-1 0 1 0],...
              'Color','none','XColor','k','YColor','m',...
              'XLim',xLimit+[xOffset 0],'YLim',[0 10],...
              'XTick',[],'XTickLabel',[],'NextPlot','add');
    h3 = axes('Units','pixels','Position',axesPosition+yWidth.*[-2 0 2 0],...
              'Color','none','XColor','k','YColor','b',...
              'XLim',xLimit+[2*xOffset 0],'YLim',[-50 50],...
              'XTick',[],'XTickLabel',[],'NextPlot','add');
    xlabel(h1,'time');
    ylabel(h3,'values');
    
    %# Plot the data:
    plot(h1,x,y1,'r');
    plot(h2,x,y2,'m');
    plot(h3,x,y3,'b');
    

    and here's the resulting figure:

    enter image description here

    How to redirect to the same page in PHP

    I use correctly in localhost:

    header('0');
    

    NSRange from Swift Range?

    For cases like the one you described, I found this to work. It's relatively short and sweet:

     let attributedString = NSMutableAttributedString(string: "follow the yellow brick road") //can essentially come from a textField.text as well (will need to unwrap though)
     let text = "follow the yellow brick road"
     let str = NSString(string: text) 
     let theRange = str.rangeOfString("yellow")
     attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor(), range: theRange)
    

    How to handle query parameters in angular 2

    RouteParams are now deprecated , So here is how to do it in the new router.

    this.router.navigate(['/login'],{ queryParams: { token:'1234'}})
    

    And then in the login component you can take the parameter,

    constructor(private route: ActivatedRoute) {}
    ngOnInit() {
        // Capture the token  if available
        this.sessionId = this.route.queryParams['token']
    
    }
    

    Here is the documentation

    Windows command for file size only

    If you are inside a batch script, you can use argument variable tricks to get the filesize:

    filesize.bat:

    @echo off
    echo %~z1
    

    This gives results like the ones you suggest in your question.

    Type

    help call
    

    at the command prompt for all of the crazy variable manipulation options. Also see this article for more information.

    Edit: This only works in Windows 2000 and later

    How to move the cursor word by word in the OS X Terminal

    Actually there is a much better approach. Hold option ( alt on some keyboards) and press the arrow keys left or right to move by word. Simple as that.

    option
    option

    Also ctrle will take you to the end of the line and ctrla will take you to the start.

    Another git process seems to be running in this repository

    • My Mac is slow so I ran 2 git commits: one executed and the second was blocked by the first.
    • I tried rm -f .git/index.lock
      • rm .git/refs/heads/[your-branch-name].lock
    • <path to your repo>/.git/index.lock
    • <path to your repo>/.git/modules/<path to your submodule>/index.lock

    @Ankush:

    1. find | grep '\.lock$'
    2. rm -f ./.git/index.lock this was useful to check - no .lock file was lurking

    I did what @Chole did - checked out of my IDE exited and looked at a git-status once more. Then ran a $git add . $git commit -m'msg' $git push

    It cleared the 2 terminals that were running commands and solved the problem. Hope this helps someone - the diagnostics were good so thanks all, very helpful.

    A slow Mac has caused this problem before - so now I just wait for a bit before running a second commit that conflicts with the first.

    jQuery click event not working in mobile browsers

    With this solution, you probably can resolve all mobile clicks problems. Use only "click" function, but add z-index:99 to the element in css:

    _x000D_
    _x000D_
      $("#test").on('click', function(){_x000D_
        alert("CLICKED!")_x000D_
      });
    _x000D_
    #test{   _x000D_
      z-index:99;_x000D_
      cursor:pointer;_x000D_
    }
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
    _x000D_
    <div id="test">CLICK ME</div>
    _x000D_
    _x000D_
    _x000D_

    Credit:https://foundation.zurb.com/forum/posts/3258-buttons-not-clickable-on-iphone

    How to convert enum value to int?

    Sometime some C# approach makes the life easier in Java world..:

    class XLINK {
    static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
    }
    //Now is trivial to use it like a C# enum:
    int rcv = XLINK.ACK;
    

    Scala list concatenation, ::: vs ++

    ::: works only with lists, while ++ can be used with any traversable. In the current implementation (2.9.0), ++ falls back on ::: if the argument is also a List.

    Understanding `scale` in R

    I thought I would contribute by providing a concrete example of the practical use of the scale function. Say you have 3 test scores (Math, Science, and English) that you want to compare. Maybe you may even want to generate a composite score based on each of the 3 tests for each observation. Your data could look as as thus:

    student_id <- seq(1,10)
    math <- c(502,600,412,358,495,512,410,625,573,522)
    science <- c(95,99,80,82,75,85,80,95,89,86)
    english <- c(25,22,18,15,20,28,15,30,27,18)
    df <- data.frame(student_id,math,science,english)
    

    Obviously it would not make sense to compare the means of these 3 scores as the scale of the scores are vastly different. By scaling them however, you have more comparable scoring units:

    z <- scale(df[,2:4],center=TRUE,scale=TRUE)
    

    You could then use these scaled results to create a composite score. For instance, average the values and assign a grade based on the percentiles of this average. Hope this helped!

    Note: I borrowed this example from the book "R In Action". It's a great book! Would definitely recommend.

    Object array initialization without default constructor

    One way to solve is to give a static factory method to allocate the array if for some reason you want to give constructor private.

    static Car*  Car::CreateCarArray(int dimensions)
    

    But why are you keeping one constructor public and other private?

    But anyhow one more way is to declare the public constructor with default value

    #define DEFAULT_CAR_INIT 0
    Car::Car(int _no=DEFAULT_CAR_INIT);
    

    What is __gxx_personality_v0 for?

    A quick grep of the libstd++ code base revealed the following two usages of __gx_personality_v0:

    In libsupc++/unwind-cxx.h

    // GNU C++ personality routine, Version 0.                                      
    extern "C" _Unwind_Reason_Code __gxx_personality_v0
         (int, _Unwind_Action, _Unwind_Exception_Class,
          struct _Unwind_Exception *, struct _Unwind_Context *);
    

    In libsupc++/eh_personality.cc

    #define PERSONALITY_FUNCTION    __gxx_personality_v0
    extern "C" _Unwind_Reason_Code
    PERSONALITY_FUNCTION (int version,
                          _Unwind_Action actions,
                          _Unwind_Exception_Class exception_class,
                          struct _Unwind_Exception *ue_header,
                          struct _Unwind_Context *context)
    {
      // ... code to handle exceptions and stuff ...
    }
    

    (Note: it's actually a little more complicated than that; there's some conditional compilation that can change some details).

    So, as long as your code isn't actually using exception handling, defining the symbol as void* won't affect anything, but as soon as it does, you're going to crash - __gxx_personality_v0 is a function, not some global object, so trying to call the function is going to jump to address 0 and cause a segfault.

    How to keep console window open

    Write Console.ReadKey(); in the last line of main() method. This line prevents finishing the console. I hope it would help you.

    What are the "spec.ts" files generated by Angular CLI for?

    The spec files are unit tests for your source files. The convention for Angular applications is to have a .spec.ts file for each .ts file. They are run using the Jasmine javascript test framework through the Karma test runner (https://karma-runner.github.io/) when you use the ng test command.

    You can use this for some further reading:

    https://angular.io/guide/testing

    Remove table row after clicking table row delete button

    Using pure Javascript:

    Don't need to pass this to the SomeDeleteRowFunction():

    <td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction()"></td>
    

    The onclick function:

    function SomeDeleteRowFunction() {
          // event.target will be the input element.
          var td = event.target.parentNode; 
          var tr = td.parentNode; // the row to be removed
          tr.parentNode.removeChild(tr);
    }
    

    Android Endless List

    I've been working in another solution very similar to that, but, I am using a footerView to give the possibility to the user download more elements clicking the footerView, I am using a "menu" which is shown above the ListView and in the bottom of the parent view, this "menu" hides the bottom of the ListView, so, when the listView is scrolling the menu disappear and when scroll state is idle, the menu appear again, but when the user scrolls to the end of the listView, I "ask" to know if the footerView is shown in that case, the menu doesn't appear and the user can see the footerView to load more content. Here the code:

    Regards.

    listView.setOnScrollListener(new OnScrollListener() {
    
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // TODO Auto-generated method stub
            if(scrollState == SCROLL_STATE_IDLE) {
                if(footerView.isShown()) {
                    bottomView.setVisibility(LinearLayout.INVISIBLE);
                } else {
                    bottomView.setVisibility(LinearLayout.VISIBLE);
                } else {
                    bottomView.setVisibility(LinearLayout.INVISIBLE);
                }
            }
        }
    
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
    
        }
    });
    

    What is the best IDE for PHP?

    I'm using Zend Studio. It has decent syntax highlighting, code completion and such. But the best part is that you can debug PHP code, either with a standalone PHP interpreter, or even on a live web server as you "browse" along your pages. You get the usual Visual Studio keys, breakpoints, watches and call stack, which is almost indispensable for bug hunting. No more "alert()"-cluttered debugged source code :)

    List all of the possible goals in Maven 2?

    The goal you indicate in the command line is linked to the lifecycle of Maven. For example, the build lifecycle (you also have the clean and site lifecycles which are different) is composed of the following phases:

    • validate: validate the project is correct and all necessary information is available.
    • compile: compile the source code of the project.
    • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed.
    • package: take the compiled code and package it in its distributable format, such as a JAR.
    • integration-test: process and deploy the package if necessary into an environment where integration tests can be run.
    • verify: run any checks to verify the package is valid and meets quality criteria
    • install: install the package into the local repository, for use as a dependency in other projects locally.
    • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

    You can find the list of "core" plugins here, but there are plenty of others plugins, such as the codehaus ones, here.

    Youtube autoplay not working on mobile devices with embedded HTML5 player

    The code below was tested on iPhone, iPad (iOS13), Safari (Catalina). It was able to autoplay the YouTube video on all devices. Make sure the video is muted and the playsinline parameter is on. Those are the magic parameters that make it work.

    <!DOCTYPE html>
    <html>
        <head>
            <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
        </head>
      <body>
    <!-- 1. The <iframe> (video player) will replace this <div> tag. -->
    <div id="player"></div>
    
    <script>
      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');
    
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    
      // 3. This function creates an <iframe> (and YouTube player)
      //    after the API code downloads.
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          width: '100%',
          videoId: 'osz5tVY97dQ',
          playerVars: { 'autoplay': 1, 'playsinline': 1 },
          events: {
            'onReady': onPlayerReady
          }
        });
      }
    
      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
         event.target.mute();
        event.target.playVideo();
      }
    </script>
      </body>
    </html>
    

    Display the current date and time using HTML and Javascript with scrollable effects in hta application

    This will help you.

    Javascript

    debugger;
    var today = new Date();
    document.getElementById('date').innerHTML = today
    

    Fiddle Demo

    R * not meaningful for factors ERROR

    new[,2] is a factor, not a numeric vector. Transform it first

    new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5
    

    MVC3 DropDownListFor - a simple example?

    For binding Dynamic Data in a DropDownList you can do the following:

    Create ViewBag in Controller like below

    ViewBag.ContribTypeOptions = yourFunctionValue();
    

    now use this value in view like below:

    @Html.DropDownListFor(m => m.ContribType, 
        new SelectList(@ViewBag.ContribTypeOptions, "ContribId", 
                       "Value", Model.ContribTypeOptions.First().ContribId), 
        "Select, please")
    

    Is there a 'foreach' function in Python 3?

    If I understood you right, you mean that if you have a function 'func', you want to check for each item in list if func(item) returns true; if you get true for all, then do something.

    You can use 'all'.

    For example: I want to get all prime numbers in range 0-10 in a list:

    from math import sqrt
    primes = [x for x in range(10) if x > 2 and all(x % i !=0 for i in range(2, int(sqrt(x)) + 1))]
    

    How to extend a class in python?

    Use:

    import color
    
    class Color(color.Color):
        ...
    

    If this were Python 2.x, you would also want to derive color.Color from object, to make it a new-style class:

    class Color(object):
        ...
    

    This is not necessary in Python 3.x.

    Why can't I find SQL Server Management Studio after installation?

    It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:

    http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

    and the one for 64 bit WITH the management tools (management studio) is here:

    http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

    From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.

    How to resolve 'npm should be run outside of the node repl, in your normal shell'

    For Windows users, run npm commands from the Command Prompt (cmd.exe), not Node.Js (node.exe). So your "normal shell" is cmd.exe. (I agree this message can be confusing for a Windows, Node newbie.)

    By the way, the Node.js Command Prompt is actually just an easy shortcut to cmd.exe.

    Below is an example screenshot for installing grunt from cmd.exe:

    enter image description here

    how to open a jar file in Eclipse

    Try JadClipse.It will open all your .class file. Add library to your project and when you try to open any object declared in the lib file it will open just like your .java file.

    In eclipse->help-> marketplace -> go to popular tab. There you can find plugins for the same.

    Update: For those who are unable to find above plug-in, try downloading this: https://github.com/java-decompiler/jd-eclipse/releases/download/v1.0.0/jd-eclipse-site-1.0.0-RC2.zip

    Then import it into Eclipse.

    If you have issues importing above plug-in, refer: How to install plugin for Eclipse from .zip

    How to read file with space separated values in pandas

    add delim_whitespace=True argument, it's faster than regex.

    How to check a boolean condition in EL?

    Both works. Instead of == you can write eq

    How do I instantiate a Queue object in java?

    Queue in Java is defined as an interface and many ready-to-use implementation is present as part of JDK release. Here are some: LinkedList, Priority Queue, ArrayBlockingQueue, ConcurrentLinkedQueue, Linked Transfer Queue, Synchronous Queue etc.

    SO You can create any of these class and hold it as Queue reference. for example

    import java.util.LinkedList;
    import java.util.Queue;
    
    public class QueueExample {
    
     public static void main (String[] args) {
      Queue que = new LinkedList();
      que.add("first");
      que.offer("second");
      que.offer("third");
      System.out.println("Queue Print:: " + que);
      
      String head = que.element();
      System.out.println("Head element:: " + head);
      
      String element1 = que.poll();
      System.out.println("Removed Element:: " + element1);
      
      System.out.println("Queue Print after poll:: " + que);
      String element2 = que.remove();
      System.out.println("Removed Element:: " + element2);
      
      System.out.println("Queue Print after remove:: " + que);  
     }
    }
    

    You can also implement your own custom Queue implementing Queue interface.

    Excel VBA date formats

    To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.

    Sub test_date_or_String()
     Set c = ActiveCell
     c.NumberFormat = "@"
     c.Value = CDate("03/04/2014")
       Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
     c.NumberFormat = "m/d/yyyy"
       Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
     c.Value = CDate("03/04/2014")
       Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date    
    End Sub
    

    Bootstrap 3 Collapse show state with Chevron icon

    Here's a couple of pure css helper classes which lets you handle any kind of toggle content right in your html.

    It works with any element you need to switch. Whatever your layout is you just put it inside a couple of elements with the .if-collapsed and .if-not-collapsed classes within the toggle element.

    The only catch is that you have to make sure you put the desired initial state of the toggle. If it's initially closed, then put a collapsed class on the toggle.

    It also requires the :not selector, it doesn't work on IE8.

    HTML example:

    <a class="btn btn-primary collapsed" data-toggle="collapse" href="#collapseExample">
      <!--You can put any valid html inside these!-->
      <span class="if-collapsed">Open</span>
      <span class="if-not-collapsed">Close</span>
    </a>
    <div class="collapse" id="collapseExample">
      <div class="well">
        ...
      </div>
    </div>
    

    Less version:

    [data-toggle="collapse"] {
        &.collapsed .if-not-collapsed {
             display: none;
        }
        &:not(.collapsed) .if-collapsed {
             display: none;
        }
    }
    

    CSS version:

    [data-toggle="collapse"].collapsed .if-not-collapsed {
      display: none;
    }
    [data-toggle="collapse"]:not(.collapsed) .if-collapsed {
      display: none;
    }
    

    Javascript - sort array based on another array

    this should works:

    var i,search, itemsArraySorted = [];
    while(sortingArr.length) {
        search = sortingArr.shift();
        for(i = 0; i<itemsArray.length; i++) {
            if(itemsArray[i][1] == search) {
                itemsArraySorted.push(itemsArray[i]);
                break;
            }
        } 
    }
    
    itemsArray = itemsArraySorted;
    

    Breaking a list into multiple columns in Latex

    I've had multenum for "Multi-column enumerated lists" recommended to me, but I've never actually used it myself, yet.

    Edit: The syntax doesn't exactly look like you could easily copy+paste lists into the LaTeX code. So, it may not be the best solution for your use case!

    Display HTML form values in same page after submit using Ajax

    display html form values in same page after clicking on submit button using JS & html codes. After opening it up again it should give that comments in that page.

    How to view DB2 Table structure

    Use the below to check the table description for a single table

    DESCRIBE TABLE Schema Name.Table Name
    

    join the below tables to check the table description for a multiple tables, join with the table id syscat.tables and syscat.columns

    You can also check the details of indexes on the table using the below command describe indexes for table . show detail

    JavaScript: SyntaxError: missing ) after argument list

    You have an extra closing } in your function.

    var nav = document.getElementsByClassName('nav-coll');
    for (var i = 0; i < button.length; i++) {
        nav[i].addEventListener('click',function(){
                console.log('haha');
            }        // <== remove this brace
        }, false);
    };
    

    You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.

    ClassNotFoundException: org.slf4j.LoggerFactory

    Better to always download as your first try, the most recent version from the developer's site

    I had the same error message you had, and by downloading the jar from the above (slf4j-1.7.2.tar.gz most recent version as of 2012OCT13), untarring, uncompressing, adding 2 jars to build path in eclipse (or adding to classpath in comand line):

    1. slf4j-api-1.7.2.jar
    2. slf4j-simple-1.7.2.jar

    I was able to run my program.

    Checking for a null object in C++

    Basically, all I'm trying to do is to prevent the program from crashing when some_cpp_function() is called with NULL.

    It is not possible to call the function with NULL. One of the purpose of having the reference, it will point to some object always as you have to initialize it when defining it. Do not think reference as a fancy pointer, think of it as an alias name for the object itself. Then this type of confusion will not arise.

    Maven: Non-resolvable parent POM

    <relativePath>

    If you build under a child project, then <relativePath> can help you resolve the parent pom.

    install parent pom

    But if you build the child project out of its folder, <relativePath> doesn't work. You can install the parent pom into your local repository first, then build the child project.

    Add space between two particular <td>s

    None of the answers worked for me. The simplest way would be to add <td>s in between with width = 5px and background='white' or whatever the background color of the page is.

    Again this will fail in case you have a list of <th>s representing table headers.

    How to loop through a dataset in powershell?

    The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()

    for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
    { 
      write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
    }
    

    Additionally foreach allows you to iterate through a collection or array without needing to figure out the length.

    Rewritten (and edited for compile) -

    foreach ($Row in $ds.Tables[1].Rows)
    { 
      write-host "value is : $($Row[0])"
    }
    

    Function not defined javascript

    The actual problem is with your

    showList function.

    There is an extra ')' after 'visible'.

    Remove that and it will work fine.

    function showList()
    {
      if (document.getElementById("favSports").style.visibility == "hidden") 
        {
           // document.getElementById("favSports").style.visibility = "visible");  
           // your code
           document.getElementById("favSports").style.visibility = "visible";
           // corrected code
        }
    }
    

    JSON parsing using Gson for Java

    You can use a JsonPath query to extract the value. And with JsonSurfer which is backed by Gson, your problem can be solved by simply two line of code!

        JsonSurfer jsonSurfer = JsonSurfer.gson();
        String result = jsonSurfer.collectOne(jsonLine, String.class, "$.data.translations[0].translatedText");
    

    Node.js Logging

    You can also use npmlog by issacs, recommended in https://npmjs.org/doc/coding-style.html.

    You can find this module here https://github.com/isaacs/npmlog

    Best way to integrate Python and JavaScript?

    PyExecJS is able to use each of PyV8, Node, JavaScriptCore, SpiderMonkey, JScript.

    >>> import execjs
    >>> execjs.eval("'red yellow blue'.split(' ')")
    ['red', 'yellow', 'blue']
    >>> execjs.get().name
    'Node.js (V8)'
    

    -XX:MaxPermSize with or without -XX:PermSize

    -XX:PermSize specifies the initial size that will be allocated during startup of the JVM. If necessary, the JVM will allocate up to -XX:MaxPermSize.

    How to urlencode data for curl command?

    The following is based on Orwellophile's answer, but solves the multibyte bug mentioned in the comments by setting LC_ALL=C (a trick from vte.sh). I've written it in the form of function suitable PROMPT_COMMAND, because that's how I use it.

    print_path_url() {
      local LC_ALL=C
      local string="$PWD"
      local strlen=${#string}
      local encoded=""
      local pos c o
    
      for (( pos=0 ; pos<strlen ; pos++ )); do
         c=${string:$pos:1}
         case "$c" in
            [-_.~a-zA-Z0-9/] ) o="${c}" ;;
            * )               printf -v o '%%%02x' "'$c"
         esac
         encoded+="${o}"
      done
      printf "\033]7;file://%s%s\007" "${HOSTNAME:-}" "${encoded}"
    }
    

    Build tree array from flat array in javascript

    You can use this "treeify" package from Github here or NPM.

    Installation:

    $ npm install --save-dev treeify-js

    How to create empty data frame with column names specified in R?

    Just create a data.frame with 0 length variables

    eg

    nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
    str(nodata)
    
    ## 'data.frame':    0 obs. of  3 variables:
    ##  $ x: num 
    ##  $ y: int 
    ##  $ z: Factor w/ 0 levels: 
    

    or to create a data.frame with 5 columns named a,b,c,d,e

    nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))
    

    Remove NaN from pandas series

    >>> s = pd.Series([1,2,3,4,np.NaN,5,np.NaN])
    >>> s[~s.isnull()]
    0    1
    1    2
    2    3
    3    4
    5    5
    

    update or even better approach as @DSM suggested in comments, using pandas.Series.dropna():

    >>> s.dropna()
    0    1
    1    2
    2    3
    3    4
    5    5
    

    Bootstrap 4 Dropdown Menu not working?

    Via JavaScript Call the dropdowns via JavaScript:

    Paste this is code after bootstrap.min.js

    $('.dropdown-toggle').dropdown();

    Also, make sure you include popper.min.js before bootstrap.min.js

    Dropdowns are positioned thanks to Popper.js (except when they are contained in a navbar).

    Angularjs - simple form submit

    I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:

    Angularjs - Form Post Data Not Posted?

    The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.

    How to validate an e-mail address in swift?

    For anyone who is still looking for an answer to this, please have a look at the following framework;

    ATGValidator

    It is a rule based validation framework, which handles most of the validations out of box. And top it all, it has form validator which supports validation of multiple textfields at the same time.

    For validating an email string, use the following;

    "[email protected]".satisfyAll(rules: [StringRegexRule.email]).status
    

    If you want to validate an email from textfield, try below code;

    textfield.validationRules = [StringRegexRule.email]
    textfield.validationHandler = { result in
        // This block will be executed with relevant result whenever validation is done.
        print(result.status, result.errors)
    }
    // Below line is to manually trigger validation.
    textfield.validateTextField()
    

    If you want to validate it while typing in textfield or when focus is changed to another field, add one of the following lines;

    textfield.validateOnInputChange(true)
    // or
    textfield.validateOnFocusLoss(true)
    

    Please check the readme file at the link for more use cases.

    Using Spring 3 autowire in a standalone Java application

    For Spring 4, using Spring Boot we can have the following example without using the anti-pattern of getting the Bean from the ApplicationContext directly:

    package com.yourproject;
    
    @SpringBootApplication
    public class TestBed implements CommandLineRunner {
    
        private MyService myService;
    
        @Autowired
        public TestBed(MyService myService){
            this.myService = myService;
        }
    
        public static void main(String... args) {
            SpringApplication.run(TestBed.class, args);
        }
    
        @Override
        public void run(String... strings) throws Exception {
            System.out.println("myService: " + MyService );
        }
    
    }
    
    @Service 
    public class MyService{
        public String getSomething() {
            return "something";
        }
    }
    

    Make sure that all your injected services are under com.yourproject or its subpackages.

    Count(*) vs Count(1) - SQL Server

    COUNT(*) and COUNT(1) are same in case of result and performance.

    XCOPY: Overwrite all without prompt in BATCH

    The solution is the /Y switch:

    xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y
    

    How to get the size of a JavaScript object?

    If your main concern is the memory usage of your Firefox extension, I suggest checking with Mozilla developers.

    Mozilla provides on its wiki a list of tools to analyze memory leaks.

    SQL Query to concatenate column values from multiple rows in Oracle

    There are a few ways depending on what version you have - see the oracle documentation on string aggregation techniques. A very common one is to use LISTAGG:

    SELECT pid, LISTAGG(Desc, ' ') WITHIN GROUP (ORDER BY seq) AS description
    FROM B GROUP BY pid;
    

    Then join to A to pick out the pids you want.

    Note: Out of the box, LISTAGG only works correctly with VARCHAR2 columns.

    Web API optional parameters

    Sku is an int, can't be defaulted to string "sku". Please check Optional URI Parameters and Default Values

    I just assigned a variable, but echo $variable shows something else

    In all of the cases above, the variable is correctly set, but not correctly read! The right way is to use double quotes when referencing:

    echo "$var"
    

    This gives the expected value in all the examples given. Always quote variable references!


    Why?

    When a variable is unquoted, it will:

    1. Undergo field splitting where the value is split into multiple words on whitespace (by default):

      Before: /* Foobar is free software */

      After: /*, Foobar, is, free, software, */

    2. Each of these words will undergo pathname expansion, where patterns are expanded into matching files:

      Before: /*

      After: /bin, /boot, /dev, /etc, /home, ...

    3. Finally, all the arguments are passed to echo, which writes them out separated by single spaces, giving

      /bin /boot /dev /etc /home Foobar is free software Desktop/ Downloads/
      

      instead of the variable's value.

    When the variable is quoted it will:

    1. Be substituted for its value.
    2. There is no step 2.

    This is why you should always quote all variable references, unless you specifically require word splitting and pathname expansion. Tools like shellcheck are there to help, and will warn about missing quotes in all the cases above.

    Can I update a JSF component from a JSF backing bean method?

    Using standard JSF API, add the client ID to PartialViewContext#getRenderIds().

    FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add("foo:bar");
    

    Using PrimeFaces specific API, use PrimeFaces.Ajax#update().

    PrimeFaces.current().ajax().update("foo:bar");
    

    Or if you're not on PrimeFaces 6.2+ yet, use RequestContext#update().

    RequestContext.getCurrentInstance().update("foo:bar");
    

    If you happen to use JSF utility library OmniFaces, use Ajax#update().

    Ajax.update("foo:bar");
    

    Regardless of the way, note that those client IDs should represent absolute client IDs which are not prefixed with the NamingContainer separator character like as you would do from the view side on.

    Set background image in CSS using jquery

    Use :

     $(this).parent().css("background-image", "url(/images/r-srchbg_white.png) no-repeat;");
    

    instead of

     $(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat;");
    

    More examples you cand see here

    Is key-value observation (KVO) available in Swift?

    Both yes and no:

    • Yes, you can use the same old KVO APIs in Swift to observe Objective-C objects.
      You can also observe dynamic properties of Swift objects inheriting from NSObject.
      But... No it's not strongly typed as you could expect Swift native observation system to be.
      Using Swift with Cocoa and Objective-C | Key Value Observing

    • No, currently there is no builtin value observation system for arbitrary Swift objects.

    • Yes, there are builtin Property Observers, which are strongly typed.
      But... No they are not KVO, since they allow only for observing of objects own properties, don't support nested observations ("key paths"), and you have to explicitly implement them.
      The Swift Programming Language | Property Observers

    • Yes, you can implement explicit value observing, which will be strongly typed, and allow for adding multiple handlers from other objects, and even support nesting / "key paths".
      But... No it will not be KVO since it will only work for properties which you implement as observable.
      You can find a library for implementing such value observing here:
      Observable-Swift - KVO for Swift - Value Observing and Events

    how to display progress while loading a url to webview in android?

    set a WebViewClient to your WebView, start your progress dialog on you onCreate() method an dismiss it when the page has finished loading in onPageFinished(WebView view, String url)

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Window;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.Toast;
    
    public class Main extends Activity {
        private WebView webview;
        private static final String TAG = "Main";
        private ProgressDialog progressBar;  
    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            requestWindowFeature(Window.FEATURE_NO_TITLE);
    
            setContentView(R.layout.main);
    
            this.webview = (WebView)findViewById(R.id.webview);
    
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    
            final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    
            progressBar = ProgressDialog.show(Main.this, "WebView Example", "Loading...");
    
            webview.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    Log.i(TAG, "Processing webview url click...");
                    view.loadUrl(url);
                    return true;
                }
    
                public void onPageFinished(WebView view, String url) {
                    Log.i(TAG, "Finished loading URL: " +url);
                    if (progressBar.isShowing()) {
                        progressBar.dismiss();
                    }
                }
    
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    Log.e(TAG, "Error: " + description);
                    Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
                    alertDialog.setTitle("Error");
                    alertDialog.setMessage(description);
                    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            return;
                        }
                    });
                    alertDialog.show();
                }
            });
            webview.loadUrl("http://www.google.com");
        }
    }
    

    your main.xml layout

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
        <WebView android:id="@string/webview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" />
    </LinearLayout>
    

    Using Lato fonts in my css (@font-face)

    Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

    (I don't see anything obviously wrong with the code you have posted above)

    Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

    How to print a single backslash?

    You need to escape your backslash by preceding it with, yes, another backslash:

    print("\\")
    

    And for versions prior to Python 3:

    print "\\"
    

    The \ character is called an escape character, which interprets the character following it differently. For example, n by itself is simply a letter, but when you precede it with a backslash, it becomes \n, which is the newline character.

    As you can probably guess, \ also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.

    See the Python 3 documentation for string literals.

    Get installed applications in a system

    Your best bet is to use WMI. Specifically the Win32_Product class.

    Eclipse - Failed to create the java virtual machine

    You can do a workaround as below:

    Create a shortcut for eclipse and right click on the short cut and go to properties of the shortcut.

    In the target box update the string:

    -vm "C:\Program Files\Java\jdk1.6.0_07\bin"
    

    the path will change according to your java installed directory.

    So after changing the target string will be something like below.

    D:\adt-bundle-windows-x86-20131030\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.6.0_07\bin"
    

    Click apply and try clicking the Eclipse shortcut.

    Testing if a site is vulnerable to Sql Injection

    The easiest way to protect yourself is to use stored procedures instead of inline SQL statements.

    Then use "least privilege" permissions and only allow access to stored procedures and not directly to tables.

    How do I remove a file from the FileList

    If you want to delete only several of the selected files: you can't. The File API Working Draft you linked to contains a note:

    The HTMLInputElement interface [HTML5] has a readonly FileList attribute, […]
    [emphasis mine]

    Reading a bit of the HTML 5 Working Draft, I came across the Common input element APIs. It appears you can delete the entire file list by setting the value property of the input object to an empty string, like:

    document.getElementById('multifile').value = "";
    

    BTW, the article Using files from web applications might also be of interest.