Programs & Examples On #Long filenames

How to add a string to a string[] array? There's no .Add function

If I'm not mistaken it is:

MyArray.SetValue(ArrayElement, PositionInArray)

Python: OSError: [Errno 2] No such file or directory: ''

I had this error because I was providing a string of arguments to subprocess.call instead of an array of arguments. To prevent this, use shlex.split:

import shlex, subprocess
command_line = "ls -a"
args = shlex.split(command_line)
p = subprocess.Popen(args)

Oracle PL/SQL string compare issue

To fix the core question, "how should I detect that these two variables don't have the same value when one of them is null?", I don't like the approach of nvl(my_column, 'some value that will never, ever, ever appear in the data and I can be absolutely sure of that') because you can't always guarantee that a value won't appear... especially with NUMBERs.

I have used the following:

if (str1 is null) <> (str2 is null) or str1 <> str2 then
  dbms_output.put_line('not equal');
end if;

Disclaimer: I am not an Oracle wizard and I came up with this one myself and have not seen it elsewhere, so there may be some subtle reason why it's a bad idea. But it does avoid the trap mentioned by APC, that comparing a null to something else gives neither TRUE nor FALSE but NULL. Because the clauses (str1 is null) will always return TRUE or FALSE, never null.

(Note that PL/SQL performs short-circuit evaluation, as noted here.)

How to align checkboxes and their labels consistently cross-browsers

Working off of One Crayon's solution, I have something that works for me and is simpler:

_x000D_
_x000D_
.font2 {font-family:Arial; font-size:32px} /* Sample font */_x000D_
_x000D_
input[type=checkbox], input[type=radio] {_x000D_
  vertical-align: middle;_x000D_
  position: relative;_x000D_
  bottom: 1px;_x000D_
}_x000D_
_x000D_
input[type=radio] { _x000D_
  bottom: 2px; _x000D_
} 
_x000D_
<label><input type="checkbox" /> Label text</label>_x000D_
<p class="font2">_x000D_
  <label><input type="checkbox"/> Label text</label>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Renders pixel-for-pixel the same in Safari (whose baseline I trust) and both Firefox and IE7 check out as good. It also works for various label font sizes, big and small. Now, for fixing IE's baseline on selects and inputs...


Update: (Third-Party Edit)

The proper bottom position depends on font-family and font-size! I found using bottom: .08em; for checkbox & radio elements is a good general value. I tested it in Chrome/Firefox/IE11 in windows with Arial & Calibri fonts using several small/mid/large font-sizes.

_x000D_
_x000D_
.font2, .font2 input {font-family:Arial; font-size:32px} /* Sample font */_x000D_
_x000D_
input[type=checkbox], input[type=radio] {_x000D_
  vertical-align: middle; _x000D_
  position: relative;_x000D_
  bottom: .08em; /* this is a better value for different fonts! */_x000D_
}
_x000D_
<label><input type="checkbox" /> Label text</label> _x000D_
_x000D_
<p class="font2">_x000D_
  <label><input type="checkbox"/> Label text</label>_x000D_
</p>
_x000D_
_x000D_
_x000D_

How to store JSON object in SQLite database

https://github.com/requery/sqlite-android allows you to query JSON fields (and arrays in them, I've tried it and am using it). Before that I was just storing JSON strings into a TEXT column. It supports FTS3, FTS4, & JSON1

As of July 2019, it still gets version bumps every now and then, so it isn't a dead project.

adding 30 minutes to datetime php/mysql

Dominc has the right idea, but put the calculation on the other side of the expression.

SELECT * FROM my_table WHERE endTime < DATE_SUB(CONVERT_TZ(NOW(), @@global.time_zone, 'GMT'), INTERVAL 30 MINUTE)

This has the advantage that you're doing the 30 minute calculation once instead of on every row. That also means MySQL can use the index on that column. Both of thse give you a speedup.

Get Cell Value from Excel Sheet with Apache Poi

May be by:-

    for(Row row : sheet) {          
        for(Cell cell : row) {              
            System.out.print(cell.getStringCellValue());

        }
    }       

For specific type of cell you can try:

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
    cellValue = cell.getStringCellValue();
    break;

case Cell.CELL_TYPE_FORMULA:
    cellValue = cell.getCellFormula();
    break;

case Cell.CELL_TYPE_NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
        cellValue = cell.getDateCellValue().toString();
    } else {
        cellValue = Double.toString(cell.getNumericCellValue());
    }
    break;

case Cell.CELL_TYPE_BLANK:
    cellValue = "";
    break;

case Cell.CELL_TYPE_BOOLEAN:
    cellValue = Boolean.toString(cell.getBooleanCellValue());
    break;

}

Run a command shell in jenkins

Error shows that script does not exists

The file does not exists. check your full path

C:\Windows\TEMP\hudson6299483223982766034.sh
The system cannot find the file specified

Moreover, to launch .sh scripts into windows, you need to have CYGWIN installed and well configured into your path

Confirm that script exists.

Into jenkins script, do the following to confirm that you do have the file

cd C:\Windows\TEMP\
ls -rtl
sh -xe hudson6299483223982766034.sh

Convert list to tuple in Python

It should work fine. Don't use tuple, list or other special names as a variable name. It's probably what's causing your problem.

>>> l = [4,5,6]
>>> tuple(l)
(4, 5, 6)

>>> tuple = 'whoops'   # Don't do this
>>> tuple(l)
TypeError: 'tuple' object is not callable

How to navigate to a directory in C:\ with Cygwin?

You can just use

cd C:/Users/../..

How does it work - requestLocationUpdates() + LocationRequest/Listener

You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:

mLocationClient.requestLocationUpdates(mLocationRequest, this);

Be sure that the LocationListener you're implementing is from the google api, that is import this:

import com.google.android.gms.location.LocationListener;

and not this:

import android.location.LocationListener;

and it should work just fine.

It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html

python: restarting a loop

Just wanted to post an alternative which might be more genearally usable. Most of the existing solutions use a loop index to avoid this. But you don't have to use an index - the key here is that unlike a for loop, where the loop variable is hidden, the loop variable is exposed.

You can do very similar things with iterators/generators:

x = [1,2,3,4,5,6]
xi = iter(x)
ival = xi.next()
while not exit_condition(ival):
    # Do some ival stuff
    if ival == 4:
        xi = iter(x)
    ival = xi.next()

It's not as clean, but still retains the ability to write to the loop iterator itself.

Usually, when you think you want to do this, your algorithm is wrong, and you should rewrite it more cleanly. Probably what you really want to do is use a generator/coroutine instead. But it is at least possible.

How to use XPath contains() here?

Paste my contains example here:

//table[contains(@class, "EC_result")]/tbody

How to establish ssh key pair when "Host key verification failed"

Most likely, the remote host ip or ip_alias is not in the ~/.ssh/known_hosts file. You can use the following command to add the host name to known_hosts file.

$ssh-keyscan -H -t rsa ip_or_ipalias >> ~/.ssh/known_hosts

Also, I have generated the following script to check if the particular ip or ipalias is in the know_hosts file.

#!/bin/bash
#Jason Xiong: Dec 2013   
# The ip or ipalias stored in known_hosts file is hashed and   
# is not human readable.This script check if the supplied ip    
# or ipalias exists in ~/.ssh/known_hosts file

if [[ $# != 2 ]]; then
   echo "Usage: ./search_known_hosts -i ip_or_ipalias"
   exit;
fi
ip_or_alias=$2;
known_host_file=/home/user/.ssh/known_hosts
entry=1;

cat $known_host_file | while read -r line;do
  if [[ -z "$line" ]]; then
    continue;
  fi   
  hash_type=$(echo $line | sed -e 's/|/ /g'| awk '{print $1}'); 
  key=$(echo $line | sed -e 's/|/ /g'| awk '{print $2}');
  stored_value=$(echo $line | sed -e 's/|/ /g'| awk '{print $3}'); 
  hex_key=$(echo $key | base64 -d | xxd -p); 
  if  [[ $hash_type = 1 ]]; then      
     gen_value=$(echo -n $ip_or_alias | openssl sha1 -mac HMAC \
         -macopt hexkey:$hex_key | cut -c 10-49 | xxd -r -p | base64);     
     if [[ $gen_value = $stored_value ]]; then
       echo $gen_value;
       echo "Found match in known_hosts file : entry#"$entry" !!!!"
     fi
  else
     echo "unknown hash_type"
  fi
  entry=$((entry + 1));
done

Windows 10 SSH keys

If you have Windows 10 with the OpenSSH client you may be able to generate the key, but you will have trouble copying it to the target Linux box as the ssh-copy-id command is not part of the client toolset.

Having has this problem I wrote a small PowerShell function to address this, that you add to your profile.

function ssh-copy-id([string]$userAtMachine, [string]$port = 22) {   
    # Get the generated public key
    $key = "$ENV:USERPROFILE" + "/.ssh/id_rsa.pub"
    # Verify that it exists
    if (!(Test-Path "$key")) {
        # Alert user
        Write-Error "ERROR: '$key' does not exist!"            
    }
    else {  
        # Copy the public key across
        & cat "$key" | ssh $userAtMachine -p $port "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys || exit 1"      
    }
}

You can get the gist here

I have a brief write up about it here

How to find the .NET framework version of a Visual Studio project?

You can't change the targeted version of either Windows or the .NET Framework if you create your project in Visual Studio 2013. That option is not available anymore.

Look that link from Microsoft: http://msdn.microsoft.com/en-us/library/bb398202.aspx

The model backing the 'ApplicationDbContext' context has changed since the database was created

It was such a strange error,, It wasn't my error at the end, it was Microsoft's,, I installed the Entity framework the " pre-release" version and it was responsible for this error,, when i upgraded to the stable release it disapperared,, thank you everyone believe me when i asked this question i searched like for a week or so for its solution so i am pretty sure that this problem isn't anywhere else : the version of entity framework.dll that caused the problem was 6.0.2 if it helps.

line breaks in a textarea

<?php
$smarty = new Smarty;
$smarty->assign('test', "This is a \n Test");
$smarty->display('index.tpl');
?>

In index.tpl

{$test|nl2br}

In HTML

This is a<br />
test

How do you get the current page number of a ViewPager for Android?

You will figure out that setOnPageChangeListener is deprecated, use addOnPageChangeListener, as below:

ViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
       if(position == 1){  // if you want the second page, for example
           //Your code here
       }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
});

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

How is Perl's @INC constructed? (aka What are all the ways of affecting where Perl modules are searched for?)

As it was said already @INC is an array and you're free to add anything you want.

My CGI REST script looks like:

#!/usr/bin/perl
use strict;
use warnings;
BEGIN {
    push @INC, 'fully_qualified_path_to_module_wiht_our_REST.pm';
}
use Modules::Rest;
gone(@_);

Subroutine gone is exported by Rest.pm.

Populating a dictionary using for loops (python)

dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
        dicts[i] = values[i]
print(dicts)

alternatively

In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

Maximum length of the textual representation of an IPv6 address?

45 characters.

You might expect an address to be

0000:0000:0000:0000:0000:0000:0000:0000

8 * 4 + 7 = 39

8 groups of 4 digits with 7 : between them.

But if you have an IPv4-mapped IPv6 address, the last two groups can be written in base 10 separated by ., eg. [::ffff:192.168.100.228]. Written out fully:

0000:0000:0000:0000:0000:ffff:192.168.100.228

(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = 45

Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. [0000:0000:0000:0000:0000:ffff:c0a8:64e4] for the address above.

How to install node.js as windows service?

I found the thing so useful that I built an even easier to use wrapper around it (npm, github).

Installing it:

npm install -g qckwinsvc

Installing your service:

qckwinsvc

prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed

Uninstalling your service:

qckwinsvc --uninstall

prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled

How to check if an object is an array?

I have updated the jsperf fiddle with two alternative methods as well as error checking.

It turns out that the method defining a constant value in the 'Object' and 'Array' prototypes is faster than any of the other methods. It is a somewhat surprising result.

_x000D_
_x000D_
/* Initialisation */_x000D_
Object.prototype.isArray = function() {_x000D_
  return false;_x000D_
};_x000D_
Array.prototype.isArray = function() {_x000D_
  return true;_x000D_
};_x000D_
Object.prototype._isArray = false;_x000D_
Array.prototype._isArray = true;_x000D_
_x000D_
var arr = ["1", "2"];_x000D_
var noarr = "1";_x000D_
_x000D_
/* Method 1 (function) */_x000D_
if (arr.isArray()) document.write("arr is an array according to function<br/>");_x000D_
if (!noarr.isArray()) document.write("noarr is not an array according to function<br/>");_x000D_
/* Method 2 (value) - **** FASTEST ***** */_x000D_
if (arr._isArray) document.write("arr is an array according to member value<br/>");_x000D_
if (!noarr._isArray) document.write("noarr is not an array according to member value<br/>");
_x000D_
_x000D_
_x000D_

These two methods do not work if the variable takes the undefined value, but they do work if you are certain that they have a value. With regards to checking with performance in mind if a value is an array or a single value, the second method looks like a valid fast method. It is slightly faster than 'instanceof' on Chrome, twice as fast as the second best method in Internet Explorer, Opera and Safari (on my machine).

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

There are many ways to scroll up and down in Selenium Webdriver I always use Java Script to do the same.

Below is the code which always works for me if I want to scroll up or down

 // This  will scroll page 400 pixel vertical
  ((JavascriptExecutor)driver).executeScript("scroll(0,400)");

You can get full code from here Scroll Page in Selenium

If you want to scroll for a element then below piece of code will work for you.

je.executeScript("arguments[0].scrollIntoView(true);",element);

You will get the full doc here Scroll for specific Element

Why is char[] preferred over String for passwords?

To quote an official document, the Java Cryptography Architecture guide says this about char[] vs. String passwords (about password-based encryption, but this is more generally about passwords of course):

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

Guideline 2-2 of the Secure Coding Guidelines for the Java Programming Language, Version 4.0 also says something similar (although it is originally in the context of logging):

Guideline 2-2: Do not log highly sensitive information

Some information, such as Social Security numbers (SSNs) and passwords, is highly sensitive. This information should not be kept for longer than necessary nor where it may be seen, even by administrators. For instance, it should not be sent to log files and its presence should not be detectable through searches. Some transient data may be kept in mutable data structures, such as char arrays, and cleared immediately after use. Clearing data structures has reduced effectiveness on typical Java runtime systems as objects are moved in memory transparently to the programmer.

This guideline also has implications for implementation and use of lower-level libraries that do not have semantic knowledge of the data they are dealing with. As an example, a low-level string parsing library may log the text it works on. An application may parse an SSN with the library. This creates a situation where the SSNs are available to administrators with access to the log files.

Razor View Engine : An expression tree may not contain a dynamic operation

Seems like your view is typed dynamic. Set the right type on the view and you'll see the error go away.

PHP: Update multiple MySQL fields in single query

Comma separate the values:

UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"

Should I use @EJB or @Inject

Update: This answer may be incorrect or out of date. Please see comments for details.

I switched from @Inject to @EJB because @EJB allows circular injection whereas @Inject pukes on it.

Details: I needed @PostConstruct to call an @Asynchronous method but it would do so synchronously. The only way to make the asynchronous call was to have the original call a method of another bean and have it call back the method of the original bean. To do this each bean needed a reference to the other -- thus circular. @Inject failed for this task whereas @EJB worked.

Assign one struct to another in C

Yes if the structure is of the same type. Think it as a memory copy.

How to access session variables from any class in ASP.NET?

In asp.net core this works differerently:

public class SomeOtherClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private ISession _session => _httpContextAccessor.HttpContext.Session;

    public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void TestSet()
    {
        _session.SetString("Test", "Ben Rules!");
    }

    public void TestGet()
    {
        var message = _session.GetString("Test");
    }
}

Source: https://benjii.me/2016/07/using-sessions-and-httpcontext-in-aspnetcore-and-mvc-core/

ArrayList vs List<> in C#

To add to the above points. Using ArrayList in 64bit operating system takes 2x memory than using in the 32bit operating system. Meanwhile, generic list List<T> will use much low memory than the ArrayList.

for example if we use a ArrayList of 19MB in 32-bit it would take 39MB in the 64-bit. But if you have a generic list List<int> of 8MB in 32-bit it would take only 8.1MB in 64-bit, which is a whooping 481% difference when compared to ArrayList.

Source: ArrayList’s vs. generic List for primitive types and 64-bits

rawQuery(query, selectionArgs)

Maybe this can help you

Cursor c = db.rawQuery("query",null);
int id[] = new int[c.getCount()];
int i = 0;
if (c.getCount() > 0) 
{               
    c.moveToFirst();
    do {
        id[i] = c.getInt(c.getColumnIndex("field_name"));
        i++;
    } while (c.moveToNext());
    c.close();
}

Convert string to JSON Object

try:

var myjson = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var newJ= $.parseJSON(myjson);
    alert(newJ.TeamList[0].teamname);

input type=file show only button

Another easy way of doing this. Make a "input type file" tag in html and hide it. Then click a button and format it according to need. After this use javascript/jquery to programmatically click the input tag when the button is clicked.

HTML :-

<input id="file" type="file" style="display: none;">
<button id="button">Add file</button>

JavaScript :-

document.getElementById('button').addEventListener("click", function() {
    document.getElementById('file').click();
});

jQuery :-

$('#button').click(function(){
    $('#file').click();
});

CSS :-

#button
{
    background-color: blue;
    color: white;
}

Here is a working JS fiddle for the same :- http://jsfiddle.net/32na3/

How do I get ruby to print a full backtrace instead of a truncated one?

Exception#backtrace has the entire stack in it:

def do_division_by_zero; 5 / 0; end
begin
  do_division_by_zero
rescue => exception
  puts exception.backtrace
  raise # always reraise
end

(Inspired by Peter Cooper's Ruby Inside blog)

Mocking static methods with Mockito

To mock static method you should use a Powermock look at: https://github.com/powermock/powermock/wiki/MockStatic. Mockito doesn't provide this functionality.

You can read nice a article about mockito: http://refcardz.dzone.com/refcardz/mockito

About "*.d.ts" in TypeScript

Like @takeshin said .d stands for declaration file for typescript (.ts).

Few points to be clarified before proceeding to answer this post -

  1. Typescript is syntactic superset of javascript.
  2. Typescript doesn't run on its own, it needs to be transpiled into javascript (typescript to javascript conversion)
  3. "Type definition" and "Type checking" are major add-on functionalities that typescript provides over javascript. (check difference between type script and javascript)

If you are thinking if typescript is just syntactic superset, what benefits does it offer - https://basarat.gitbooks.io/typescript/docs/why-typescript.html#the-typescript-type-system

To Answer this post -

As we discussed, typescript is superset of javascript and needs to be transpiled into javascript. So if a library or third party code is written in typescript, it eventually gets converted to javascript which can be used by javascript project but vice versa does not hold true.

For ex -

If you install javascript library -

npm install --save mylib

and try importing it in typescript code -

import * from "mylib";

you will get error.

"Cannot find module 'mylib'."

As mentioned by @Chris, many libraries like underscore, Jquery are already written in javascript. Rather than re-writing those libraries for typescript projects, an alternate solution was needed.

In order to do this, you can provide type declaration file in javascript library named as *.d.ts, like in above case mylib.d.ts. Declaration file only provides type declarations of functions and variables defined in respective javascript file.

Now when you try -

import * from "mylib";

mylib.d.ts gets imported which acts as an interface between javascript library code and typescript project.

How to get a MemoryStream from a Stream in .NET?

I use this combination of extension methods:

    public static Stream Copy(this Stream source)
    {
        if (source == null)
            return null;

        long originalPosition = -1;

        if (source.CanSeek)
            originalPosition = source.Position;

        MemoryStream ms = new MemoryStream();

        try
        {
            Copy(source, ms);

            if (originalPosition > -1)
                ms.Seek(originalPosition, SeekOrigin.Begin);
            else
                ms.Seek(0, SeekOrigin.Begin);

            return ms;
        }
        catch
        {
            ms.Dispose();
            throw;
        }
    }

    public static void Copy(this Stream source, Stream target)
    {
        if (source == null)
            throw new ArgumentNullException("source");
        if (target == null)
            throw new ArgumentNullException("target");

        long originalSourcePosition = -1;
        int count = 0;
        byte[] buffer = new byte[0x1000];

        if (source.CanSeek)
        {
            originalSourcePosition = source.Position;
            source.Seek(0, SeekOrigin.Begin);
        }

        while ((count = source.Read(buffer, 0, buffer.Length)) > 0)
            target.Write(buffer, 0, count);

        if (originalSourcePosition > -1)
        {
            source.Seek(originalSourcePosition, SeekOrigin.Begin);
        }
    }

python: [Errno 10054] An existing connection was forcibly closed by the remote host

For me this problem arised while trying to connect to the SAP Hana database. When I got this error,

OperationalError: Lost connection to HANA server (ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

I tried to run the code for connection(mentioned below), which created that error, again and it worked.


    import pyhdb
    connection = pyhdb.connect(host="example.com",port=30015,user="user",password="secret")
    cursor = connection.cursor()
    cursor.execute("SELECT 'Hello Python World' FROM DUMMY")
    cursor.fetchone()
    connection.close()

It was because the server refused to connect. It might require you to wait for a while and try again. Try closing the Hana Studio by logging off and then logging in again. Keep running the code for a number of times.

Android studio - Failed to find target android-18

I've had a similar problem occurr when I had both Eclipse, Android Studio and the standalone Android SDK installed (the problem lied where the AVD Manager couldn't find target images). I had been using Eclipse for Android development but have moved over to Android Studio, and quickly found that Android Studio couldn't find my previously created AVDs.

The problem could potentially lie in that Android Studio is looking at it's own Android SDK (found in C:\Users\username\AppData\Local\Android\android-studio\sdk) and not a previously installed standalone SDK, which I had installed at C:\adt\sdk.

Renaming Android Studio's SDK folder, in C:\Users... (only rename it, just in case things break) then creating a symbolic link between the Android Studio SDK location and a standalone Android SDK fixes this issue.

I also used the Link Shell Extension (http://schinagl.priv.at/nt/hardlinkshellext/linkshellextension.html) just to take the tedium out of creating symbolic links.

What is the difference between git clone and checkout?

Simply git checkout have 2 uses

  1. Switching between existing local branches like git checkout <existing_local_branch_name>
  2. Create a new branch from current branch using flag -b. Suppose if you are at master branch then git checkout -b <new_feature_branch_name> will create a new branch with the contents of master and switch to newly created branch

You can find more options at the official site

How to use jquery $.post() method to submit form values

You have to select and send the form data as well:

$("#post-btn").click(function(){        
    $.post("process.php", $("#reg-form").serialize(), function(data) {
        alert(data);
    });
});

Take a look at the documentation for the jQuery serialize method, which encodes the data from the form fields into a data-string to be sent to the server.

Convert Array to Object

_x000D_
_x000D_
let i = 0;_x000D_
let myArray = ["first", "second", "third", "fourth"];_x000D_
_x000D_
const arrayToObject = (arr) =>_x000D_
    Object.assign({}, ...arr.map(item => ({[i++]: item})));_x000D_
_x000D_
console.log(arrayToObject(myArray));
_x000D_
_x000D_
_x000D_

Or use

_x000D_
_x000D_
myArray = ["first", "second", "third", "fourth"]_x000D_
console.log({...myArray})
_x000D_
_x000D_
_x000D_

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

Reload nginx configuration

Maybe you're not doing it as root?

Try sudo nginx -s reload, if it still doesn't work, you might want to try sudo pkill -HUP nginx.

Alter Table Add Column Syntax

Just remove COLUMN from ADD COLUMN

ALTER TABLE Employees
  ADD EmployeeID numeric NOT NULL IDENTITY (1, 1)

ALTER TABLE Employees ADD CONSTRAINT
        PK_Employees PRIMARY KEY CLUSTERED 
        (
          EmployeeID
        ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
        ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

Select top 2 rows in Hive

Yes, here you can use LIMIT.

You can try it by the below query:

SELECT * FROM employee_list SORT BY salary DESC LIMIT 2

Simple calculations for working with lat/lon and km distance?

If you're using Java, Javascript or PHP, then there's a library that will do these calculations exactly, using some amusingly complicated (but still fast) trigonometry:

http://www.jstott.me.uk/jcoord/

How to print the array?

There is no .length property in C. The .length property can only be applied to arrays in object oriented programming (OOP) languages. The .length property is inherited from the object class; the class all other classes & objects inherit from in an OOP language. Also, one would use .length-1 to return the number of the last index in an array; using just the .length will return the total length of the array.

I would suggest something like this:

int index;
int jdex;
for( index = 0; index < (sizeof( my_array ) / sizeof( my_array[0] )); index++){
   for( jdex = 0; jdex < (sizeof( my_array ) / sizeof( my_array[0] )); jdex++){
        printf( "%d", my_array[index][jdex] );
        printf( "\n" );
   }
}

The line (sizeof( my_array ) / sizeof( my_array[0] )) will give you the size of the array in question. The sizeof property will return the length in bytes, so one must divide the total size of the array in bytes by how many bytes make up each element, each element takes up 4 bytes because each element is of type int, respectively. The array is of total size 16 bytes and each element is of 4 bytes so 16/4 yields 4 the total number of elements in your array because indexing starts at 0 and not 1.

How to get a complete list of object's methods and attributes?

Only to supplement:

  1. dir() is the most powerful/fundamental tool. (Most recommended)
  2. Solutions other than dir() merely provide their way of dealing the output of dir().

    Listing 2nd level attributes or not, it is important to do the sifting by yourself, because sometimes you may want to sift out internal vars with leading underscores __, but sometimes you may well need the __doc__ doc-string.

  3. __dir__() and dir() returns identical content.
  4. __dict__ and dir() are different. __dict__ returns incomplete content.
  5. IMPORTANT: __dir__() can be sometimes overwritten with a function, value or type, by the author for whatever purpose.

    Here is an example:

    \\...\\torchfun.py in traverse(self, mod, search_attributes)
    445             if prefix in traversed_mod_names:
    446                 continue
    447             names = dir(m)
    448             for name in names:
    449                 obj = getattr(m,name)
    

    TypeError: descriptor __dir__ of 'object' object needs an argument

    The author of PyTorch modified the __dir__() method to something that requires an argument. This modification makes dir() fail.

  6. If you want a reliable scheme to traverse all attributes of an object, do remember that every pythonic standard can be overridden and may not hold, and every convention may be unreliable.

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:

Subject: Claiming (?P...) regex syntax extensions

From: Guido van Rossum ([email protected])

Date: Dec 10, 1997 3:36:19 pm

I have an unusual request for the Perl developers (those that develop the Perl language). I hope this (perl5-porters) is the right list. I am cc'ing the Python string-sig because it is the origin of most of the work I'm discussing here.

You are probably aware of Python. I am Python's creator; I am planning to release a next "major" version, Python 1.5, by the end of this year. I hope that Python and Perl can co-exist in years to come; cross-pollination can be good for both languages. (I believe Larry had a good look at Python when he added objects to Perl 5; O'Reilly publishes books about both languages.)

As you may know, Python 1.5 adds a new regular expression module that more closely matches Perl's syntax. We've tried to be as close to the Perl syntax as possible within Python's syntax. However, the regex syntax has some Python-specific extensions, which all begin with (?P . Currently there are two of them:

(?P<foo>...) Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed, via the symbolic group name "foo".

(?P=foo) Matches the same string as that matched by the group named "foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.

I hope that this Python-specific extension won't conflict with any future Perl extensions to the Perl regex syntax. If you have plans to use (?P, please let us know as soon as possible so we can resolve the conflict. Otherwise, it would be nice if the (?P syntax could be permanently reserved for Python-specific syntax extensions. (Is there some kind of registry of extensions?)

to which Larry Wall replied:

[...] There's no registry as of now--yours is the first request from outside perl5-porters, so it's a pretty low-bandwidth activity. (Sorry it was even lower last week--I was off in New York at Internet World.)

Anyway, as far as I'm concerned, you may certainly have 'P' with my blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]

So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.

Android failed to load JS bundle

The following made it work for me on Ubuntu 14.04:

cd (App Dir)
react-native start > /dev/null 2>&1 &
adb reverse tcp:8081 tcp:8081

Update: See

Update 2: @scgough We got this error because React Native (RN) was unable to fetch JavaScript from the dev server running on our workstations. You can see why this happens here:

https://github.com/facebook/react-native/blob/42eb5464fd8a65ed84b799de5d4dc225349449be/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.java#L116-L137

If your RN app detects that you're using Genymotion or the emulator it tries to fetch the JavaScript from GENYMOTION_LOCALHOST (10.0.3.2) or EMULATOR_LOCALHOST (10.0.2.2). Otherwise it presumes that you're using a device and it tries to fetch the JavaScript from DEVICE_LOCALHOST (localhost). The problem is that the dev server runs on your workstation's localhost, not the device's, so in order to get it to work you need to either:

Construct a manual legend for a complicated plot

You need to map attributes to aesthetics (colours within the aes statement) to produce a legend.

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here

I understand where Roland is coming from, but since this is only 3 attributes, and complications arise from superimposing bars and error bars this may be reasonable to leave the data in wide format like it is. It could be slightly reduced in complexity by using geom_pointrange.


To change the background color for the error bars legend in the original, add + theme(legend.key = element_rect(fill = "white",colour = "white")) to the plot specification. To merge different legends, you typically need to have a consistent mapping for all elements, but it is currently producing an artifact of a black background for me. I thought guide = guide_legend(fill = NULL,colour = NULL) would set the background to null for the legend, but it did not. Perhaps worth another question.

ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) + 
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here


To get rid of the black background in the legend, you need to use the override.aes argument to the guide_legend. The purpose of this is to let you specify a particular aspect of the legend which may not be being assigned correctly.

ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols, 
                      guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here

How do I get the App version and build number using Swift?

for anyone interested, there's a nice and neat library called SwifterSwift available at github and also fully documented for every version of swift (see swifterswift.com).

using this library, reading app version and build number would be as easy as this:

import SwifterSwift

let buildNumber = SwifterSwift.appBuild
let version = SwifterSwift.appVersion

Oracle SQL escape character (for a '&')

The real answer is you need to set the escape character to '\': SET ESCAPE ON

The problem may have occurred either because escaping was disabled, or the escape character was set to something other than '\'. The above statement will enable escaping and set it to '\'.


None of the other answers previously posted actually answer the original question. They all work around the problem but don't resolve it.

Show/hide div if checkbox selected

change the input boxes like

<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox

and js code as

function showMe (box) {

    var chboxs = document.getElementsByName("c1");
    var vis = "none";
    for(var i=0;i<chboxs.length;i++) { 
        if(chboxs[i].checked){
         vis = "block";
            break;
        }
    }
    document.getElementById(box).style.display = vis;


}

here is a demo fiddle

iOS 7 status bar overlapping UI

Many thanks man. It worked fine on:

MAC OS X 10.9.1 - Xcode 5.0.2 - cordova 3.3 - jQuery mobile 1.3.2.

Read url to string in few lines of java code

If your url is of type java.net.URL, then you can just convert it to uri and then to string

url.toURI().toString()

Position a div container on the right side

if you don't want to use float

<div style="text-align:right; margin:0px auto 0px auto;">
<p> Hello </p>
</div>
  <div style="">
<p> Hello </p>
</div>

Repository access denied. access via a deployment key is read-only

I had this happen when I was trying to use a deployment key because that is exactly what I wanted.

I could connect via ssh -T [email protected] and it would tell me I had access to read the repository I wanted, but git clone would fail.

Clearing out ~/.ssh/known_hosts, generating a new key via ssh-keygen, adding that new key to bitbucket, and retrying fixed it for me.

What is the meaning of the term "thread-safe"?

At least in C++, I think of thread-safe as a bit of a misnomer in that it leaves a lot out of the name. To be thread-safe, code typically has to be proactive about it. It's not generally a passive quality.

For a class to be thread-safe, it has to have "extra" features that add overhead. These features are part of the implementation of the class and generally speaking, hidden from the interface. That is, different threads can access any of the class' members without ever having to worry about conflicting with a concurrent access by a different thread AND can do so in a very lazy manner, using some plain old regular human coding style, without having to do all that crazy synchronization stuff that is already rolled into the guts of the code being called.

And this is why some people prefer to use the term internally synchronized.

Terminology Sets

There are three main sets of terminology for these ideas I have encountered. The first and historically more popular (but worse) is:

  1. thread safe
  2. not thread safe

The second (and better) is:

  1. thread proof
  2. thread compatible
  3. thread hostile

A third is:

  1. internally synchronized
  2. externally synchronized
  3. unsynchronizable

Analogies

thread safe ~ thread proof ~ internally synchronized

An example of an internally synchronized (aka. thread-safe or thread proof) system is a restaurant where a host greets you at the door, and disallows you from queueing yourself. The host is part of the mechanism of the restaurant for dealing with multiple customers, and can use some rather tricky tricks for optimizing the seating of waiting customers, like taking the size of their party into account, or how much time they look like they have, or even taking reservations over the phone. The restaurant is internally synchronized because all of this is included "behind the scenes" when you interact with it. You, the customer, don't do any of it. The host does all of it for you.

not thread-safe (but nice) ~ thread compatible ~ externally synchronized ~ free-threaded

Suppose that you go to the bank. There is a line, i.e. contention for the bank tellers. Because you're not a savage, you recognize that the best thing to do in the midst of contention for a resource is to queue like a civilized being. No one technically makes you do this. We hope you have the necessary social programming to do it on your own. In this sense, the bank lobby is externally synchronized. Should we say that it's thread-unsafe? that's what the implication is if you go with the thread-safe, thread-unsafe bipolar terminology set. It's not a very good set of terms. The better terminology is externally synchronized, The bank lobby is not hostile to being accessed by multiple customers, but it doesn't do the work of synchronizing them either. The customers do that themselves.

This is also called "free threaded," where "free" is as in "free from lice"--or in this case, locks. Well, more accurately, synchronization primitives. That doesn't mean the code can run on multiple threads without those primitives. It just means it doesn't come with them already installed and it's up to you, the user of the code, to install them yourself however you see fit. Installing your own synchronization primitives can be difficult and requires thinking hard about the code, but also can lead to the fastest possible program by allowing you to customize how the program executes on today's hyperthreaded CPUs.

not thread safe (and bad) ~ thread hostile ~ unsynchronizable

An example everyday analogy of a thread-hostile system is some jerk with a sports car refusing to use their blinkers and changing lanes willy-nilly. Their driving style is thread hostile or unsychronizable because you have no way to coordinate with them, and this can lead to contention for the same lane, without resolution, and thus an accident as two cars attempt to occupy the same space, without any protocol to prevent this. This pattern can also be thought of more broadly as anti-social, which I prefer because it's less specific to threads and so more generally applicable to many areas of programming.

Why thread safe et al. are a bad terminology set

The first and oldest terminology set fails to make the finer distinction between thread hostility and thread compatibility. Thread compatibility is more passive than so-called thread safety, but that doesn't mean the called code is unsafe for concurrent thread use. It just means it's passive about the synchronization that would allow this, putting it off to the calling code, instead of providing it as part of its internal implementation. Thread compatible is how code should probably be written by default in most cases but this is also sadly often erroneously thought of as thread unsafe, as if it's inherently anti safety, which is a major point of confusion for programmers.

NOTE: Many software manuals actually use the term "thread-safe" to refer to "thread-compatible," adding even more confusion to what was already a mess! I avoid the term "thread-safe" and "thread-unsafe" at all costs for this very reason, as some sources will call something "thread-safe" while others will call it "thread-unsafe" because they can't agree on whether you have to meet some extra standards for safety (synchronization primitives), or just NOT be hostile to be considered "safe". So avoid those terms and use the smarter terms instead, to avoid dangerous miscommunications with other engineers.

Reminder of our goals

Essentially, our goal is to subvert chaos.

We do that by creating deterministic systems we can rely on. Determinism is expensive, mostly due to the opportunity costs of losing parallelism, pipelining, and reordering. We try to minimize the amount of determinism we need to keep our costs low, while also avoiding making decisions that will further erode what little determinism we can afford.

Synchronization of threads is about increasing the order and decreasing the chaos. The levels at which you do this correspond to the terms mentioned above. The highest level means that a system behaves in an entirely predictable manner every time. The second level means that the system behaves well enough that calling code can reliably detect unpredictability. For example, a spurious wakeup in a condition variable or a failure to lock a mutex because it's not ready. The third level means that the system doesn't behave well enough to play with anyone else and can only EVER be run single-threaded without incurring chaos.

Angular - Set headers for every request

For Angular 5 and above, we can use HttpInterceptor for generalizing the request and response operations. This helps us avoid duplicating:

1) Common headers

2) Specifying response type

3) Querying request

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {

  requestCounter: number = 0;
  constructor() {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      responseType: 'json',
      setHeaders: {
        Authorization: `Bearer token_value`,
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    });

    return next.handle(request).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response if you want
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        // do stuff with response error if you want
      }
    });
  }
}

We can use this AuthHttpInterceptor class as a provider for the HttpInterceptors:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app.routing-module';
import { AuthHttpInterceptor } from './services/auth-http.interceptor';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    BrowserAnimationsModule,
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthHttpInterceptor,
      multi: true
    }
  ],
  exports: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Declaring static constants in ES6 classes?

Maybe just put all your constants in a frozen object?

class MyClass {

    constructor() {
        this.constants = Object.freeze({
            constant1: 33,
            constant2: 2,
        });
    }

    static get constant1() {
        return this.constants.constant1;
    }

    doThisAndThat() {
        //...
        let value = this.constants.constant2;
        //...
    }
}

How to auto-generate a C# class file from a JSON string

If you install Web Essentials into Visual studio you can go to Edit => Past special => paste JSON as class.

That is probably the easiest there is.

Web Essentials: http://vswebessentials.com/

How to exit an if clause

use return in the if condition will returns you out from the function, so that you can use return to break the the if condition.

What does the Java assert keyword do, and when should it be used?

Assertion are basically used to debug the application or it is used in replacement of exception handling for some application to check the validity of an application.

Assertion works at run time. A simple example, that can explain the whole concept very simply, is herein - What does the assert keyword do in Java? (WikiAnswers).

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

I used

a2ensite default-ssl

and it worked like a charm.

If you want to force e.g. phpmyadmin to use SSL/https you will run into this problem if this link is missing.

"Multiple definition", "first defined here" errors

You should not include commands.c in your header file. In general, you should not include .c files. Rather, commands.c should include commands.h. As defined here, the C preprocessor is inserting the contents of commands.c into commands.h where the include is. You end up with two definitions of f123 in commands.h.

commands.h

#ifndef COMMANDS_H_
#define COMMANDS_H_

void f123();

#endif

commands.c

#include "commands.h"

void f123()
{
    /* code */
}

How to scp in Python?

If you are on *nix you can use sshpass

sshpass -p password scp -o User=username -o StrictHostKeyChecking=no src dst:/path

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

how to set default main class in java?

If you're creating 2 executable JAR files, each will have it's own manifest file, and each manifest file will specify the class that contains the main() method you want to use to start execution.

In each JAR file, the manifest will be a file with the following path / name inside the JAR - META-INF/MANIFEST.MF

There are ways to specify alternatively named files as a JAR's manifest using the JAR command-line parameters.

The specific class you want to use is specified using Main-Class: package.classname inside the META-INF/MANIFEST.MF file.

As for how to do this in Netbeans - not sure off the top of my head - I usually use IntelliJ and / or Eclipse and usually build the JAR through ANT or Maven anyway.

Ignore mapping one property with Automapper

Hello All Please Use this it's working fine... for auto mapper use multiple .ForMember in C#

        if (promotionCode.Any())
        {
            Mapper.Reset();
            Mapper.CreateMap<PromotionCode, PromotionCodeEntity>().ForMember(d => d.serverTime, o => o.MapFrom(s => s.promotionCodeId == null ? "date" : String.Format("{0:dd/MM/yyyy h:mm:ss tt}", DateTime.UtcNow.AddHours(7.0))))
                .ForMember(d => d.day, p => p.MapFrom(s => s.code != "" ? LeftTime(Convert.ToInt32(s.quantity), Convert.ToString(s.expiryDate), Convert.ToString(DateTime.UtcNow.AddHours(7.0))) : "Day"))
                .ForMember(d => d.subCategoryname, o => o.MapFrom(s => s.subCategoryId == 0 ? "" : Convert.ToString(subCategory.Where(z => z.subCategoryId.Equals(s.subCategoryId)).FirstOrDefault().subCategoryName)))
                .ForMember(d => d.optionalCategoryName, o => o.MapFrom(s => s.optCategoryId == 0 ? "" : Convert.ToString(optionalCategory.Where(z => z.optCategoryId.Equals(s.optCategoryId)).FirstOrDefault().optCategoryName)))
                .ForMember(d => d.logoImg, o => o.MapFrom(s => s.vendorId == 0 ? "" : Convert.ToString(vendorImg.Where(z => z.vendorId.Equals(s.vendorId)).FirstOrDefault().logoImg)))
                .ForMember(d => d.expiryDate, o => o.MapFrom(s => s.expiryDate == null ? "" : String.Format("{0:dd/MM/yyyy h:mm:ss tt}", s.expiryDate))); 
            var userPromotionModel = Mapper.Map<List<PromotionCode>, List<PromotionCodeEntity>>(promotionCode);
            return userPromotionModel;
        }
        return null;

Python and pip, list all versions of a package that's available?

For pip >= 20.3 use:

pip install --use-deprecated=legacy-resolver pylibmc==

For updates see: https://github.com/pypa/pip/issues/9139

For pip >= 9.0 use:

$ pip install pylibmc==
Collecting pylibmc==
  Could not find a version that satisfies the requirement pylibmc== (from 
  versions: 0.2, 0.3, 0.4, 0.5.1, 0.5.2, 0.5.3, 0.5.4, 0.5.5, 0.5, 0.6.1, 0.6, 
  0.7.1, 0.7.2, 0.7.3, 0.7.4, 0.7, 0.8.1, 0.8.2, 0.8, 0.9.1, 0.9.2, 0.9, 
  1.0-alpha, 1.0-beta, 1.0, 1.1.1, 1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.3.0)
No matching distribution found for pylibmc==

– all the available versions will be printed without actually downloading or installing any additional packages.

For pip < 9.0 use:

pip install pylibmc==blork

where blork can be any string that is not a valid version number.

How to find the length of a string in R

nchar(YOURSTRING)

you may need to convert to a character vector first;

nchar(as.character(YOURSTRING))

How to match, but not capture, part of a regex?

Update: Thanks to Germán Rodríguez Herrera!

In javascript try: /123-(apple(?=-)|banana(?=-)|(?!-))-?456/

Remember that the result is in group 1

Debuggex Demo

ERROR: Google Maps API error: MissingKeyMapError

you must create a project and collect the key in this way:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;language=en&key=()"></script>

How to stop line breaking in vim

set formatoptions-=t Keeps the visual textwidth but doesn't add new line in insert mode.

How can I get the current screen orientation?

getActivity().getResources().getConfiguration().orientation

this command returns int value 1 for Portrait and 2 for Landscape

How do I install the OpenSSL libraries on Ubuntu?

You want to install the development package, which is libssl-dev:

sudo apt-get install libssl-dev

Selecting Folder Destination in Java?

try something like this

JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("select folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);

What is the @Html.DisplayFor syntax for?

DisplayFor is also useful for templating. You could write a template for your Model, and do something like this:

@Html.DisplayFor(m => m)

Similar to @Html.EditorFor(m => m). It's useful for the DRY principal so that you don't have to write the same display logic over and over for the same Model.

Take a look at this blog on MVC2 templates. It's still very applicable to MVC3:

http://www.dalsoft.co.uk/blog/index.php/2010/04/26/mvc-2-templates/


It's also useful if your Model has a Data annotation. For instance, if the property on the model is decorated with the EmailAddress data annotation, DisplayFor will render it as a mailto: link.

What are Java command line options to set to allow JVM to be remotely debugged?

For java 1.5 or greater:

java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>

For java 1.4:

java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>

For java 1.3:

java -Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>

Here is output from a simple program:

java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 HelloWhirled
Listening for transport dt_socket at address: 1044
Hello whirled

How do I use Maven through a proxy?

If maven works through proxy but not some of the plugins it is invoking, try setting JAVA_TOOL_OPTIONS as well with -Dhttp*.proxy* settings.

If you have already JAVA_OPTS just do

export JAVA_TOOL_OPTIONS=$JAVA_OPTS

Why is the use of alloca() not considered good practice?

Sadly the truly awesome alloca() is missing from the almost awesome tcc. Gcc does have alloca().

  1. It sows the seed of its own destruction. With return as the destructor.

  2. Like malloc() it returns an invalid pointer on fail which will segfault on modern systems with a MMU (and hopefully restart those without).

  3. Unlike auto variables you can specify the size at run time.

It works well with recursion. You can use static variables to achieve something similar to tail recursion and use just a few others pass info to each iteration.

If you push too deep you are assured of a segfault (if you have an MMU).

Note that malloc() offers no more as it returns NULL (which will also segfault if assigned) when the system is out of memory. I.e. all you can do is bail or just try to assign it any way.

To use malloc() I use globals and assign them NULL. If the pointer is not NULL I free it before I use malloc().

You can also use realloc() as general case if want copy any existing data. You need to check pointer before to work out if you are going to copy or concatenate after the realloc().

3.2.5.2 Advantages of alloca

Apply style to cells of first row

This should do the work:

.category_table tr:first-child td {
    vertical-align: top;
}

jquery function val() is not equivalent to "$(this).value="?

$(this).value is attempting to call the 'value' property of a jQuery object, which does not exist. Native JavaScript does have a 'value' property on certain HTML objects, but if you are operating on a jQuery object you must access the value by calling $(this).val().

geom_smooth() what are the methods available?

Sometimes it's asking the question that makes the answer jump out. The methods and extra arguments are listed on the ggplot2 wiki stat_smooth page.

Which is alluded to on the geom_smooth() page with:

"See stat_smooth for examples of using built in model fitting if you need some more flexible, this example shows you how to plot the fits from any model of your choosing".

It's not the first time I've seen arguments in examples for ggplot graphs that aren't specifically in the function. It does make it tough to work out the scope of each function, or maybe I am yet to stumble upon a magic explicit list that says what will and will not work within each function.

How to get response status code from jQuery.ajax?

NB: Using jQuery 3.4.1

$.ajax({
  url: URL,
  success: function(data, textStatus, jqXHR){
    console.log(textStatus + ": " + jqXHR.status);
    // do something with data
  },
  error: function(jqXHR, textStatus, errorThrown){
    console.log(textStatus + ": " + jqXHR.status + " " + errorThrown);
  }
});

Update Jenkins from a war file

when you open the Jenkins panel it will show available package from their latest version. you can download it via wget command in the server.after download the latest package you should take .war backup file.

Eg-: wget http://updates.jenkins-ci.org/download/war/2.205/jenkins.war

Jenkins war file path for Ubuntu - /usr/share/jenkins/

Jenkins war file path for centos - /usr/lib/jenkins/

after taking backup overwrite the war file and restart the jenkins service.

Ubuntu - service jenkins restart , centos - systemctl restart jenkins.service

Javascript decoding html entities

I think you are looking for this ?

$('#your_id').html('&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;').text();

How do you obtain a Drawable object from a resource id in android package?

Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(d);

How do I encode/decode HTML entities in Ruby?

If you don't want to add a new dependency just to do this (like HTMLEntities) and you're already using Hpricot, it can both escape and unescape for you. It handles much more than CGI:

Hpricot.uxs "foo&nbsp;b&auml;r"
=> "foo bär"

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

Can we overload the main method in Java?

Yes a main method can be overloaded as other functions can be overloaded.One thing needs to be taken care is that there should be atleast one main function with "String args[] " as arguments .And there can be any number of main functions in your program with different arguments and functionality.Lets understand through a simple example:

Class A{

public static void main(String[] args)
{
System.out.println("This is the main function ");
A object= new A();
object.main("Hi this is overloaded function");//Calling the main function
}

public static void main(String argu)     //duplicate main function
{
System.out.println("main(String argu)");
}
}

Output: This is the main function
Hi this is overloaded function

Twitter bootstrap scrollable table

I had the same issue and used a combination of the above solutions (and added a twist of my own). Note that I had to specify column widths to keep them consistent between header and body.

In my solution, the header and footer stay fixed while the body scrolls.

<div class="table-responsive">
    <table class="table table-striped table-hover table-condensed">
        <thead>
            <tr>
                <th width="25%">First Name</th>
                <th width="13%">Last Name</th>
                <th width="25%" class="text-center">Address</th>
                <th width="25%" class="text-center">City</th>
                <th width="4%" class="text-center">State</th>
                <th width="8%" class="text-center">Zip</th>
            </tr>
        </thead>
    </table>
    <div class="bodycontainer scrollable">
        <table class="table table-hover table-striped table-condensed table-scrollable">
            <tbody>
                <!-- add rows here, specifying same widths as in header, at least on one row -->
            </tbody>
        </table>
    </div>
    <table class="table table-hover table-striped table-condensed">
        <tfoot>
            <!-- add your footer here... -->
        </tfoot>
    </table>
</div>

And then just applied the following CSS:

.bodycontainer { max-height: 450px; width: 100%; margin: 0; overflow-y: auto; }
.table-scrollable { margin: 0; padding: 0; }

I hope this helps someone else.

How do I modify the URL without reloading the page?

This is all you will need to navigate without reload

_x000D_
_x000D_
// add setting without reload 
location.hash = "setting";

// if url change with hash do somthing
window.addEventListener('hashchange', () => {
    console.log('url hash changed!');
});

// if url change do somthing (dont detect changes with hash)
//window.addEventListener('locationchange', function(){
//    console.log('url changed!');
//})


// remove #setting without reload 

history.back();
_x000D_
_x000D_
_x000D_

Signed to unsigned conversion in C - is it always safe?

Horrible Answers Galore

Ozgur Ozcitak

When you cast from signed to unsigned (and vice versa) the internal representation of the number does not change. What changes is how the compiler interprets the sign bit.

This is completely wrong.

Mats Fredriksson

When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.

This is also wrong. Unsigned ints may be promoted to ints should they have equal precision due to padding bits in the unsigned type.

smh

Your addition operation causes the int to be converted to an unsigned int.

Wrong. Maybe it does and maybe it doesn't.

Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)

Wrong. It is either undefined behavior if it causes overflow or the value is preserved.

Anonymous

The value of i is converted to unsigned int ...

Wrong. Depends on the precision of an int relative to an unsigned int.

Taylor Price

As was previously answered, you can cast back and forth between signed and unsigned without a problem.

Wrong. Trying to store a value outside the range of a signed integer results in undefined behavior.

Now I can finally answer the question.

Should the precision of int be equal to unsigned int, u will be promoted to a signed int and you will get the value -4444 from the expression (u+i). Now, should u and i have other values, you may get overflow and undefined behavior but with those exact numbers you will get -4444 [1]. This value will have type int. But you are trying to store that value into an unsigned int so that will then be cast to an unsigned int and the value that result will end up having would be (UINT_MAX+1) - 4444.

Should the precision of unsigned int be greater than that of an int, the signed int will be promoted to an unsigned int yielding the value (UINT_MAX+1) - 5678 which will be added to the other unsigned int 1234. Should u and i have other values, which make the expression fall outside the range {0..UINT_MAX} the value (UINT_MAX+1) will either be added or subtracted until the result DOES fall inside the range {0..UINT_MAX) and no undefined behavior will occur.

What is precision?

Integers have padding bits, sign bits, and value bits. Unsigned integers do not have a sign bit obviously. Unsigned char is further guaranteed to not have padding bits. The number of values bits an integer has is how much precision it has.

[Gotchas]

The macro sizeof macro alone cannot be used to determine precision of an integer if padding bits are present. And the size of a byte does not have to be an octet (eight bits) as defined by C99.

[1] The overflow may occur at one of two points. Either before the addition (during promotion) - when you have an unsigned int which is too large to fit inside an int. The overflow may also occur after the addition even if the unsigned int was within the range of an int, after the addition the result may still overflow.

VBA Subscript out of range - error 9

Option Explicit

Private Sub CommandButton1_Click()
Dim mode As String
Dim RecordId As Integer
Dim Resultid As Integer
Dim sourcewb As Workbook
Dim targetwb As Workbook
Dim SourceRowCount As Long
Dim TargetRowCount As Long
Dim SrceFile As String
Dim TrgtFile As String
Dim TitleId As Integer
Dim TestPassCount As Integer
Dim TestFailCount As Integer
Dim myWorkbook1 As Workbook
Dim myWorkbook2 As Workbook


TitleId = 4
Resultid = 0

Dim FileName1, FileName2 As String
Dim Difference As Long



'TestPassCount = 0
'TestFailCount = 0

'Retrieve number of records in the TestData SpreadSheet
Dim TestDataRowCount As Integer
TestDataRowCount = Worksheets("TestData").UsedRange.Rows.Count

If (TestDataRowCount <= 2) Then
  MsgBox "No records to validate.Please provide test data in Test Data SpreadSheet"
Else
  For RecordId = 3 To TestDataRowCount
    RefreshResultSheet

    'Source File row count
    SrceFile = Worksheets("TestData").Range("D" & RecordId).Value
    Set sourcewb = Workbooks.Open(SrceFile)
    With sourcewb.Worksheets(1)
      SourceRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
      sourcewb.Close
    End With

    'Target File row count
    TrgtFile = Worksheets("TestData").Range("E" & RecordId).Value
    Set targetwb = Workbooks.Open(TrgtFile)
    With targetwb.Worksheets(1)
      TargetRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
      targetwb.Close
    End With

    ' Set Row Count Result Test data value
    TitleId = TitleId + 3
    Worksheets("Result").Range("A" & TitleId).Value = Worksheets("TestData").Range("A" & RecordId).Value

    'Compare Source and Target Row count
    Resultid = TitleId + 1
    Worksheets("Result").Range("A" & Resultid).Value = "Source and Target record Count"
    If (SourceRowCount = TargetRowCount) Then
       Worksheets("Result").Range("B" & Resultid).Value = "Passed"
       Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
       TestPassCount = TestPassCount + 1
    Else
      Worksheets("Result").Range("B" & Resultid).Value = "Failed"
      Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
      TestFailCount = TestFailCount + 1
    End If


    'For comparison of two files

    FileName1 = Worksheets("TestData").Range("D" & RecordId).Value
    FileName2 = Worksheets("TestData").Range("E" & RecordId).Value

    Set myWorkbook1 = Workbooks.Open(FileName1)
    Set myWorkbook2 = Workbooks.Open(FileName2)

    Difference = Compare2WorkSheets(myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1"))
    myWorkbook1.Close
    myWorkbook2.Close


    'MsgBox Difference

    'Set Result of data validation in result sheet
    Resultid = Resultid + 1

    Worksheets("Result").Activate
    Worksheets("Result").Range("A" & Resultid).Value = "Data validation of source and target File"

    If Difference > 0 Then
        Worksheets("Result").Range("B" & Resultid).Value = "Failed"
        Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
        TestFailCount = TestFailCount + 1
    Else
      Worksheets("Result").Range("B" & Resultid).Value = "Passed"
      Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
      TestPassCount = TestPassCount + 1
    End If


  Next RecordId
End If

UpdateTestExecData TestPassCount, TestFailCount
End Sub

Sub RefreshResultSheet()
  Worksheets("Result").Activate
  Worksheets("Result").Range("B1:B4").Select
  Selection.ClearContents
  Worksheets("Result").Range("D1:D4").Select
  Selection.ClearContents
  Worksheets("Result").Range("B1").Value = Worksheets("Instructions").Range("D3").Value
  Worksheets("Result").Range("B2").Value = Worksheets("Instructions").Range("D4").Value
  Worksheets("Result").Range("B3").Value = Worksheets("Instructions").Range("D6").Value
  Worksheets("Result").Range("B4").Value = Worksheets("Instructions").Range("D5").Value
End Sub

Sub UpdateTestExecData(TestPassCount As Integer, TestFailCount As Integer)
  Worksheets("Result").Range("D1").Value = TestPassCount + TestFailCount
  Worksheets("Result").Range("D2").Value = TestPassCount
  Worksheets("Result").Range("D3").Value = TestFailCount
  Worksheets("Result").Range("D4").Value = ((TestPassCount / (TestPassCount + TestFailCount)))
End Sub

Get average color of image via Javascript

I would say via the HTML canvas tag.

You can find here a post by @Georg talking about a small code by the Opera dev :

// Get the CanvasPixelArray from the given coordinates and dimensions.
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;

// Loop over each pixel and invert the color.
for (var i = 0, n = pix.length; i < n; i += 4) {
    pix[i  ] = 255 - pix[i  ]; // red
    pix[i+1] = 255 - pix[i+1]; // green
    pix[i+2] = 255 - pix[i+2]; // blue
    // i+3 is alpha (the fourth element)
}

// Draw the ImageData at the given (x,y) coordinates.
context.putImageData(imgd, x, y);

This invert the image by using the R, G and B value of each pixel. You could easily store the RGB values, then round up the Red, Green and Blue arrays, and finally converting them back into an HEX code.

Initialization of an ArrayList in one line

Yes with the help of Arrays you can initialize array list in one line,

List<String> strlist= Arrays.asList("aaa", "bbb", "ccc");

Simple If/Else Razor Syntax

I would just go with

<tr @(if (count++ % 2 == 0){<text>class="alt-row"</text>})>

Or even better

<tr class="alt-row@(count++ % 2)">

this will give you lines like

<tr class="alt-row0">
<tr class="alt-row1">
<tr class="alt-row0">
<tr class="alt-row1">

Attach IntelliJ IDEA debugger to a running Java process

in AndroidStudio or idea

  1. Config the application will be debug, open Edit Configurations

add "VM Options" Config “-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005” remember "address"

enter image description here

  1. Config Remote Debugger if not exits, Click + to add

specify "Port" same as in Step 1 "address" enter image description here

Choosing a jQuery datagrid plugin?

A good plugin that I have used before is DataTables.

Read a Csv file with powershell and capture corresponding data

So I figured out what is wrong with this statement:

Import-Csv H:\Programs\scripts\SomeText.csv |`

(Original)

Import-Csv H:\Programs\scripts\SomeText.csv -Delimiter "|"

(Proposed, You must use quotations; otherwise, it will not work and ISE will give you an error)

It requires the -Delimiter "|", in order for the variable to be populated with an array of items. Otherwise, Powershell ISE does not display the list of items.

I cannot say that I would recommend the | operator, since it is used to pipe cmdlets into one another.

I still cannot get the if statement to return true and output the values entered via the prompt.

If anyone else can help, it would be great. I still appreciate the post, it has been very helpful!

JavaScript implementation of Gzip

I ported an implementation of LZMA from a GWT module into standalone JavaScript. It's called LZMA-JS.

ITextSharp HTML to PDF?

It has ability to convert HTML file in to pdf.

Required namespace for conversions are:

using iTextSharp.text;
using iTextSharp.text.pdf;

and for conversion and download file :

// Create a byte array that will eventually hold our final PDF
Byte[] bytes;

// Boilerplate iTextSharp setup here

// Create a stream that we can write to, in this case a MemoryStream
using (var ms = new MemoryStream())
{
    // Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
    using (var doc = new Document())
    {
        // Create a writer that's bound to our PDF abstraction and our stream
        using (var writer = PdfWriter.GetInstance(doc, ms))
        {
            // Open the document for writing
            doc.Open();

            string finalHtml = string.Empty;

            // Read your html by database or file here and store it into finalHtml e.g. a string
            // XMLWorker also reads from a TextReader and not directly from a string
            using (var srHtml = new StringReader(finalHtml))
            {
                // Parse the HTML
                iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
            }

            doc.Close();
        }
    }

    // After all of the PDF "stuff" above is done and closed but **before** we
    // close the MemoryStream, grab all of the active bytes from the stream
    bytes = ms.ToArray();
}

// Clear the response
Response.Clear();
MemoryStream mstream = new MemoryStream(bytes);

// Define response content type
Response.ContentType = "application/pdf";

// Give the name of file of pdf and add in to header
Response.AddHeader("content-disposition", "attachment;filename=invoice.pdf");
Response.Buffer = true;
mstream.WriteTo(Response.OutputStream);
Response.End();

Shorthand for if-else statement

Try this method;

Shorthand method:

_x000D_
_x000D_
let variable1 = '';_x000D_
_x000D_
let variable2 = variable1 || 'new'_x000D_
console.log(variable2); // new
_x000D_
_x000D_
_x000D_

Longhand method:

_x000D_
_x000D_
 let variable1 = 'ya';_x000D_
 let varibale2;_x000D_
_x000D_
 if (variable1 !== null || variable1 !== undefined || variable1 !== '')_x000D_
       variable2 = variable1;_x000D_
_x000D_
console.log(variable2); // ya
_x000D_
_x000D_
_x000D_

Getting the first and last day of a month, using a given DateTime object

The accepted answer here does not take into account the Kind of the DateTime instance. For example if your original DateTime instance was a UTC Kind then by making a new DateTime instance you will be making an Unknown Kind instance which will then be treated as local time based on server settings. Therefore the more proper way to get the first and last date of the month would be this:

var now = DateTime.UtcNow;
var first = now.Date.AddDays(-(now.Date.Day - 1));
var last = first.AddMonths(1).AddTicks(-1);

This way the original Kind of the DateTime instance is preserved.

Quickest way to convert a base 10 number to any base in .NET?

FAST "FROM" AND "TO" METHODS

I am late to the party, but I compounded previous answers and improved over them. I think these two methods are faster than any others posted so far. I was able to convert 1,000,000 numbers from and to base 36 in under 400ms in a single core machine.

Example below is for base 62. Change the BaseChars array to convert from and to any other base.

private static readonly char[] BaseChars = 
         "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
private static readonly Dictionary<char, int> CharValues = BaseChars
           .Select((c,i)=>new {Char=c, Index=i})
           .ToDictionary(c=>c.Char,c=>c.Index);

public static string LongToBase(long value)
{
   long targetBase = BaseChars.Length;
   // Determine exact number of characters to use.
   char[] buffer = new char[Math.Max( 
              (int) Math.Ceiling(Math.Log(value + 1, targetBase)), 1)];

   var i = buffer.Length;
   do
   {
       buffer[--i] = BaseChars[value % targetBase];
       value = value / targetBase;
   }
   while (value > 0);

   return new string(buffer, i, buffer.Length - i);
}

public static long BaseToLong(string number) 
{ 
    char[] chrs = number.ToCharArray(); 
    int m = chrs.Length - 1; 
    int n = BaseChars.Length, x;
    long result = 0; 
    for (int i = 0; i < chrs.Length; i++)
    {
        x = CharValues[ chrs[i] ];
        result += x * (long)Math.Pow(n, m--);
    }
    return result;  
} 

EDIT (2018-07-12)

Fixed to address the corner case found by @AdrianBotor (see comments) converting 46655 to base 36. This is caused by a small floating-point error calculating Math.Log(46656, 36) which is exactly 3, but .NET returns 3 + 4.44e-16, which causes an extra character in the output buffer.

jQuery .find() on data from .ajax() call is returning "[object Object]" instead of div

You might have to do something like

var content= (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d

then you should be able to use

result = $(content).find("#result")

How do I make a WinForms app go Full Screen

And for the menustrip-question, try set

MenuStrip1.Parent = Nothing

when in fullscreen mode, it should then disapear.

And when exiting fullscreenmode, reset the menustrip1.parent to the form again and the menustrip will be normal again.

mysql -> insert into tbl (select from another table) and some default values

You simply have to do:

INSERT INTO def (catid, title, page, publish) 
SELECT catid, title, 'page','yes' from `abc`

Which type of folder structure should be used with Angular 2?

Maybe something like this structure:

|-- app
     |-- modules
       |-- home
           |-- [+] components
           |-- pages
              |-- home
              |-- home.component.ts|html|scss|spec
           |-- home-routing.module.ts
           |-- home.module.ts
     |-- core
       |-- authentication
           |-- authentication.service.ts|spec.ts
       |-- footer
           |-- footer.component.ts|html|scss|spec.ts
       |-- guards
           |-- auth.guard.ts
           |-- no-auth-guard.ts
           |-- admin-guard.ts 
       |-- http
           |-- user
               |-- user.service.ts|spec.ts
           |-- api.service.ts|spec.ts
       |-- interceptors
           |-- api-prefix.interceptor.ts
           |-- error-handler.interceptor.ts
           |-- http.token.interceptor.ts
       |-- mocks
           |-- user.mock.ts
       |-- services
           |-- srv1.service.ts|spec.ts
           |-- srv2.service.ts|spec.ts
       |-- header
           |-- header.component.ts|html|scss|spec.ts
       |-- core.module.ts
       |-- ensureModuleLoadedOnceGuard.ts
       |-- logger.service.ts
     |-- shared
          |-- components
              |-- loader
                  |-- loader.component.ts|html|scss|spec.ts
          |-- buttons
              |-- favorite-button
                  |-- favorite-button.component.ts|html|scss|spec.ts
              |-- collapse-button
                  |-- collapse-button.component.ts|html|scss|spec.ts
          |-- directives
              |-- auth.directive.ts|spec.ts
          |-- pipes
              |-- capitalize.pipe.ts
              |-- safe.pipe.ts
     |-- configs
         |-- app-settings.config.ts
         |-- dt-norwegian.config.ts
     |-- scss
          |-- [+] partials
          |-- _base.scss
          |-- styles.scss
     |-- assets

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

Python decorators in classes

You can decorate the decorator:

import decorator

class Test(object):
    @decorator.decorator
    def _decorator(foo, self):
        foo(self)

    @_decorator
    def bar(self):
        pass

Convert java.time.LocalDate into java.util.Date type

Simple

public Date convertFrom(LocalDate date) {
    return java.sql.Timestamp.valueOf(date.atStartOfDay());
}

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

In case you are trying to use ARC app from google and post a XML and you are getting this error, then try changing the body content type to application/xml. Example here

filename and line number of Python script

import inspect    

file_name = __FILE__
current_line_no = inspect.stack()[0][2]
current_function_name = inspect.stack()[0][3]

#Try printing inspect.stack() you can see current stack and pick whatever you want 

Trust Store vs Key Store - creating with keytool

There is no difference between keystore and truststore files. Both are files in the proprietary JKS file format. The distinction is in the use: To the best of my knowledge, Java will only use the store that is referenced by the -Djavax.net.ssl.trustStore system property to look for certificates to trust when creating SSL connections. Same for keys and -Djavax.net.ssl.keyStore. But in theory it's fine to use one and the same file for trust- and keystores.

Java - How to find the redirected url of a url?

Simply call getUrl() on URLConnection instance after calling getInputStream():

URLConnection con = new URL( url ).openConnection();
System.out.println( "orignal url: " + con.getURL() );
con.connect();
System.out.println( "connected url: " + con.getURL() );
InputStream is = con.getInputStream();
System.out.println( "redirected url: " + con.getURL() );
is.close();

If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:

HttpURLConnection con = (HttpURLConnection)(new URL( url ).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
int responseCode = con.getResponseCode();
System.out.println( responseCode );
String location = con.getHeaderField( "Location" );
System.out.println( location );

How to Compare two strings using a if in a stored procedure in sql server 2008?

What you want is a SQL case statement. The form of these is either:

  select case [expression or column]
  when [value] then [result]
  when [value2] then [result2]
  else [value3] end

or:

  select case 
  when [expression or column] = [value] then [result]
  when [expression or column] = [value2] then [result2]
  else [value3] end

In your example you are after:

declare @temp as varchar(100)
set @temp='Measure'

select case @temp 
   when 'Measure' then Measure 
   else OtherMeasure end
from Measuretable

Summarizing multiple columns with dplyr?

All the examples are great, but I figure I'd add one more to show how working in a "tidy" format simplifies things. Right now the data frame is in "wide" format meaning the variables "a" through "d" are represented in columns. To get to a "tidy" (or long) format, you can use gather() from the tidyr package which shifts the variables in columns "a" through "d" into rows. Then you use the group_by() and summarize() functions to get the mean of each group. If you want to present the data in a wide format, just tack on an additional call to the spread() function.


library(tidyverse)

# Create reproducible df
set.seed(101)
df <- tibble(a   = sample(1:5, 10, replace=T), 
             b   = sample(1:5, 10, replace=T), 
             c   = sample(1:5, 10, replace=T), 
             d   = sample(1:5, 10, replace=T), 
             grp = sample(1:3, 10, replace=T))

# Convert to tidy format using gather
df %>%
    gather(key = variable, value = value, a:d) %>%
    group_by(grp, variable) %>%
    summarize(mean = mean(value)) %>%
    spread(variable, mean)
#> Source: local data frame [3 x 5]
#> Groups: grp [3]
#> 
#>     grp        a     b        c        d
#> * <int>    <dbl> <dbl>    <dbl>    <dbl>
#> 1     1 3.000000   3.5 3.250000 3.250000
#> 2     2 1.666667   4.0 4.666667 2.666667
#> 3     3 3.333333   3.0 2.333333 2.333333

Detecting when Iframe content has loaded (Cross browser)

See this blog post. It uses jQuery, but it should help you even if you are not using it.

Basically you add this to your document.ready()

$('iframe').load(function() {
    RunAfterIFrameLoaded();
});

When to use <span> instead <p>?

Span is completely non-semantic. It has no meaning, and serves merely as an element for cosmetic effects.

Paragraphs have semantic meaning - they tell a machine (like a browser or a screen reader) that the content they encapsulate is a block of text, and has the same meaning as a paragraph of text in a book.

How can I git stash a specific file?

To add to svick's answer, the -m option simply adds a message to your stash, and is entirely optional. Thus, the command

git stash push [paths you wish to stash]

is perfectly valid. So for instance, if I want to only stash changes in the src/ directory, I can just run

git stash push src/

Adding machineKey to web.config on web-farm sites

Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.

An alternative option is to set it in the machine level web.config, so its not even in the web site folder.

To generate it do it just like the linked article in David's answer.

Converting Integer to String with comma for thousands

can't you use a

System.out.printf("%n%,d",int name);

The comma in the printf should add the commas into the %d inter.

Not positive about it, but works for me.

PHP : send mail in localhost

It is possible to send Emails without using any heavy libraries I have included my example here.

lightweight SMTP Email sender for PHP

https://github.com/jerryurenaa/EZMAIL

Tested in both environments production and development.

and most importantly emails will not go to spam unless your IP is blacklisted by the server.

cheers.

Is it possible to get multiple values from a subquery?

you can use cross apply:

select
    a.x,
    bb.y,
    bb.z
from
    a
    cross apply
    (   select b.y, b.z
        from b
        where b.v = a.v
    ) bb

If there will be no row from b to mach row from a then cross apply wont return row. If you need such a rows then use outer apply

If you need to find only one specific row for each of row from a, try:

    cross apply
    (   select top 1 b.y, b.z
        from b
        where b.v = a.v
        order by b.order
    ) bb

jQuery UI Color Picker

That is because you are trying to access the plugin before it's loaded. You should try making a call to it when the DOM is loaded by surrounding it with this:

$(document).ready(function(){
    $("#colorpicker").colorpicker();
}

Regular Expression to match valid dates

This regex validates dates between 01-01-2000 and 12-31-2099 with matching separators.

^(0[1-9]|1[012])([- /.])(0[1-9]|[12][0-9]|3[01])\2(19|20)\d\d$

Why does dividing two int not yield the right value when assigned to double?

With very few exceptions (I can only think of one), C++ determines the entire meaning of an expression (or sub-expression) from the expression itself. What you do with the results of the expression doesn't matter. In your case, in the expression a / b, there's not a double in sight; everything is int. So the compiler uses integer division. Only once it has the result does it consider what to do with it, and convert it to double.

asp.net mvc @Html.CheckBoxFor

Use this code:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "YourId" })
}

Encode/Decode URLs in C++

Had to do it in a project without Boost. So, ended up writing my own. I will just put it on GitHub: https://github.com/corporateshark/LUrlParser

clParseURL URL = clParseURL::ParseURL( "https://name:[email protected]:80/path/res" );

if ( URL.IsValid() )
{
    cout << "Scheme    : " << URL.m_Scheme << endl;
    cout << "Host      : " << URL.m_Host << endl;
    cout << "Port      : " << URL.m_Port << endl;
    cout << "Path      : " << URL.m_Path << endl;
    cout << "Query     : " << URL.m_Query << endl;
    cout << "Fragment  : " << URL.m_Fragment << endl;
    cout << "User name : " << URL.m_UserName << endl;
    cout << "Password  : " << URL.m_Password << endl;
}

How to fix "'System.AggregateException' occurred in mscorlib.dll"

As the message says, you have a task which threw an unhandled exception.

Turn on Break on All Exceptions (Debug, Exceptions) and rerun the program.
This will show you the original exception when it was thrown in the first place.


(comment appended): In VS2015 (or above). Select Debug > Options > Debugging > General and unselect the "Enable Just My Code" option.

Webfont Smoothing and Antialiasing in Firefox and Opera

Case: Light text with jaggy web font on dark background Firefox (v35)/Windows
Example: Google Web Font Ruda

Surprising solution -
adding following property to the applied selectors:

selector {
    text-shadow: 0 0 0;
}

Actually, result is the same just with text-shadow: 0 0;, but I like to explicitly set blur-radius.

It's not an universal solution, but might help in some cases. Moreover I haven't experienced (also not thoroughly tested) negative performance impacts of this solution so far.

hardcoded string "row three", should use @string resource

A good practice is write text inside String.xml

example:

String.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="yellow">Yellow</string>
</resources>

and inside layout:

<TextView android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/yellow" />

How do you stop MySQL on a Mac OS install?

sudo /opt/local/etc/LaunchDaemons/org.macports.mysql5/mysql5.wrapper stop

You can also use start and restart here. I found this by looking at the contents of /Library/LaunchDaemons/org.macports.mysql.plist.

Reading a string with spaces with sscanf

The following line will start reading a number (%d) followed by anything different from tabs or newlines (%[^\t\n]).

sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);

How to prevent robots from automatically filling up a form?

I'm thinking of many things here:

  1. using JS (although you don't want it) to track mouse move, key press, mouse click
  2. getting the referral url (which in this case should be one from the same domain) ... the normal user must navigate through the website before reaching the contact form: PHP: How to get referrer URL?
  3. using a $_SESSION variable to acquire the IP and check the form submit against that list of IPs
  4. Fill in one text field with some dummy text that you can check on server side if it had been overwritten
  5. Check the browser version: http://chrisschuld.com/projects/browser-php-detecting-a-users-browser-from-php.html ... It's clear that a bot won't use a browser but just a script.
  6. Use AJAX to send the fields one by one and check the difference in time between submissions
  7. Use a fake page before/after the form, just to send another input

PostgreSQL how to see which queries have run

While using Django with postgres 10.6, logging was enabled by default, and I was able to simply do:

tail -f /var/log/postgresql/*

Ubuntu 18.04, django 2+, python3+

Angular EXCEPTION: No provider for Http

I faced this issue in my code. I only put this code in my app.module.ts.

import { HttpModule } from '@angular/http';

@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

How to remove "disabled" attribute using jQuery?

2018, without JQuery

I know the question is about JQuery: this answer is just FYI.

document.getElementById('edit').addEventListener(event => {
    event.preventDefault();
    [...document.querySelectorAll('.inputDisabled')].map(e => e.disabled = false);
}); 

How to retrieve unique count of a field using Kibana + Elastic Search

Using Aggs u can easily do that. Writing down query for now.

GET index/_search
{
  "size":0,
  "aggs": {
    "source": {
      "terms": {
        "field": "field",
        "size": 100000
      }
    }
  }
 }

This would return the different values of field with there doc counts.

A fast way to delete all rows of a datatable at once

That's the easiest way to delete all rows from the table in dbms via DataAdapter. But if you want to do it in one batch, you can set the DataAdapter's UpdateBatchSize to 0(unlimited).

Another way would be to use a simple SqlCommand with CommandText DELETE FROM Table:

using(var con = new SqlConnection(ConfigurationSettings.AppSettings["con"]))
using(var cmd = new SqlCommand())
{
    cmd.CommandText = "DELETE FROM Table";
    cmd.Connection = con;
    con.Open();
    int numberDeleted = cmd.ExecuteNonQuery();  // all rows deleted
}

But if you instead only want to remove the DataRows from the DataTable, you just have to call DataTable.Clear. That would prevent any rows from being deleted in dbms.

Using (Ana)conda within PyCharm

I know it's late, but I thought it would be nice to clarify things: PyCharm and Conda and pip work well together.

The short answer

Just manage Conda from the command line. PyCharm will automatically notice changes once they happen, just like it does with pip.

The long answer

Create a new Conda environment:

conda create --name foo pandas bokeh

This environment lives under conda_root/envs/foo. Your python interpreter is conda_root/envs/foo/bin/pythonX.X and your all your site-packages are in conda_root/envs/foo/lib/pythonX.X/site-packages. This is same directory structure as in a pip virtual environement. PyCharm sees no difference.

Now to activate your new environment from PyCharm go to file > settings > project > interpreter, select Add local in the project interpreter field (the little gear wheel) and hunt down your python interpreter. Congratulations! You now have a Conda environment with pandas and bokeh!

Now install more packages:

conda install scikit-learn

OK... go back to your interpreter in settings. Magically, PyCharm now sees scikit-learn!

And the reverse is also true, i.e. when you pip install another package in PyCharm, Conda will automatically notice. Say you've installed requests. Now list the Conda packages in your current environment:

conda list

The list now includes requests and Conda has correctly detected (3rd column) that it was installed with pip.

Conclusion

This is definitely good news for people like myself who are trying to get away from the pip/virtualenv installation problems when packages are not pure python.

NB: I run PyCharm pro edition 4.5.3 on Linux. For Windows users, replace in command line with in the GUI (and forward slashes with backslashes). There's no reason it shouldn't work for you too.

EDIT: PyCharm5 is out with Conda support! In the community edition too.

"Full screen" <iframe>

You can use this piece of code:

  <iframe src="http://example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0%;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>

How do I find out what License has been applied to my SQL Server installation?

When I run:

   exec sp_readerrorlog @p1 = 0
   ,@p2 = 1
   ,@p3 = N'licensing'

I get:

SQL Server detected 2 sockets with 21 cores per socket and 21 logical processors per socket, 42 total logical processors; using 20 logical processors based on SQL Server licensing. This is an informational message; no user action is required.

also, SELECT @@VERSION shows:

Microsoft SQL Server 2014 (SP1-GDR) (KB4019091) - 12.0.4237.0 (X64) Jul 5 2017 22:03:42 Copyright (c) Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.3 (Build 9600: ) (Hypervisor)

This is a VM

show all tags in git log

Note: the commit 5e1361c from brian m. carlson (bk2204) (for git 1.9/2.0 Q1 2014) deals with a special case in term of log decoration with tags:

log: properly handle decorations with chained tags

git log did not correctly handle decorations when a tag object referenced another tag object that was no longer a ref, such as when the second tag was deleted.
The commit would not be decorated correctly because parse_object had not been called on the second tag and therefore its tagged field had not been filled in, resulting in none of the tags being associated with the relevant commit.

Call parse_object to fill in this field if it is absent so that the chain of tags can be dereferenced and the commit can be properly decorated.
Include tests as well to prevent future regressions.

Example:

git tag -a tag1 -m tag1 &&
git tag -a tag2 -m tag2 tag1 &&
git tag -d tag1 &&
git commit --amend -m shorter &&
git log --no-walk --tags --pretty="%H %d" --decorate=full

How to compare strings in sql ignoring case?

I don't recall the exact syntax, but you may set the table column to be case insensitive. But be careful because then you won't be able to match based on case anymore and if you WANT 'cool' to not match 'CoOl' it will no longer be possible.

How to hide a TemplateField column in a GridView

A slight improvement using column name, IMHO:

    Private Sub GridView1_Init(sender As Object, e As System.EventArgs) Handles GridView1.Init
    For Each dcf As DataControlField In GridView1.Columns
        Select Case dcf.HeaderText.ToUpper
            Case "CBSELECT"
                dcf.Visible = Me.CheckBoxVisible
                dcf.HeaderText = "<small>Select</small>"
        End Select
    Next
End Sub

This allows control over multiple column. I initially use a 'technical' column name, matching the control name within. This makes it obvious within the ASCX page that it's a control column. Then swap out the name as desired for presentation. If I spy the odd name in production, I know I skipped something. The "ToUpper" avoids case-issues.

Finally, this runs ONE time on any post instead of capturing the event during row-creation.

Angular update object in object array

You can use for loop to find your element and update it:

updateItem(newItem){
  for (let i = 0; i < this.itemsArray.length; i++) {
      if(this.itemsArray[i].id == newItem.id){
        this.users[i] = newItem;
      }
    }
}

Can anyone explain python's relative imports?

Checking it out in python3:

python -V
Python 3.6.5

Example1:

.
+-- parent.py
+-- start.py
+-- sub
    +-- relative.py

- start.py
import sub.relative

- parent.py
print('Hello from parent.py')

- sub/relative.py
from .. import parent

If we run it like this(just to make sure PYTHONPATH is empty):

PYTHONPATH='' python3 start.py

Output:

Traceback (most recent call last):
  File "start.py", line 1, in <module>
    import sub.relative
  File "/python-import-examples/so-example-v1/sub/relative.py", line 1, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/relative.py

- sub/relative.py
import parent

If we run it like this:

PYTHONPATH='' python3 start.py

Output:

Hello from parent.py

Example2:

.
+-- parent.py
+-- sub
    +-- relative.py
    +-- start.py

- parent.py
print('Hello from parent.py')

- sub/relative.py
print('Hello from relative.py')

- sub/start.py
import relative
from .. import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 2, in <module>
    from .. import parent
ValueError: attempted relative import beyond top-level package

If we change import in sub/start.py:

- sub/start.py
import relative
import parent

Run it like:

PYTHONPATH='' python3 sub/start.py

Output:

Hello from relative.py
Traceback (most recent call last):
  File "sub/start.py", line 3, in <module>
    import parent
ModuleNotFoundError: No module named 'parent'

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

Also it's better to use import from root folder, i.e.:

- sub/start.py
import sub.relative
import parent

Run it like:

PYTHONPATH='.' python3 sub/start.py

Output:

Hello from relative.py
Hello from parent.py

What does (function($) {})(jQuery); mean?

Just small addition to explanation

This structure (function() {})(); is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. So when you're writing these rows:

(function($) {
  // do something
})(jQuery);

this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $.

How to stop a setTimeout loop?

setTimeout returns a timer handle, which you can use to stop the timeout with clearTimeout.

So for instance:

function setBgPosition() {
    var c = 0,
        timer = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c >= numbers.length) {
            c = 0;
        }
        timer = setTimeout(run, 200);
    }
    timer = setTimeout(run, 200);

    return stop;

    function stop() {
        if (timer) {
            clearTimeout(timer);
            timer = 0;
        }
}

So you'd use that as:

var stop = setBgPosition();
// ...later, when you're ready to stop...
stop();

Note that rather than having setBgPosition call itself again, I've just had it set c back to 0. Otherwise, this wouldn't work. Also note that I've used 0 as a handle value for when the timeout isn't pending; 0 isn't a valid return value from setTimeout so it makes a handy flag.

This is also one of the (few) places I think you'd be better off with setInterval rather than setTimeout. setInterval repeats. So:

function setBgPosition() {
    var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c >= numbers.length) {
            c = 0;
        }
    }
    return setInterval(run, 200);
}

Used like this:

var timer = setBgPosition();
// ...later, when you're ready to stop...
clearInterval(timer);

All of the above notwithstanding, I'd want to find a way to make setBgPosition stop things itself, by detecting that some completion condition has been satisfied.

What charset does Microsoft Excel use when saving files?

CSV files could be in any format, depending on what encoding option was specified during the export from Excel: (Save Dialog, Tools Button, Web Options Item, Encoding Tab)

UPDATE: Excel (including Office 2013) doesn't actually respect the web options selected in the "save as..." dialog, so this is a bug of some sort. I just use OpenOffice Calc now to open my XLSX files and export them as CSV files (edit filter settings, choose UTF-8 encoding).

What is the exact location of MySQL database tables in XAMPP folder?

For Mac, your database files are located at:

/Applications/XAMPP/xamppfiles/var/mysql

You might need admin permissions to access or delete your files.

Unused arguments in R

I had the same problem as you. I had a long list of arguments, most of which were irrelevant. I didn't want to hard code them in. This is what I came up with

library(magrittr)
do_func_ignore_things <- function(data, what){
    acceptable_args <- data[names(data) %in% (formals(what) %>% names)]
    do.call(what, acceptable_args %>% as.list)
}

do_func_ignore_things(c(n = 3, hello = 12, mean = -10), "rnorm")
# -9.230675 -10.503509 -10.927077

How to replace innerHTML of a div using jQuery?

Just to add some performance insights.

A few years ago I had a project, where we had issues trying to set a large HTML / Text to various HTML elements.

It appeared, that "recreating" the element and injecting it to the DOM was way faster than any of the suggested methods to update the DOM content.

So something like:

_x000D_
_x000D_
var text = "very big content";_x000D_
$("#regTitle").remove();_x000D_
$("<div id='regTitle'>" + text + "</div>").appendTo("body");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Should get you a better performance. I haven't recently tried to measure that (browsers should be clever these days), but if you're looking for performance it may help.

The downside is that you will have more work to keep the DOM and the references in your scripts pointing to the right object.

add allow_url_fopen to my php.ini using .htaccess

Try this, but I don't think it will work because you're not supposed to be able to change this

Put this line in an htaccess file in the directory you want the setting to be enabled:

php_value allow_url_fopen On

Note that this setting will only apply to PHP file's in the same directory as the htaccess file.

As an alternative to using url_fopen, try using curl.

What should I do if the current ASP.NET session is null?

If your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.

This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):

public class MyAshxClass : IHttpHandler, IRequiresSessionState

Amazon S3 - HTTPS/SSL - Is it possible?

payton109’s answer is correct if you’re in the default US-EAST-1 region. If your bucket is in a different region, use a slightly different URL:

https://s3-<region>.amazonaws.com/your.domain.com/some/asset

Where <region> is the bucket location name. For example, if your bucket is in the us-west-2 (Oregon) region, you can do this:

https://s3-us-west-2.amazonaws.com/your.domain.com/some/asset

grep for special characters in Unix

The one that worked for me is:

grep -e '->'

The -e means that the next argument is the pattern, and won't be interpreted as an argument.

From: http://www.linuxquestions.org/questions/programming-9/how-to-grep-for-string-769460/

How do I find Waldo with Mathematica?

I've found Waldo!

waldo had been found

How I've done it

First, I'm filtering out all colours that aren't red

waldo = Import["http://www.findwaldo.com/fankit/graphics/IntlManOfLiterature/Scenes/DepartmentStore.jpg"];
red = Fold[ImageSubtract, #[[1]], Rest[#]] &@ColorSeparate[waldo];

Next, I'm calculating the correlation of this image with a simple black and white pattern to find the red and white transitions in the shirt.

corr = ImageCorrelate[red, 
   Image@Join[ConstantArray[1, {2, 4}], ConstantArray[0, {2, 4}]], 
   NormalizedSquaredEuclideanDistance];

I use Binarize to pick out the pixels in the image with a sufficiently high correlation and draw white circle around them to emphasize them using Dilation

pos = Dilation[ColorNegate[Binarize[corr, .12]], DiskMatrix[30]];

I had to play around a little with the level. If the level is too high, too many false positives are picked out.

Finally I'm combining this result with the original image to get the result above

found = ImageMultiply[waldo, ImageAdd[ColorConvert[pos, "GrayLevel"], .5]]

How do I upload a file with the JS fetch API?

To submit a single file, you can simply use the File object from the input's .files array directly as the value of body: in your fetch() initializer:

const myInput = document.getElementById('my-input');

// Later, perhaps in a form 'submit' handler or the input's 'change' handler:
fetch('https://example.com/some_endpoint', {
  method: 'POST',
  body: myInput.files[0],
});

This works because File inherits from Blob, and Blob is one of the permissible BodyInit types defined in the Fetch Standard.

How do you add a timed delay to a C++ program?

On Windows you can include the windows library and use "Sleep(0);" to sleep the program. It takes a value that represents milliseconds.

Obtaining only the filename when using OpenFileDialog property "FileName"

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

RunAs A different user when debugging in Visual Studio

cmd.exe is located in different locations in different versions of Windows. To avoid needing the location of cmd.exe, you can use the command moogs wrote without calling "cmd.exe /C".

Here's an example that worked for me:

  1. Open Command Prompt
  2. Change directory to where your application's .exe file is located.
  3. Execute the following command: runas /user:domain\username Application.exe

So the final step will look something like this in Command Prompt:

C:\Projects\MyProject\bin\Debug>runas /user:domain\username Application.exe

Note: the domain name was required in my situation.

How do I automatically resize an image for a mobile site?

You can use the following css to resize the image for mobile view

object-fit: scale-down; max-width: 100%

Change Primary Key

Sometimes when we do these steps:

 alter table my_table drop constraint my_pk; 
 alter table my_table add constraint my_pk primary key (city_id, buildtime, time);

The last statement fails with

ORA-00955 "name is already used by an existing object"

Oracle usually creates an unique index with the same name my_pk. In such a case you can drop the unique index or rename it based on whether the constraint is still relevant.

You can combine the dropping of primary key constraint and unique index into a single sql statement:

alter table my_table drop constraint my_pk drop index; 

check this: ORA-00955 "name is already used by an existing object"

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

for xcode 11.1which doesn't contain ipad pro iPad Pro (2nd Gen) 12.9" Display run this command in terminal

xcrun simctl create "iPad Pro (12.9-inch) (2nd generation)" "com.apple.CoreSimulator.SimDeviceType.iPad-Pro--12-9-inch---2nd-generation-" "com.apple.CoreSimulator.SimRuntime.iOS-13-1"

look here

WebAPI Multiple Put/Post parameters

Natively WebAPI doesn't support binding of multiple POST parameters. As Colin points out there are a number of limitations that are outlined in my blog post he references.

There's a workaround by creating a custom parameter binder. The code to do this is ugly and convoluted, but I've posted code along with a detailed explanation on my blog, ready to be plugged into a project here:

Passing multiple simple POST Values to ASP.NET Web API

How do I remove a library from the arduino environment?

Go to your Arduino documents directory; inside you will find a directory named "Libraries". The imported library directory will be there. Just delete it and restart the Arduino app.

Your Arduino library folder should look like this (on Windows):

  My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.cpp
  My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.h
  My Documents\Arduino\libraries\ArduinoParty\examples
  ....

or like this (on Mac and Linux):

  Documents/Arduino/libraries/ArduinoParty/ArduinoParty.cpp
  Documents/Arduino/libraries/ArduinoParty/ArduinoParty.h
  Documents/Arduino/libraries/ArduinoParty/examples

The only issue with unused libraries is the trivial amount of disk space they use. They aren't loaded automatically so don't take up any application memory of the Arduino IDE.

Mysql adding user for remote access

for what DB is the user? look at this example

mysql> create database databasename;
Query OK, 1 row affected (0.00 sec)
mysql> grant all on databasename.* to cmsuser@localhost identified by 'password';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

so to return to you question the "%" operator means all computers in your network.

like aspesa shows I'm also sure that you have to create or update a user. look for all your mysql users:

SELECT user,password,host FROM user;

as soon as you got your user set up you should be able to connect like this:

mysql -h localhost -u gmeier -p

hope it helps

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

What is "string[] args" in Main class for?

The args parameter stores all command line arguments which are given by the user when you run the program.

If you run your program from the console like this:

program.exe there are 4 parameters

Your args parameter will contain the four strings: "there", "are", "4", and "parameters"

Here is an example of how to access the command line arguments from the args parameter: example

How to convert answer into two decimal point

If you have a Decimal or similar numeric type, you can use:

Math.Round(myNumber, 2)

EDIT: So, in your case, it would be:

Public Class Form1
  Private Sub btncalc_Click(ByVal sender As System.Object,
                            ByVal e As System.EventArgs) Handles btncalc.Click
    txtA.Text = Math.Round((Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text)), 2)
    txtB.Text = Math.Round((Val(txtA.Text) * 1000 / Val(txtG.Text)), 2)
  End Sub
End Class

T-SQL: Looping through an array of known values

What I do in this scenario is create a table variable to hold the Ids.

  Declare @Ids Table (id integer primary Key not null)
  Insert @Ids(id) values (4),(7),(12),(22),(19)

-- (or call another table valued function to generate this table)

Then loop based on the rows in this table

  Declare @Id Integer
  While exists (Select * From @Ids)
    Begin
      Select @Id = Min(id) from @Ids
      exec p_MyInnerProcedure @Id 
      Delete from @Ids Where id = @Id
    End

or...

  Declare @Id Integer = 0 -- assuming all Ids are > 0
  While exists (Select * From @Ids
                where id > @Id)
    Begin
      Select @Id = Min(id) 
      from @Ids Where id > @Id
      exec p_MyInnerProcedure @Id 
    End

Either of above approaches is much faster than a cursor (declared against regular User Table(s)). Table-valued variables have a bad rep because when used improperly, (for very wide tables with large number of rows) they are not performant. But if you are using them only to hold a key value or a 4 byte integer, with a index (as in this case) they are extremely fast.

System.MissingMethodException: Method not found?

Using Costura.Fody 1.6 & 2.0:
After wasting a bunch of time looking into this same kind of error with all other potential solutions not working, I found that an older version of the DLL I was embedding was in the same directory I was running my newly compiled .exe from. Apparently it looks for a local file in the same directory first, then looks inward to its embedded library. Deleting the old DLL worked.

To be clear, it wasn't that my reference was pointing to an old DLL, it was that a copy of an old DLL was in the directory I was testing my application from on a separate system from that which it was compiled on.

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

I had this issue after migrating from spring-boot-starter-data-jpa ver. 1.5.7 to 2.0.2 (from old hibernate to hibernate 5.2). In my @Configuration class I injected entityManagerFactory and transactionManager.

//I've got my data source defined in application.yml config file, 
//so there is no need to configure it from java.
@Autowired
DataSource dataSource;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    //JpaVendorAdapteradapter can be autowired as well if it's configured in application properties.
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(false);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    //Add package to scan for entities.
    factory.setPackagesToScan("com.company.domain");
    factory.setDataSource(dataSource);
    return factory;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory);
    return txManager;
}

Also remember to add hibernate-entitymanager dependency to pom.xml otherwise EntityManagerFactory won't be found on classpath:

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.0.12.Final</version>
</dependency>

how can I check if a file exists?

For anyone who is looking a way to watch a specific file to exist in VBS:

Function bIsFileDownloaded(strPath, timeout)
  Dim FSO, fileIsDownloaded
  set FSO = CreateObject("Scripting.FileSystemObject")
  fileIsDownloaded = false
  limit = DateAdd("s", timeout, Now)
  Do While Now < limit
    If FSO.FileExists(strPath) Then : fileIsDownloaded = True : Exit Do : End If
    WScript.Sleep 1000      
  Loop
  Set FSO = Nothing
  bIsFileDownloaded = fileIsDownloaded
End Function

Usage:

FileName = "C:\test.txt"
fileIsDownloaded = bIsFileDownloaded(FileName, 5) ' keep watching for 5 seconds

If fileIsDownloaded Then
  WScript.Echo Now & " File is Downloaded: " & FileName
Else
  WScript.Echo Now & " Timeout, file not found: " & FileName 
End If

How can I see the entire HTTP request that's being sent by my Python application?

The verbose configuration option might allow you to see what you want. There is an example in the documentation.

NOTE: Read the comments below: The verbose config options doesn't seem to be available anymore.

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

Remove this line from your code:

console.info(JSON.parse(scatterSeries));

Highlight text similar to grep, but don't filter out text

If you are doing this because you want more context in your search, you can do this:

cat BIG_FILE.txt | less

Doing a search in less should highlight your search terms.

Or pipe the output to your favorite editor. One example:

cat BIG_FILE.txt | vim -

Then search/highlight/replace.

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

How to find a string inside a entire database?

create procedure usp_find_string(@string as varchar(1000))
as
begin
declare @mincounter as int
declare @maxcounter as int
declare @stmtquery as varchar(1000)
set @stmtquery=''
create table #tmp(tablename varchar(128),columnname varchar(128),rowid int identity)
create table #tablelist(tablename varchar(128),columnname varchar(128))
declare @tmp table(name varchar(128))
declare @tablename as varchar(128)
declare @columnname as varchar(128)

insert into #tmp(tablename,columnname)
select a.name,b.name as columnname from sysobjects a
inner join syscolumns b on a.name=object_name(b.id)
where a.type='u'
and b.xtype in(select xtype from systypes
    where name='text' or name='ntext' or name='varchar' or name='nvarchar' or name='char' or name='nchar')
order by a.name

select @maxcounter=max(rowid),@mincounter=min(rowid) from #tmp 
while(@mincounter <= @maxcounter )
begin
 select @tablename=tablename, @columnname=columnname from #tmp where rowid=@mincounter
 set @stmtquery ='select top 1  ' + '[' +@columnname+']' + ' from ' + '['+@tablename+']' + ' where ' + '['+@columnname+']' + ' like ' + '''%' + @string + '%'''
 insert into @tmp(name) exec(@stmtquery)
 if @@rowcount >0
 insert into #tablelist values(@tablename,@columnname)
 set @mincounter=@mincounter +1
end
select * from #tablelist
end

How do I generate a stream from a string?

I used a mix of answers like this:

public static Stream ToStream(this string str, Encoding enc = null)
{
    enc = enc ?? Encoding.UTF8;
    return new MemoryStream(enc.GetBytes(str ?? ""));
}

And then I use it like this:

String someStr="This is a Test";
Encoding enc = getEncodingFromSomeWhere();
using (Stream stream = someStr.ToStream(enc))
{
    // Do something with the stream....
}

Error: free(): invalid next size (fast):

We need the code, but that usually pops up when you try to free() memory from a pointer that is not allocated. This often happens when you're double-freeing.

How to add/subtract dates with JavaScript?

Something I am using (jquery needed), in my script I need it for the current day, but of course you can edit it accordingly.

HTML:

<label>Date:</label><input name="date" id="dateChange" type="date"/>
<input id="SubtractDay" type="button" value="-" />
<input id="AddDay" type="button" value="+" />

JavaScript:

    var counter = 0;

$("#SubtractDay").click(function() {
    counter--;
    var today = new Date();
    today.setDate(today.getDate() + counter);
    var formattedDate = new Date(today);
    var d = ("0" + formattedDate.getDate()).slice(-2);
    var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
    var y = formattedDate.getFullYear();
    $("#dateChange").val(d + "/" + m + "/" + y);
});
$("#AddDay").click(function() {
    counter++;
    var today = new Date();
    today.setDate(today.getDate() + counter);
    var formattedDate = new Date(today);
    var d = ("0" + formattedDate.getDate()).slice(-2);
    var m = ("0" + (formattedDate.getMonth() + 1)).slice(-2);
    var y = formattedDate.getFullYear();
    $("#dateChange").val(d + "/" + m + "/" + y);
});

jsfiddle

Git error when trying to push -- pre-receive hook declined

I got this error with GitHub gist. I was trying to push a commit with files in sub-directories. Turned out gist can only have files in root directory.

Check if all values of array are equal

arr.length && arr.reduce(function(a, b){return (a === b)?a:false;}) === arr[0];

How to loop through a plain JavaScript object with the objects as members?

Using Underscore.js’s _.each:

_.each(validation_messages, function(value, key){
    _.each(value, function(value, key){
        console.log(value);
    });
});

how to compare two string dates in javascript?

var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
    alert ("Error!");
}

Demo Jsfiddle

#define in Java

Simplest Answer is "No Direct method of getting it because there is no pre-compiler" But you can do it by yourself. Use classes and then define variables as final so that it can be assumed as constant throughout the program
Don't forget to use final and variable as public or protected not private otherwise you won't be able to access it from outside that class

WaitAll vs WhenAll

Task.WaitAll blocks the current thread until everything has completed.

Task.WhenAll returns a task which represents the action of waiting until everything has completed.

That means that from an async method, you can use:

await Task.WhenAll(tasks);

... which means your method will continue when everything's completed, but you won't tie up a thread to just hang around until that time.

Android get current Locale, not default

As per official documentation ConfigurationCompat is deprecated in support libraries

You can consider using

LocaleListCompat.getDefault()[0].toLanguageTag() 0th position will be user preferred locale

To get Default locale at 0th position would be LocaleListCompat.getAdjustedDefault()