Programs & Examples On #Odbc bridge

C++ Loop through Map

You can achieve this like following :

map<string, int>::iterator it;

for (it = symbolTable.begin(); it != symbolTable.end(); it++)
{
    std::cout << it->first    // string (key)
              << ':'
              << it->second   // string's value 
              << std::endl;
}

With C++11 ( and onwards ),

for (auto const& x : symbolTable)
{
    std::cout << x.first  // string (key)
              << ':' 
              << x.second // string's value 
              << std::endl;
}

With C++17 ( and onwards ),

for (auto const& [key, val] : symbolTable)
{
    std::cout << key        // string (key)
              << ':'  
              << val        // string's value
              << std::endl;
}

Collections.sort with multiple fields

Here is a full example comparing 2 fields in an object, one String and one int, also using Collator to sort.

public class Test {

    public static void main(String[] args) {

        Collator myCollator;
        myCollator = Collator.getInstance(Locale.US);

        List<Item> items = new ArrayList<Item>();

        items.add(new Item("costrels", 1039737, ""));
        items.add(new Item("Costs", 1570019, ""));
        items.add(new Item("costs", 310831, ""));
        items.add(new Item("costs", 310832, ""));

        Collections.sort(items, new Comparator<Item>() {
            @Override
            public int compare(final Item record1, final Item record2) {
                int c;
                //c = record1.item1.compareTo(record2.item1); //optional comparison without Collator                
                c = myCollator.compare(record1.item1, record2.item1);
                if (c == 0) 
                {
                    return record1.item2 < record2.item2 ? -1
                            :  record1.item2 > record2.item2 ? 1
                            : 0;
                }
                return c;
            }
        });     

        for (Item item : items)
        {
            System.out.println(item.item1);
            System.out.println(item.item2);
        }       

    }

    public static class Item
    {
        public String item1;
        public int item2;
        public String item3;

        public Item(String item1, int item2, String item3)
        {
            this.item1 = item1;
            this.item2 = item2;
            this.item3 = item3;
        }       
    }

}

Output:

costrels 1039737

costs 310831

costs 310832

Costs 1570019

Correct way to work with vector of arrays

Use:

vector<vector<float>> vecArray; //both dimensions are open!

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

Initializing C dynamic arrays

p = {1,2,3} is wrong.

You can never use this:

int * p;
p = {1,2,3};

loop is right

int *p,i;
p = malloc(3*sizeof(int));
for(i = 0; i<3; ++i)
    p[i] = i;

BigDecimal equals() versus compareTo()

You can also compare with double value

BigDecimal a= new BigDecimal("1.1"); BigDecimal b =new BigDecimal("1.1");
System.out.println(a.doubleValue()==b.doubleValue());

NSRange from Swift Range?

Swift 4:

Sure, I know that Swift 4 has an extension for NSRange already

public init<R, S>(_ region: R, in target: S) where R : RangeExpression,
    S : StringProtocol, 
    R.Bound == String.Index, S.Index == String.Index

I know in most cases this init is enough. See its usage:

let string = "Many animals here:  !!!"

if let range = string.range(of: ""){
     print((string as NSString).substring(with: NSRange(range, in: string))) //  ""
 }

But conversion can be done directly from Range< String.Index > to NSRange without Swift's String instance.

Instead of generic init usage which requires from you the target parameter as String and if you don't have target string at hand you can create conversion directly

extension NSRange {
    public init(_ range:Range<String.Index>) {
        self.init(location: range.lowerBound.encodedOffset,
              length: range.upperBound.encodedOffset -
                      range.lowerBound.encodedOffset) }
    }

or you can create the specialized extension for Range itself

extension Range where Bound == String.Index {
    var nsRange:NSRange {
    return NSRange(location: self.lowerBound.encodedOffset,
                     length: self.upperBound.encodedOffset -
                             self.lowerBound.encodedOffset)
    }
}

Usage:

let string = "Many animals here:  !!!"
if let range = string.range(of: ""){
    print((string as NSString).substring(with: NSRange(range))) //  ""
}

or

if let nsrange = string.range(of: "")?.nsRange{
    print((string as NSString).substring(with: nsrange)) //  ""
}

Swift 5:

Due to the migration of Swift strings to UTF-8 encoding by default, the usage of encodedOffset is considered as deprecated and Range cannot be converted to NSRange without an instance of String itself, because in order to calculate the offset we need the source string which is encoded in UTF-8 and it should be converted to UTF-16 before calculating offset. So best approach, for now, is to use generic init.

How to create a batch file to run cmd as administrator

(This is based on @DarkXphenomenon's answer, which unfortunately had some problems.)

You need to enclose your code within this wrapper:

if _%1_==_payload_  goto :payload

:getadmin
    echo %~nx0: elevating self
    set vbs=%temp%\getadmin.vbs
    echo Set UAC = CreateObject^("Shell.Application"^)                >> "%vbs%"
    echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof

:payload
    echo %~nx0: running payload with parameters:
    echo %*
    echo ---------------------------------------------------
    cd /d %2
    shift
    shift
    rem put your code here
    rem e.g.: perl myscript.pl %1 %2 %3 %4 %5 %6 %7 %8 %9
goto :eof

This makes batch file run itself as elevated user. It adds two parameters to the privileged code:

  • word payload, to indicate this is payload call, i.e. already elevated. Otherwise it would just open new processes over and over.

  • directory path where the main script was called. Due to the fact that Windows always starts elevated cmd.exe in "%windir%\system32", there's no easy way of knowing what the original path was (and retaining ability to copy your script around without touching code)

Note: Unfortunately, for some reason shift does not work for %*, so if you need to pass actual arguments on, you will have to resort to the ugly notation I used in the example (%1 %2 %3 %4 %5 %6 %7 %8 %9), which also brings in the limit of maximum of 9 arguments

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

I ran into the same situation where commands such as git diff origin or git diff origin master produced the error reported in the question, namely Fatal: ambiguous argument...

To resolve the situation, I ran the command

git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master

to set refs/remotes/origin/HEAD to point to the origin/master branch.

Before running this command, the output of git branch -a was:

* master
  remotes/origin/master

After running the command, the error no longer happened and the output of git branch -a was:

* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master

(Other answers have already identified that the source of the error is HEAD not being set for origin. But I thought it helpful to provide a command which may be used to fix the error in question, although it may be obvious to some users.)


Additional information:

For anybody inclined to experiment and go back and forth between setting and unsetting refs/remotes/origin/HEAD, here are some examples.

To unset:
git remote set-head origin --delete

To set:
(additional ways, besides the way shown at the start of this answer)
git remote set-head origin master to set origin/head explicitly
OR
git remote set-head origin --auto to query the remote and automatically set origin/HEAD to the remote's current branch.

References:

  • This SO Answer
  • This SO Comment and its associated answer
  • git remote --help see set-head description
  • git symbolic-ref --help

SQL string value spanning multiple lines in query

I prefer to use the @ symbol so I see the query exactly as I can copy and paste into a query file:

string name = "Joe";
string gender = "M";
string query = String.Format(@"
SELECT
   *
FROM
   tableA
WHERE
   Name = '{0}' AND
   Gender = '{1}'", name, gender);

It's really great with long complex queries. Nice thing is it keeps tabs and line feeds so pasting into a query browser retains the nice formatting

Rotating a point about another point (2D)

First subtract the pivot point (cx,cy), then rotate it, then add the point again.

Untested:

POINT rotate_point(float cx,float cy,float angle,POINT p)
{
  float s = sin(angle);
  float c = cos(angle);

  // translate point back to origin:
  p.x -= cx;
  p.y -= cy;

  // rotate point
  float xnew = p.x * c - p.y * s;
  float ynew = p.x * s + p.y * c;

  // translate point back:
  p.x = xnew + cx;
  p.y = ynew + cy;
  return p;
}

Simple DateTime sql query

You need quotes around the string you're trying to pass off as a date, and you can also use BETWEEN here:

 SELECT *
   FROM TABLENAME
  WHERE DateTime BETWEEN '04/12/2011 12:00:00 AM' AND '05/25/2011 3:53:04 AM'

See answer to the following question for examples on how to explicitly convert strings to dates while specifying the format:

Sql Server string to date conversion

In java how to get substring from a string till a character c?

Here is code which returns a substring from a String until any of a given list of characters:

/**
 * Return a substring of the given original string until the first appearance
 * of any of the given characters.
 * <p>
 * e.g. Original "ab&cd-ef&gh"
 * 1. Separators {'&', '-'}
 * Result: "ab"
 * 2. Separators {'~', '-'}
 * Result: "ab&cd"
 * 3. Separators {'~', '='}
 * Result: "ab&cd-ef&gh"
 *
 * @param original   the original string
 * @param characters the separators until the substring to be considered
 * @return the substring or the original string of no separator exists
 */
public static String substringFirstOf(String original, List<Character> characters) {
    return characters.stream()
            .map(original::indexOf)
            .filter(min -> min > 0)
            .reduce(Integer::min)
            .map(position -> original.substring(0, position))
            .orElse(original);
}

Copy a variable's value into another

the question is already solved since quite a long time, but for future reference a possible solution is

b = a.slice(0);

Be careful, this works correctly only if a is a non-nested array of numbers and strings

A column-vector y was passed when a 1d array was expected

use below code:

model = forest.fit(train_fold, train_y.ravel())

if you are still getting slap by error as identical as below ?

Unknown label type: %r" % y

use this code:

y = train_y.ravel()
train_y = np.array(y).astype(int)
model = forest.fit(train_fold, train_y)

python pandas extract year from datetime: df['year'] = df['date'].year is not working

This works:

df['date'].dt.year

Now:

df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month

gives this data frame:

        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

Calling one method from another within same class in Python

To call the method, you need to qualify function with self.. In addition to that, if you want to pass a filename, add a filename parameter (or other name you want).

class MyHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        srcpath = event.src_path
        print (srcpath, 'has been ',event.event_type)
        print (datetime.datetime.now())
        filename = srcpath[12:]
        self.dropbox_fn(filename) # <----

    def dropbox_fn(self, filename):  # <-----
        print('In dropbox_fn:', filename)

Couldn't load memtrack module Logcat Error

This error, as you can read on the question linked in comments above, results to be:

"[...] a problem with loading {some} hardware module. This could be something to do with GPU support, sdcard handling, basically anything."

The step 1 below should resolve this problem. Also as I can see, you have some strange package names inside your manifest:

  • package="com.example.hive" in <manifest> tag,
  • android:name="com.sit.gems.app.GemsApplication" for <application>
  • and android:name="com.sit.gems.activity" in <activity>

As you know, these things do not prevent your app to be displayed. But I think:

the Couldn't load memtrack module error could occur because of emulators configurations problems and, because your project contains many organization problems, it might help to give a fresh redesign.

For better using and with few things, this can be resolved by following these tips:


1. Try an other emulator...

And even a real device! The memtrack module error seems related to your emulator. So change it into Run configuration, don't forget to change the API too.


2. OpenGL error logs

For OpenGl errors, as called unimplemented OpenGL ES API, it's not an error but a statement! You should enable it in your manifest (you can read this answer if you're using GLSurfaceView inside HomeActivity.java, it might help you):

<uses-feature android:glEsVersion="0x00020000"></uses-feature>  
// or
<uses-feature android:glEsVersion="0x00010001" android:required="true" />

3. Use the same package

Don't declare different package names to all the tags in Manifest. You should have the same for Manifest, Activities, etc. Something like this looks right:

<!-- set the general package -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sit.gems.activity"
    android:versionCode="1"
    android:versionName="1.0" >

    <!-- don't set a package name in <application> -->
    <application ... >

        <!-- then, declare the activities -->
        <activity
            android:name="com.sit.gems.activity.SplashActivity" ... >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- same package here -->
        <activity
            android:name="com.sit.gems.activity.HomeActivity" ... >
        </activity>
    </application>
</manifest>  

4. Don't get lost with layouts:

You should set another layout for SplashScreenActivity.java because you're not using the TabHost for the splash screen and this is not a safe resource way. Declare a specific layout with something different, like the app name and the logo:

// inside SplashScreen class
setContentView(R.layout.splash_screen);

// layout splash_screen.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent" 
     android:gravity="center"
     android:text="@string/appname" />  

Avoid using a layout in activities which don't use it.


5. Splash Screen?

Finally, I don't understand clearly the purpose of your SplashScreenActivity. It sets a content view and directly finish. This is useless.

As its name is Splash Screen, I assume that you want to display a screen before launching your HomeActivity. Therefore, you should do this and don't use the TabHost layout ;):

// FragmentActivity is also useless here! You don't use a Fragment into it, so, use traditional Activity
public class SplashActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set your splash_screen layout
        setContentView(R.layout.splash_screen);

        // create a new Thread
        new Thread(new Runnable() {
            public void run() {
                try {
                    // sleep during 800ms
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // start HomeActivity
                startActivity(new Intent(SplashActivity.this, HomeActivity.class));
                SplashActivity.this.finish();
            }
        }).start();
    }
}  

I hope this kind of tips help you to achieve what you want.
If it's not the case, let me know how can I help you.

Finding child element of parent pure javascript

The children property returns an array of elements, like so:

parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]

There are alternatives to querySelector, like document.getElementsByClassName('parent')[0] if you so desire.


Edit: Now that I think about it, you could just use querySelectorAll to get decendents of parent having a class name of child1:

children = document.querySelectorAll('.parent .child1');

The difference between qS and qSA is that the latter returns all elements matching the selector, while the former only returns the first such element.

What is this CSS selector? [class*="span"]

.show-grid [class*="span"]

It's a CSS selector that selects all elements with the class show-grid that has a child element whose class contains the name span.

Maximum value for long integer

Direct answer to title question:

Integers are unlimited in size and have no maximum value in Python.

Answer which addresses stated underlying use case:

According to your comment of what you're trying to do, you are currently thinking something along the lines of

minval = MAXINT;
for (i = 1; i < num_elems; i++)
    if a[i] < a[i-1]
        minval = a[i];

That's not how to think in Python. A better translation to Python (but still not the best) would be

minval = a[0]  # Just use the first value
for i in range(1, len(a)):
    minval = min(a[i], a[i - 1])

Note that the above doesn't use MAXINT at all. That part of the solution applies to any programming language: You don't need to know the highest possible value just to find the smallest value in a collection.

But anyway, what you really do in Python is just

minval = min(a)

That is, you don't write a loop at all. The built-in min() function gets the minimum of the whole collection.

Elegant ways to support equivalence ("equality") in Python classes

Not a direct answer but seemed relevant enough to be tacked on as it saves a bit of verbose tedium on occasion. Cut straight from the docs...


functools.total_ordering(cls)

Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest. This simplifies the effort involved in specifying all of the possible rich comparison operations:

The class must define one of __lt__(), __le__(), __gt__(), or __ge__(). In addition, the class should supply an __eq__() method.

New in version 2.7

@total_ordering
class Student:
    def __eq__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))

Shortest way to print current year in a website

according to chrome audit

For users on slow connections, external scripts dynamically injected via document.write() can delay page load by tens of seconds.

https://web.dev/no-document-write/?utm_source=lighthouse&utm_medium=devtools

so solution without errors is:

(new Date).getFullYear();

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

Try this for Amazon Linux AMI or for centOS

sudo service mysqld restart

Display help message with python argparse when script is called without any arguments

This answer comes from Steven Bethard on Google groups. I'm reposting it here to make it easier for people without a Google account to access.

You can override the default behavior of the error method:

import argparse
import sys

class MyParser(argparse.ArgumentParser):
    def error(self, message):
        sys.stderr.write('error: %s\n' % message)
        self.print_help()
        sys.exit(2)

parser = MyParser()
parser.add_argument('foo', nargs='+')
args = parser.parse_args()

Note that the above solution will print the help message whenever the error method is triggered. For example, test.py --blah will print the help message too if --blah isn't a valid option.

If you want to print the help message only if no arguments are supplied on the command line, then perhaps this is still the easiest way:

import argparse
import sys

parser=argparse.ArgumentParser()
parser.add_argument('foo', nargs='+')
if len(sys.argv)==1:
    parser.print_help(sys.stderr)
    sys.exit(1)
args=parser.parse_args()

Note that parser.print_help() prints to stdout by default. As init_js suggests, use parser.print_help(sys.stderr) to print to stderr.

How do you do the "therefore" (?) symbol on a Mac or in Textmate?

From System Preferences, turn on the "Show Keyboard & Character Viewer in menu bar" setting.

Then, the "Character Viewer" menu will pop up a tool that will let you search for any unicode character (by name) and insert it ? you're all set.

What is private bytes, virtual bytes, working set?

There is an interesting discussion here: http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/307d658a-f677-40f2-bdef-e6352b0bfe9e/ My understanding of this thread is that freeing small allocations are not reflected in Private Bytes or Working Set.

Long story short:

if I call

p=malloc(1000);
free(p);

then the Private Bytes reflect only the allocation, not the deallocation.

if I call

p=malloc(>512k);
free(p);

then the Private Bytes correctly reflect the allocation and the deallocation.

dropping rows from dataframe based on a "not in" condition

You can use pandas.Dataframe.isin.

pandas.Dateframe.isin will return boolean values depending on whether each element is inside the list a or not. You then invert this with the ~ to convert True to False and vice versa.

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

print(df)
#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

print(df)
#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

get current date with 'yyyy-MM-dd' format in Angular 4

Try this:

   import * as moment from 'moment';

     ngOnInit() {
     this.date = moment().format("YYYY Do MMM");
                }

Can I try/catch a warning?

FolderStructure

index.php //Script File
logs //Folder for log Every warning and Errors
CustomException.php //Custom exception File

CustomException.php

/**
* Custom error handler
*/
function handleError($code, $description, $file = null, $line = null, $context = null) {
    $displayErrors = ini_get("display_errors");;
    $displayErrors = strtolower($displayErrors);
    if (error_reporting() === 0 || $displayErrors === "on") {
        return false;
    }
    list($error, $log) = mapErrorCode($code);
    $data = array(
        'timestamp' => date("Y-m-d H:i:s:u", time()),
        'level' => $log,
        'code' => $code,
        'type' => $error,
        'description' => $description,
        'file' => $file,
        'line' => $line,
        'context' => $context,
        'path' => $file,
        'message' => $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']'
    );
    $data = array_map('htmlentities',$data);
    return fileLog(json_encode($data));
}

/**
* This method is used to write data in file
* @param mixed $logData
* @param string $fileName
* @return boolean
*/
function fileLog($logData, $fileName = ERROR_LOG_FILE) {
    $fh = fopen($fileName, 'a+');
    if (is_array($logData)) {
        $logData = print_r($logData, 1);
    }
    $status = fwrite($fh, $logData . "\n");
    fclose($fh);
//    $file = file_get_contents($filename);
//    $content = '[' . $file .']';
//    file_put_contents($content); 
    return ($status) ? true : false;
}

/**
* Map an error code into an Error word, and log location.
*
* @param int $code Error code to map
* @return array Array of error word, and log location.
*/
function mapErrorCode($code) {
    $error = $log = null;
    switch ($code) {
        case E_PARSE:
        case E_ERROR:
        case E_CORE_ERROR:
        case E_COMPILE_ERROR:
        case E_USER_ERROR:
            $error = 'Fatal Error';
            $log = LOG_ERR;
            break;
        case E_WARNING:
        case E_USER_WARNING:
        case E_COMPILE_WARNING:
        case E_RECOVERABLE_ERROR:
            $error = 'Warning';
            $log = LOG_WARNING;
            break;
        case E_NOTICE:
        case E_USER_NOTICE:
            $error = 'Notice';
            $log = LOG_NOTICE;
            break;
        case E_STRICT:
            $error = 'Strict';
            $log = LOG_NOTICE;
            break;
        case E_DEPRECATED:
        case E_USER_DEPRECATED:
            $error = 'Deprecated';
            $log = LOG_NOTICE;
            break;
        default :
            break;
    }
    return array($error, $log);
}
//calling custom error handler
set_error_handler("handleError");

just include above file into your script file like this

index.php

error_reporting(E_ALL);
ini_set('display_errors', 'off');
define('ERROR_LOG_FILE', 'logs/app_errors.log');

include_once 'CustomException.php';
echo $a; // here undefined variable warning will be logged into logs/app_errors.log

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException in simple words is -> you have 10 students in your class (int array size 10) and you want to view the value of the 11th student (a student who does not exist)

if you make this int i[3] then i takes values i[0] i[1] i[2]

for your problem try this code structure

double[] array = new double[50];

    for (int i = 0; i < 24; i++) {

    }

    for (int j = 25; j < 50; j++) {

    }

SQL: Insert all records from one table to another table without specific the columns

As you probably understood from previous answers, you can't really do what you're after. I think you can understand the problem SQL Server is experiencing with not knowing how to map the additional/missing columns.

That said, since you mention that the purpose of what you're trying to here is backup, maybe we can work with SQL Server and workaround the issue. Not knowing your exact scenario makes it impossible to hit with a right answer here, but I assume the following:

  • You wish to manage a backup/audit process for a table.
  • You probably have a few of those and wish to avoid altering dependent objects on every column addition/removal.
  • The backup table may contain additional columns for auditing purposes.

I wish to suggest two options for you:

The efficient practice (IMO) for this can be to detect schema changes using DDL triggers and use them to alter the backup table accordingly. This will enable you to use the 'select * from...' approach, because the column list will be consistent between the two tables.

I have used this approach successfully and you can leverage it to have DDL triggers automatically manage your auditing tables. In my case, I used a naming convention for a table requiring audits and the DDL trigger just managed it on the fly.

Another option that might be useful for your specific scenario is to create a supporting view for the tables aligning the column list. Here's a quick example:

create table foo (id int, name varchar(50))
create table foo_bk (id int, name varchar(50), tagid int)
go

create view vw_foo as select id,name from foo 
go

create view vw_foo_bk as select id,name from foo_bk
go

insert into vw_foo
    select * from vw_foo_bk 
go

drop view vw_foo
drop view vw_foo_bk
drop table foo
drop table foo_bk
go

I hope this helps :)

Javascript to sort contents of select element

I used this bubble sort because I wasnt able to order them by the .value in the options array and it was a number. This way I got them properly ordered. I hope it's useful to you too.

function sortSelect(selElem) {
  for (var i=0; i<(selElem.options.length-1); i++)
      for (var j=i+1; j<selElem.options.length; j++)
          if (parseInt(selElem.options[j].value) < parseInt(selElem.options[i].value)) {
              var dummy = new Option(selElem.options[i].text, selElem.options[i].value);
              selElem.options[i] = new Option(selElem.options[j].text, selElem.options[j].value);
              selElem.options[j] = dummy;
          }
}

Toggle Checkboxes on/off

Since jQuery 1.6 you can use .prop(function) to toggle the checked state of each found element:

$("input[name=recipients\\[\\]]").prop('checked', function(_, checked) {
    return !checked;
});

Calculate summary statistics of columns in dataframe

Now there is the pandas_profiling package, which is a more complete alternative to df.describe().

If your pandas dataframe is df, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.

import pandas_profiling
pandas_profiling.ProfileReport(df)

See the example notebook detailing the usage.

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

OMG Ponies's answer works perfectly, but just in case you need something more complex, here is an example of a slightly more advanced update query:

UPDATE table1 
SET col1 = subquery.col2,
    col2 = subquery.col3 
FROM (
    SELECT t2.foo as col1, t3.bar as col2, t3.foobar as col3 
    FROM table2 t2 INNER JOIN table3 t3 ON t2.id = t3.t2_id
    WHERE t2.created_at > '2016-01-01'
) AS subquery
WHERE table1.id = subquery.col1;

LINQ - Full Outer Join

My clean solution for situation that key is unique in both enumerables:

 private static IEnumerable<TResult> FullOuterJoin<Ta, Tb, TKey, TResult>(
            IEnumerable<Ta> a, IEnumerable<Tb> b,
            Func<Ta, TKey> key_a, Func<Tb, TKey> key_b,
            Func<Ta, Tb, TResult> selector)
        {
            var alookup = a.ToLookup(key_a);
            var blookup = b.ToLookup(key_b);
            var keys = new HashSet<TKey>(alookup.Select(p => p.Key));
            keys.UnionWith(blookup.Select(p => p.Key));
            return keys.Select(key => selector(alookup[key].FirstOrDefault(), blookup[key].FirstOrDefault()));
        }

so

    var ax = new[] {
        new { id = 1, first_name = "ali" },
        new { id = 2, first_name = "mohammad" } };
    var bx = new[] {
        new { id = 1, last_name = "rezaei" },
        new { id = 3, last_name = "kazemi" } };

    var list = FullOuterJoin(ax, bx, a => a.id, b => b.id, (a, b) => "f: " + a?.first_name + " l: " + b?.last_name).ToArray();

outputs:

f: ali l: rezaei
f: mohammad l:
f:  l: kazemi

Save and load MemoryStream to/from a file

For anyone looking for the short versions:

var memoryStream = new MemoryStream(File.ReadAllBytes("1.dat"));

File.WriteAllBytes("1.dat", memoryStream.ToArray()); 

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

The root problem here seems that iOS8 safari won't hide the address bar when scrolling down if the content is equal or less than the viewport.

As you found out already, adding some padding at the bottom gets around this issue:

html {
    /* enough space to scroll up to get fullscreen on iOS8 */
    padding-bottom: 80px;
}
// sort of emulate safari's "bounce back to top" scroll
window.addEventListener('scroll', function(ev) {
    // avoids scrolling when the focused element is e.g. an input
    if (
        !document.activeElement
        || document.activeElement === document.body
    ) {
        document.body.scrollIntoViewIfNeeded(true);
    }
});

The above css should be conditionally applied, for example with UA sniffing adding a gt-ios8 class to <html>.

c# regex matches example

It looks like most of post here described what you need here. However - something you might need more complex behavior - depending on what you're parsing. In your case it might be so that you won't need more complex parsing - but it depends what information you're extracting.

You can use regex groups as field name in class, after which could be written for example like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

public class Info
{
    public String Identifier;
    public char nextChar;
};

class testRegex {

    const string input = "Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. " +
    "Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.";

    static void Main(string[] args)
    {
        Regex regex = new Regex(@"%download%#(?<Identifier>[0-9]*)(?<nextChar>.)(?<thisCharIsNotNeeded>.)");
        List<Info> infos = new List<Info>();

        foreach (Match match in regex.Matches(input))
        {
            Info info = new Info();
            for( int i = 1; i < regex.GetGroupNames().Length; i++ )
            {
                String groupName = regex.GetGroupNames()[i];

                FieldInfo fi = info.GetType().GetField(regex.GetGroupNames()[i]);

                if( fi != null ) // Field is non-public or does not exists.
                    fi.SetValue( info, Convert.ChangeType( match.Groups[groupName].Value, fi.FieldType));
            }
            infos.Add(info);
        }

        foreach ( var info in infos )
        {
            Console.WriteLine(info.Identifier + " followed by '" + info.nextChar.ToString() + "'");
        }
    }

};

This mechanism uses C# reflection to set value to class. group name is matched against field name in class instance. Please note that Convert.ChangeType won't accept any kind of garbage.

If you want to add tracking of line / column - you can add extra Regex split for lines, but in order to keep for loop intact - all match patterns must have named groups. (Otherwise column index will be calculated incorrectly)

This will results in following output:

456 followed by ' '
3434 followed by ' '
298 followed by '.'
893434 followed by ' '

Set a form's action attribute when submitting?

You can also set onSubmit attribute's value in form tag. You can set its value using Javascript.

Something like this:

<form id="whatever" name="whatever" onSubmit="return xyz();">
    Here is your entire form
    <input type="submit">
</form>;

<script type=text/javascript>
function xyz() {
  document.getElementById('whatever').action = 'whatever you want'
}
</script>

Remember that onSubmit has higher priority than action attribute. So whenever you specify onSubmit value, that operation will be performed first and then the form will move to action.

Excel VBA Open a Folder

I use this to open a workbook and then copy that workbook's data to the template.

Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
 With Application.FileDialog(msoFileDialogOpen)
    .InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
    .Filters.Clear
    .Title = "Your Title"
    If Not .Show Then
        MsgBox "No file selected.": Exit Sub
    End If
    Workbooks.OpenText .SelectedItems(1)

'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1

    Set myfile = ActiveWorkbook
    ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
    myfile.Close
    Template.Activate
    ActiveSheet.Cells.Select
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Select
    ActiveSheet.Paste

End With

HTML CSS How to stop a table cell from expanding

<table border="1" width="183" style='table-layout:fixed'>
  <col width="67">
  <col width="75">
  <col width="41">
  <tr>
    <td>First Column</td>
    <td>Second Column</td>
    <td>Third Column</td>
  </tr>
  <tr>
    <td>Row 1</td>
    <td>Text</td>
    <td align="right">1</td>
  </tr>
  <tr>
    <td>Row 2</td>
    <td>Abcdefg</td>
    <td align="right">123</td>
  </tr>
  <tr>
    <td>Row 3</td>
    <td>Abcdefghijklmnop</td>
    <td align="right">123456</td>
  </tr>
</table>

I know it's old school, but give that a try, it works.

may also want to add this:

<style>
  td {overflow:hidden;}
</style>

Of course, you'd put this in a separate linked stylesheet, and not inline... wouldn't you ;)

How to append to New Line in Node.js

Use the os.EOL constant instead.

var os = require("os");

function processInput ( text ) 
{     
  fs.open('H://log.txt', 'a', 666, function( e, id ) {
   fs.write( id, text + os.EOL, null, 'utf8', function(){
    fs.close(id, function(){
     console.log('file is updated');
    });
   });
  });
 }

Uncaught SyntaxError: Unexpected token < On Chrome

My solution to this is pretty unbelievable.

<script type="text/javascript" src="/js/dataLayer.js?v=1"></script>

The filename in the src attribute needed to be lowercase:

<script type="text/javascript" src="/js/datalayer.js?v=1"></script>

and that somewhat inexplicably fixed the problem.

In both cases the reference was returning 404 for testing.

Importing files from different folder

I usually create a symlink to the module I want to import. The symlink makes sure Python interpreter can locate the module inside the current directory (the script you are importing the other module into); later on when your work is over, you can remove the symlink. Also, you should ignore symlinks in .gitignore, so that, you wouldn't accidentally commit symlinked modules to your repo. This approach lets you even successfully work with modules that are located parallel to the script you are executing.

ln -s ~/path/to/original/module/my_module ~/symlink/inside/the/destination/directory/my_module

Get current cursor position

You get the cursor position by calling GetCursorPos.

POINT p;
if (GetCursorPos(&p))
{
    //cursor position now in p.x and p.y
}

This returns the cursor position relative to screen coordinates. Call ScreenToClient to map to window coordinates.

if (ScreenToClient(hwnd, &p))
{
    //p.x and p.y are now relative to hwnd's client area
}

You hide and show the cursor with ShowCursor.

ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again

You must ensure that every call to hide the cursor is matched by one that shows it again.

What are the differences between .gitignore and .gitkeep?

.gitkeep is just a placeholder. A dummy file, so Git will not forget about the directory, since Git tracks only files.


If you want an empty directory and make sure it stays 'clean' for Git, create a .gitignore containing the following lines within:

# .gitignore sample
###################

# Ignore all files in this dir...
*

# ... except for this one.
!.gitignore

If you desire to have only one type of files being visible to Git, here is an example how to filter everything out, except .gitignore and all .txt files:

# .gitignore to keep just .txt files
###################################

# Filter everything...
*

# ... except the .gitignore...
!.gitignore

# ... and all text files.
!*.txt

('#' indicates comments.)

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

How do I format a Microsoft JSON date?

You can use this to get a date from JSON:

var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));

And then you can use a JavaScript Date Format script (1.2 KB when minified and gzipped) to display it as you want.

websocket closing connection automatically

Just found the solution to this for myself. What you want to set is the maxIdleTime of WebSocketServlet, in millis. How to do that depends on how you config your servlet. With Guice ServletModule you can do something like this for timeout of 10 hours:

serve("ws").with(MyWSServlet.class, 
new HashMap<String, Sring>(){{ put("maxIdleTime", TimeUnit.HOURS.toMillis(10) + ""); }});

Anything <0 is infinite idle time I believe.

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

I solved this issue for myself, I found there's was two files of http-client with different version of other dependent jar files. So there may version were collapsing between libraries files so remove all old/previous libraries files and re-add are jar files from lib folder of this zip file:

Donwload Zip file from here

SQL Server : How to test if a string has only digit characters

Use Not Like

where some_column NOT LIKE '%[^0-9]%'

Demo

declare @str varchar(50)='50'--'asdarew345'

select 1 where @str NOT LIKE '%[^0-9]%'

What is the best regular expression to check if a string is a valid URL?

If you would like to apply a more strict rule, here is what I have developed:

isValidUrl(input) {
    var regex = /^(((H|h)(T|t)(T|t)(P|p)(S|s)?):\/\/)?[-a-zA-Z0-9@:%._\+~#=]{2,100}\.[a-zA-Z]{2,10}(\/([-a-zA-Z0-9@:%_\+.~#?&//=]*))?/
    return regex.test(input)
}

get unique machine id

Check out this article. It is very exhaustive and you will find how to extract various hardware information.

Quote from the article:

To get hardware information, you need to create an object of ManagementObjectSearcher class.

using System.Management;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key);
foreach (ManagementObject share in searcher.Get()) {
    // Some Codes ...
}

The Key on the code above, is a variable that is replaced with appropriate data. For example, to get the information of the CPU, you have to replace the Key with Win32_Processor.

unsigned APK can not be installed

You cannot install an unsigned application on a phone. You can only use it to test with an emulator. If you still want to go ahead, you can try self-signing the application.

Also, since you are installing the application from an SD card, I hope you have the necessary permissions set. Do go through stackoverflow.com and look at questions regarding installation of applications from an SD card - there have been many and they have been asked before.

Hope that helps.

How to compile c# in Microsoft's new Visual Studio Code?

Since no one else said it, the short-cut to compile (build) a C# app in Visual Studio Code (VSCode) is SHIFT+CTRL+B.

If you want to see the build errors (because they don't pop-up by default), the shortcut is SHIFT+CTRL+M.

(I know this question was asking for more than just the build shortcut. But I wanted to answer the question in the title, which wasn't directly answered by other answers/comments.)

Eclipse: Java was started but returned error code=13

Since you didn't mention the version of Eclipse, I advice you to download the latest version of Eclipse Luna which comes with Java 8 support by default.

download a file from Spring boot rest service

I would suggest using a StreamingResponseBody since with it the application can write directly to the response (OutputStream) without holding up the Servlet container thread. It is a good approach if you are downloading a file very large.

@GetMapping("download")
public StreamingResponseBody downloadFile(HttpServletResponse response, @PathVariable Long fileId) {

    FileInfo fileInfo = fileService.findFileInfo(fileId);
    response.setContentType(fileInfo.getContentType());
    response.setHeader(
        HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + fileInfo.getFilename() + "\"");

    return outputStream -> {
        int bytesRead;
        byte[] buffer = new byte[BUFFER_SIZE];
        InputStream inputStream = fileInfo.getInputStream();
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
    };
}

Ps.: When using StreamingResponseBody, it is highly recommended to configure TaskExecutor used in Spring MVC for executing asynchronous requests. TaskExecutor is an interface that abstracts the execution of a Runnable.

More info: https://medium.com/swlh/streaming-data-with-spring-boot-restful-web-service-87522511c071

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

A solution I came up with is to use a vis.js instance in an iframe. This shows an interactive 3D plot inside a notebook, which still works in nbviewer. The visjs code is borrowed from the example code on the 3D graph page

A small notebook to illustrate this: demo

The code itself:

from IPython.core.display import display, HTML
import json

def plot3D(X, Y, Z, height=600, xlabel = "X", ylabel = "Y", zlabel = "Z", initialCamera = None):

    options = {
        "width": "100%",
        "style": "surface",
        "showPerspective": True,
        "showGrid": True,
        "showShadow": False,
        "keepAspectRatio": True,
        "height": str(height) + "px"
    }

    if initialCamera:
        options["cameraPosition"] = initialCamera

    data = [ {"x": X[y,x], "y": Y[y,x], "z": Z[y,x]} for y in range(X.shape[0]) for x in range(X.shape[1]) ]
    visCode = r"""
       <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.css" type="text/css" rel="stylesheet" />
       <script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.min.js"></script>
       <div id="pos" style="top:0px;left:0px;position:absolute;"></div>
       <div id="visualization"></div>
       <script type="text/javascript">
        var data = new vis.DataSet();
        data.add(""" + json.dumps(data) + """);
        var options = """ + json.dumps(options) + """;
        var container = document.getElementById("visualization");
        var graph3d = new vis.Graph3d(container, data, options);
        graph3d.on("cameraPositionChange", function(evt)
        {
            elem = document.getElementById("pos");
            elem.innerHTML = "H: " + evt.horizontal + "<br>V: " + evt.vertical + "<br>D: " + evt.distance;
        });
       </script>
    """
    htmlCode = "<iframe srcdoc='"+visCode+"' width='100%' height='" + str(height) + "px' style='border:0;' scrolling='no'> </iframe>"
    display(HTML(htmlCode))

How to center Font Awesome icons horizontally?

Use text-align: center; on the block container of the icon (the <td>) - text-align doesn't apply to inline elements, only block containers:

td {
    text-align: center;
}

http://jsfiddle.net/kB6Ju/2/

Add content to a new open window

in parent.html:

<script type="text/javascript">
    $(document).ready(function () {
        var output = "data";
        var OpenWindow = window.open("child.html", "mywin", '');
        OpenWindow.dataFromParent = output; // dataFromParent is a variable in child.html
        OpenWindow.init();
    });
</script>

in child.html:

<script type="text/javascript">
    var dataFromParent;    
    function init() {
        document.write(dataFromParent);
    }
</script>

Disabling swap files creation in vim

If you put set directory="" in your exrc file, you will turn off the swap file. However, doing so will disable recovery.

More info here.

VSCode: How to Split Editor Vertically

I just found a simple solution. You can drag an opened file and move towards the four sides of the Editor, it will show a highlighted area that you can drop to. It will split the view automatically, either horizontally, vertically, or even into three rows.

VSCode v1.30.2

Update: you can also drag a file from the Explorer to split the Editor in the same way above.

Absolute Positioning & Text Alignment

position: absolute;
color: #ffffff;
font-weight: 500;
top: 0%;
left: 0%;
right: 0%;
text-align: center;

Get only records created today in laravel

$records = User::where('created_at' = CURDATE())->GET()); print($records);

How to kill all processes with a given partial name?

you can use the following command to list the process

ps aux | grep -c myProcessName 

if you need to check the count of that process then run

ps aux | grep -c myProcessName |grep -v grep 

after which you can kill the process using

kill -9 $(ps aux | grep -e myProcessName | awk '{ print $2 }') 

Open file dialog box in JavaScript

This is what worked best for me (Tested on IE8, FF, Chrome, Safari).

_x000D_
_x000D_
#file-input {_x000D_
  cursor: pointer;_x000D_
  outline: none;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  overflow: hidden;_x000D_
  filter: alpha(opacity=0); /* IE < 9 */_x000D_
  opacity: 0;_x000D_
}_x000D_
.input-label {_x000D_
  cursor: pointer;_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
}
_x000D_
<label for="file-input" class="input-label">_x000D_
  Click Me <!-- Replace with whatever text or icon you wish to use -->_x000D_
  <input type="file" id="file-input">_x000D_
</label>
_x000D_
_x000D_
_x000D_

Explanation: I positioned the file input directly above the element to be clicked, so any clicks would either land on it or its label (which pulls up the upload dialog just as if you clicked the label itself). I had some issues with the button part of the default input sticking out of the side of the label, so overflow: hidden on the input and display: inline-block on the label were necessary.

How can I iterate JSONObject to get individual items

You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .

public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
    Iterator<String> keys = json.keys();
    while(keys.hasNext()){
        String key = keys.next();
        String val = null;
        try{
             JSONObject value = json.getJSONObject(key);
             parse(value,out);
        }catch(Exception e){
            val = json.getString(key);
        }

        if(val != null){
            out.put(key,val);
        }
    }
    return out;
}

 public static void main(String[] args) throws JSONException {

    String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";

    JSONObject object = new JSONObject(json);

    JSONObject info = object.getJSONObject("ipinfo");

    Map<String,String> out = new HashMap<String, String>();

    parse(info,out);

    String latitude = out.get("latitude");
    String longitude = out.get("longitude");
    String city = out.get("city");
    String state = out.get("state");
    String country = out.get("country");
    String postal = out.get("postal_code");

    System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);

    System.out.println("ALL VALUE " + out);

}

Output:

    Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}

How to use the priority queue STL for objects?

A priority queue is an abstract data type that captures the idea of a container whose elements have "priorities" attached to them. An element of highest priority always appears at the front of the queue. If that element is removed, the next highest priority element advances to the front.

The C++ standard library defines a class template priority_queue, with the following operations:

push: Insert an element into the prioity queue.

top: Return (without removing it) a highest priority element from the priority queue.

pop: Remove a highest priority element from the priority queue.

size: Return the number of elements in the priority queue.

empty: Return true or false according to whether the priority queue is empty or not.

The following code snippet shows how to construct two priority queues, one that can contain integers and another one that can contain character strings:

#include <queue>

priority_queue<int> q1;
priority_queue<string> q2;

The following is an example of priority queue usage:

#include <string>
#include <queue>
#include <iostream>

using namespace std;  // This is to make available the names of things defined in the standard library.

int main()
{
    piority_queue<string> pq; // Creates a priority queue pq to store strings, and initializes the queue to be empty.

    pq.push("the quick");
    pq.push("fox");
    pq.push("jumped over");
    pq.push("the lazy dog");

    // The strings are ordered inside the priority queue in lexicographic (dictionary) order:
    // "fox", "jumped over", "the lazy dog", "the quick"
    //  The lowest priority string is "fox", and the highest priority string is "the quick"

    while (!pq.empty()) {
       cout << pq.top() << endl;  // Print highest priority string
       pq.pop();                    // Remmove highest priority string
    }

    return 0;
}

The output of this program is:

the quick
the lazy dog
jumped over
fox

Since a queue follows a priority discipline, the strings are printed from highest to lowest priority.

Sometimes one needs to create a priority queue to contain user defined objects. In this case, the priority queue needs to know the comparison criterion used to determine which objects have the highest priority. This is done by means of a function object belonging to a class that overloads the operator (). The overloaded () acts as < for the purpose of determining priorities. For example, suppose we want to create a priority queue to store Time objects. A Time object has three fields: hours, minutes, seconds:

struct Time {
    int h; 
    int m; 
    int s;
};

class CompareTime {
    public:
    bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2
    {
       if (t1.h < t2.h) return true;
       if (t1.h == t2.h && t1.m < t2.m) return true;
       if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
       return false;
    }
}

A priority queue to store times according the the above comparison criterion would be defined as follows:

priority_queue<Time, vector<Time>, CompareTime> pq;

Here is a complete program:

#include <iostream>
#include <queue>
#include <iomanip>

using namespace std;

struct Time {
    int h; // >= 0
    int m; // 0-59
    int s; // 0-59
};

class CompareTime {
public:
    bool operator()(Time& t1, Time& t2)
    {
       if (t1.h < t2.h) return true;
       if (t1.h == t2.h && t1.m < t2.m) return true;
       if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
       return false;
    }
};

int main()
{
    priority_queue<Time, vector<Time>, CompareTime> pq;

    // Array of 4 time objects:

    Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};

    for (int i = 0; i < 4; ++i)
       pq.push(t[i]);

    while (! pq.empty()) {
       Time t2 = pq.top();
       cout << setw(3) << t2.h << " " << setw(3) << t2.m << " " <<
       setw(3) << t2.s << endl;
       pq.pop();
    }

    return 0;
}

The program prints the times from latest to earliest:

5  16  13
5  14  20
3   2  40
3   2  26

If we wanted earliest times to have the highest priority, we would redefine CompareTime like this:

class CompareTime {
public:
    bool operator()(Time& t1, Time& t2) // t2 has highest prio than t1 if t2 is earlier than t1
    {
       if (t2.h < t1.h) return true;
       if (t2.h == t1.h && t2.m < t1.m) return true;
       if (t2.h == t1.h && t2.m == t1.m && t2.s < t1.s) return true;
       return false;
    }
};

Can someone explain mappedBy in JPA and Hibernate?

mappedby speaks for itself, it tells hibernate not to map this field. it's already mapped by this field [name="field"].
field is in the other entity (name of the variable in the class not the table in the database)..

If you don't do that, hibernate will map this two relation as it's not the same relation

so we need to tell hibernate to do the mapping in one side only and co-ordinate between them.

Access host database from a docker container

There are several long standing discussions about how to do this in a consistent, well understood and portable way. No complete resolution but I'll link you to the discussions below.

In any event you many want to try using the --add-host option to docker run to add the ip address of the host into the container's /etc/host file. From there it's trivial to connect to the host on any required port:

Adding entries to a container hosts file

You can add other hosts into a container's /etc/hosts file by using one or more --add-host flags. This example adds a static address for a host named docker:

 $ docker run --add-host=docker:10.180.0.1 --rm -it debian
    $$ ping docker
    PING docker (10.180.0.1): 48 data bytes
    56 bytes from 10.180.0.1: icmp_seq=0 ttl=254 time=7.600 ms
    56 bytes from 10.180.0.1: icmp_seq=1 ttl=254 time=30.705 ms
    ^C--- docker ping statistics ---
    2 packets transmitted, 2 packets received, 0% packet loss
    round-trip min/avg/max/stddev = 7.600/19.152/30.705/11.553 ms

Note: Sometimes you need to connect to the Docker host, which means getting the IP address of the host. You can use the following shell commands to simplify this process:

 $ alias hostip="ip route show 0.0.0.0/0 | grep -Eo 'via \S+' | awk '{ print $2 }'"
 $ docker run  --add-host=docker:$(hostip) --rm -it debian

Documentation:

https://docs.docker.com/engine/reference/commandline/run/

Discussions on accessing host from container:

https://github.com/docker/docker/issues/1143

https://github.com/docker/docker/issues/10023

store and retrieve a class object in shared preference

Do you need to retrieve the object even after the application shutting donw or just during it's running ?

You can store it into a database.
Or Simply create a custom Application class.

public class MyApplication extends Application {

    private static Object mMyObject;
    // static getter & setter
    ...
}

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application ... android:name=".MyApplication">
        <activity ... />
        ...
    </application>
    ...
</manifest>

And then from every activities do :

((MyApplication) getApplication).getMyObject();

Not really the best way but it works.

How to switch text case in visual studio code

I've written a Visual Studio Code extension for changing case (not only upper case, many other options): https://github.com/wmaurer/vscode-change-case

To map the upper case command to a keybinding (e.g. Ctrl+T U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:

{
  "key": "ctrl+t u",
  "command": "extension.changeCase.upper",
  "when": "editorTextFocus"
}




EDIT:

With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase and editor.action.transformToLowercase. These don't have default keybindings.

The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake-case, etc.

Angular pass callback function to child component as @Input similar to AngularJS way

An alternative to the answer Max Fahl gave.

You can define callback function as an arrow function in the parent component so that you won't need to bind that.

_x000D_
_x000D_
@Component({_x000D_
  ..._x000D_
  // unlike this, template: '<child [myCallback]="theCallback.bind(this)"></child>',_x000D_
  template: '<child [myCallback]="theCallback"></child>',_x000D_
  directives: [ChildComponent]_x000D_
})_x000D_
export class ParentComponent {_x000D_
_x000D_
   // unlike this, public theCallback(){_x000D_
   public theCallback = () => {_x000D_
    ..._x000D_
  }_x000D_
}_x000D_
_x000D_
@Component({...})_x000D_
export class ChildComponent{_x000D_
  //This will be bound to the ParentComponent.theCallback_x000D_
  @Input()_x000D_
  public myCallback: Function; _x000D_
  ..._x000D_
}
_x000D_
_x000D_
_x000D_

Code coverage with Mocha

Blanket.js works perfect too.

npm install --save-dev blanket

in front of your test/tests.js

require('blanket')({
    pattern: function (filename) {
        return !/node_modules/.test(filename);
    }
});

run mocha -R html-cov > coverage.html

SQL Query to fetch data from the last 30 days?

SELECT productid FROM product WHERE purchase_date > sysdate-30

Vim clear last search highlighting

If you want to be able to enable/disable highlighting quickly, you can map a key to

" Press F4 to toggle highlighting on/off, and show current value.
:noremap <F4> :set hlsearch! hlsearch?<CR>

Just put the above snippet in you .vimrc file.

That's the most convenient way for me to show and hide the search highlight with a sing key stroke

For more information check the documentation http://vim.wikia.com/wiki/Highlight_all_search_pattern_matches

How to add image in Flutter

  1. Create images folder in root level of your project.

    enter image description here

    enter image description here

  2. Drop your image in this folder, it should look like

    enter image description here

  3. Go to your pubspec.yaml file, add assets header and pay close attention to all the spaces.

    flutter:
    
      uses-material-design: true
    
      # add this
      assets:
        - images/profile.jpg
    
  4. Tap on Packages get at the top right corner of the IDE.

    enter image description here

  5. Now you can use your image anywhere using

    Image.asset("images/profile.jpg")
    

Java - Reading XML file

Reading xml the easy way:

http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

} 

.

package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

          } catch (JAXBException e) {
              e.printStackTrace();
          }

    }
}

How to expand 'select' option width after the user wants to select an option

I fixed it in my bootstrap page by setting the min-width and max-width to the same value in the select and then setting the select:focus to auto.

_x000D_
_x000D_
select {_x000D_
  min-width: 120px;_x000D_
  max-width: 120px;_x000D_
}_x000D_
select:focus {_x000D_
  width: auto;_x000D_
}
_x000D_
<select style="width: 120px">_x000D_
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>_x000D_
  <option>ABC</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

demo - http://jsfiddle.net/victor_007/ywevz8ra/

added border for better view (testing)

more info about white-space

table{
    width:100%;
}
table td{
    white-space: nowrap;  /** added **/
}
table td:last-child{
    width:100%;
}

_x000D_
_x000D_
    table {_x000D_
      width: 100%;_x000D_
    }_x000D_
    table td {_x000D_
      white-space: nowrap;_x000D_
    }_x000D_
    table td:last-child {_x000D_
      width: 100%;_x000D_
    }
_x000D_
<table border="1">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column A</th>_x000D_
      <th>Column B</th>_x000D_
      <th>Column C</th>_x000D_
      <th class="absorbing-column">Column D</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Data A.1 lorem</td>_x000D_
      <td>Data B.1 ip</td>_x000D_
      <td>Data C.1 sum l</td>_x000D_
      <td>Data D.1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.2 ipsum</td>_x000D_
      <td>Data B.2 lorem</td>_x000D_
      <td>Data C.2 some data</td>_x000D_
      <td>Data D.2 a long line of text that is long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.3</td>_x000D_
      <td>Data B.3</td>_x000D_
      <td>Data C.3</td>_x000D_
      <td>Data D.3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Count number of days between two dates

To have the number of whole days between two dates (DateTime objects):

((end_at - start_at).to_f / 1.day).floor

Implements vs extends: When to use? What's the difference?

We use SubClass extends SuperClass only when the subclass wants to use some functionality (methods or instance variables) that is already declared in the SuperClass, or if I want to slightly modify the functionality of the SuperClass (Method overriding). But say, I have an Animal class(SuperClass) and a Dog class (SubClass) and there are few methods that I have defined in the Animal class eg. doEat(); , doSleep(); ... and many more.

Now, my Dog class can simply extend the Animal class, if i want my dog to use any of the methods declared in the Animal class I can invoke those methods by simply creating a Dog object. So this way I can guarantee that I have a dog that can eat and sleep and do whatever else I want the dog to do.

Now, imagine, one day some Cat lover comes into our workspace and she tries to extend the Animal class(cats also eat and sleep). She makes a Cat object and starts invoking the methods.

But, say, someone tries to make an object of the Animal class. You can tell how a cat sleeps, you can tell how a dog eats, you can tell how an elephant drinks. But it does not make any sense in making an object of the Animal class. Because it is a template and we do not want any general way of eating.

So instead, I will prefer to make an abstract class that no one can instantiate but can be used as a template for other classes.

So to conclude, Interface is nothing but an abstract class(a pure abstract class) which contains no method implementations but only the definitions(the templates). So whoever implements the interface just knows that they have the templates of doEat(); and doSleep(); but they have to define their own doEat(); and doSleep(); methods according to their need.

You extend only when you want to reuse some part of the SuperClass(but keep in mind, you can always override the methods of your SuperClass according to your need) and you implement when you want the templates and you want to define them on your own(according to your need).

I will share with you a piece of code: You try it with different sets of inputs and look at the results.

class AnimalClass {

public void doEat() {
    
    System.out.println("Animal Eating...");
}

public void sleep() {
    
    System.out.println("Animal Sleeping...");
}

}

public class Dog extends AnimalClass implements AnimalInterface, Herbi{

public static void main(String[] args) {
    
    AnimalInterface a = new Dog();
    Dog obj = new Dog();
    obj.doEat();
    a.eating();
    
    obj.eating();
    obj.herbiEating();
}

public void doEat() {
    System.out.println("Dog eating...");
}

@Override
public void eating() {
    
    System.out.println("Eating through an interface...");
    // TODO Auto-generated method stub
    
}

@Override
public void herbiEating() {
    
    System.out.println("Herbi eating through an interface...");
    // TODO Auto-generated method stub
    
}


}

Defined Interfaces :

public interface AnimalInterface {

public void eating();

}


interface Herbi {

public void herbiEating();

}

phpmyadmin "Not Found" after install on Apache, Ubuntu

The easiest way to do in ubuntu (I tested in ubuntu-20.04):

Step 1. Open the file:

sudo nano /etc/apache2/apache2.conf

Step 2: Add the following line at the end of file:

Include /etc/phpmyadmin/apache.conf

Step 3: Restart apache2:

sudo systemctl restart apache2.service

Hopefully, it'll be helpful!

How can I build for release/distribution on the Xcode 4?

The "play" button is specifically for build and run (or test or profile, etc). The Archive action is intended to build for release and to generate an archive that is suitable for submission to the app store. If you want to skip that, you can choose Product > Build For > Archive to force the release build without actually archiving. To find the built product, expand the Products group in the Project navigator, right-click the product and choose to show in Finder.

That said, you can click and hold the play button for a menu of other build actions (including Build and Archive).

How to set response header in JAX-RS so that user sees download popup for Excel?

You don't need HttpServletResponse to set a header on the response. You can do it using javax.ws.rs.core.Response. Just make your method to return Response instead of entity:

return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build()

If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:

@Path("/resource")
class MyResource {

  // one way to get HttpServletResponse
  @Context
  private HttpServletResponse anotherServletResponse;

  // another way
  Response myMethod(@Context HttpServletResponse servletResponse) {
      // ... code
  }
}

Fastest method to replace all instances of a character in a string

@Gumbo adding extra answer - user.email.replace(/foo/gi,"bar");

/foo/g - Refers to the all string to replace matching the case sensitive

/foo/gi - Refers to the without case sensitive and replace all For Eg: (Foo, foo, FoO, fOO)

DEMO

python requests get cookies

Alternatively, you can use requests.Session and observe cookies before and after a request:

>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}

ASP.NET Setting width of DataBound column in GridView

I did a small demo for you. Demonstrating how to display long text.

In this example there is a column Name which may contain very long text. The boundField will display all content in a table cell and therefore the cell will expand as needed (because of the content)

The TemplateField will also be rendered as a cell BUT it contains a div which limits the width of any contet to eg 40px. So this column will have some kind of max-width!

    <asp:GridView ID="gvPersons" runat="server" AutoGenerateColumns="False" Width="100px">
        <Columns>
            <asp:BoundField HeaderText="ID" DataField="ID" />
            <asp:BoundField HeaderText="Name (long)" DataField="Name">
                <ItemStyle Width="40px"></ItemStyle>
            </asp:BoundField>
            <asp:TemplateField HeaderText="Name (short)">
                <ItemTemplate>
                    <div style="width: 40px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis">
                        <%# Eval("Name") %>
                    </div>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

enter image description here

Here is my demo codeBehind

 public partial class gridViewLongText : System.Web.UI.Page
 {
     protected void Page_Load(object sender, EventArgs e)
     {
         #region init and bind data
         List<Person> list = new List<Person>();
         list.Add(new Person(1, "Sam"));
         list.Add(new Person(2, "Max"));
         list.Add(new Person(3, "Dave"));
         list.Add(new Person(4, "TabularasaVeryLongName"));
         gvPersons.DataSource = list;
         gvPersons.DataBind();
         #endregion
     }
 }

 public class Person
 {
     public int ID { get; set; }
     public string Name { get; set; }

     public Person(int _ID, string _Name)
     {
         ID = _ID;
         Name = _Name;
     }
 }

How to merge multiple dicts with same key or different key?

If keys are nested:

d1 = { 'key1': { 'nkey1': 'x1' }, 'key2': { 'nkey2': 'y1' } } 
d2 = { 'key1': { 'nkey1': 'x2' }, 'key2': { 'nkey2': 'y2' } }
ds = [d1, d2]
d = {}
for k in d1.keys():
    for k2 in d1[k].keys():
        d.setdefault(k, {})
        d[k].setdefault(k2, [])
        d[k][k2] = tuple(d[k][k2] for d in ds)

yields:

{'key1': {'nkey1': ('x1', 'x2')}, 'key2': {'nkey2': ('y1', 'y2')}}

Should I use int or Int32

It doesn't matter. int is the language keyword and Int32 its actual system type.

See also my answer here to a related question.

JSON to string variable dump

something along this?

function dump(x, indent) {
    var indent = indent || '';
    var s = '';
    if (Array.isArray(x)) {
        s += '[';
        for (var i=0; i<x.length; i++) {
            s += dump(x[i], indent)
            if (i < x.length-1) s += ', ';
        }
        s +=']';
    } else if (x === null) {
      s = 'NULL';
    } else switch(typeof x) {
        case 'undefined':
            s += 'UNDEFINED';
            break;
        case 'object':
            s += "{ ";
            var first = true;
            for (var p in x) {
                if (!first) s += indent + '  ';
                s += p + ': ';
                s += dump(x[p], indent + '  ');
                s += "\n"
                first = false;
            }
            s += '}';
            break;
        case 'boolean':
            s += (x) ? 'TRUE' : 'FALSE';
            break;
        case 'number':
            s += x;
            break;
        case 'string':
            s += '"' + x + '"';
            break;
        case 'function':
            s += '<FUNCTION>';
            break;
        default:
            s += x;
            break;
    }
    return s;
}

Measuring elapsed time with the Time module

For the best measure of elapsed time (since Python 3.3), use time.perf_counter().

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

For measurements on the order of hours/days, you don't care about sub-second resolution so use time.monotonic() instead.

Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

In many implementations, these may actually be the same thing.

Before 3.3, you're stuck with time.clock().

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.


Update for Python 3.7

New in Python 3.7 is PEP 564 -- Add new time functions with nanosecond resolution.

Use of these can further eliminate rounding and floating-point errors, especially if you're measuring very short periods, or your application (or Windows machine) is long-running.

Resolution starts breaking down on perf_counter() after around 100 days. So for example after a year of uptime, the shortest interval (greater than 0) it can measure will be bigger than when it started.


Update for Python 3.8

time.clock is now gone.

Is it a bad practice to use break in a for loop?

I disagree!

Why would you ignore the built-in functionality of a for loop to make your own? You do not need to reinvent the wheel.

I think it makes more sense to have your checks at the top of your for loop like so

for(int i = 0; i < myCollection.Length && myCollection[i].SomeValue != "Break Condition"; i++)
{
//loop body
}

or if you need to process the row first

for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
//loop body
}

This way you can write a function to perform everything and make much cleaner code.

for(int i = 0; i < myCollection.Length && (i == 0 ? true : myCollection[i-1].SomeValue != "Break Condition"); i++)
{
    DoAllThatCrazyStuff(myCollection[i]);
}

Or if your condition is complicated you can move that code out too!

for(int i = 0; i < myCollection.Length && BreakFunctionCheck(i, myCollection); i++)
{
    DoAllThatCrazyStuff(myCollection[i]);
}

"Professional Code" that is riddled with breaks doesn't really sound like professional code to me. It sounds like lazy coding ;)

How to set a timeout on a http.request() in Node?

2019 Update

There are various ways to handle this more elegantly now. Please see some other answers on this thread. Tech moves fast so answers can often become out of date fairly quickly. My answer will still work but it's worth looking at alternatives as well.

2012 Answer

Using your code, the issue is that you haven't waited for a socket to be assigned to the request before attempting to set stuff on the socket object. It's all async so:

var options = { ... }
var req = http.request(options, function(res) {
  // Usual stuff: on(data), on(end), chunks, etc...
});

req.on('socket', function (socket) {
    socket.setTimeout(myTimeout);  
    socket.on('timeout', function() {
        req.abort();
    });
});

req.on('error', function(err) {
    if (err.code === "ECONNRESET") {
        console.log("Timeout occurs");
        //specific error treatment
    }
    //other error treatment
});

req.write('something');
req.end();

The 'socket' event is fired when the request is assigned a socket object.

Case insensitive 'Contains(string)'

You could always just up or downcase the strings first.

string title = "string":
title.ToUpper().Contains("STRING")  // returns true

Oops, just saw that last bit. A case insensitive compare would *probably* do the same anyway, and if performance is not an issue, I don't see a problem with creating uppercase copies and comparing those. I could have sworn that I once saw a case-insensitive compare once...

What's the difference between "Solutions Architect" and "Applications Architect"?

An 'architect' is the title given to someone who can design multiple layers of applications that work together well at a high level. Anything that gets into a generic type of 'architect' without a specific type of technology (i.e. "Solutions", "Applications", "Business", etc) is marketing speak.

What is the difference between `sorted(list)` vs `list.sort()`?

sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations).

sorted() works on any iterable, not just lists. Strings, tuples, dictionaries (you'll get the keys), generators, etc., returning a list containing all elements, sorted.

  • Use list.sort() when you want to mutate the list, sorted() when you want a new sorted object back. Use sorted() when you want to sort something that is an iterable, not a list yet.

  • For lists, list.sort() is faster than sorted() because it doesn't have to create a copy. For any other iterable, you have no choice.

  • No, you cannot retrieve the original positions. Once you called list.sort() the original order is gone.

"unary operator expected" error in Bash if condition

If you know you're always going to use bash, it's much easier to always use the double bracket conditional compound command [[ ... ]], instead of the Posix-compatible single bracket version [ ... ]. Inside a [[ ... ]] compound, word-splitting and pathname expansion are not applied to words, so you can rely on

if [[ $aug1 == "and" ]];

to compare the value of $aug1 with the string and.

If you use [ ... ], you always need to remember to double quote variables like this:

if [ "$aug1" = "and" ];

If you don't quote the variable expansion and the variable is undefined or empty, it vanishes from the scene of the crime, leaving only

if [ = "and" ]; 

which is not a valid syntax. (It would also fail with a different error message if $aug1 included white space or shell metacharacters.)

The modern [[ operator has lots of other nice features, including regular expression matching.

Why doesn't [01-12] range work as expected?

This also works:

^([1-9]|[0-1][0-2])$

[1-9] matches single digits between 1 and 9

[0-1][0-2] matches double digits between 10 and 12

There are some good examples here

how to display employee names starting with a and then b in sql

select name_last, name_first
from employees
where name_last like 'A%' or name_last like 'B%'
order by name_last, name_first asc

Bootstrap 3 - Responsive mp4-video

Simply add class="img-responsive" to the video tag. I'm doing this on a current project, and it works. It doesn't need to be wrapped in anything.

<video class="img-responsive" src="file.mp4" autoplay loop/>

Is there a vr (vertical rule) in html?

Too many overly-complicated answers. Just make a TableData tag that spans how many rows you want it to using rowspan. Then use the right-border for the actual bar.

Example:

<td rowspan="5" style="border-right-color: #000000; border-right-width: thin; border-right-style: solid">&nbsp;</td>
<td rowspan="5">&nbsp;</td>

Ensure that the "&nbsp" in the second line runs the same amount of lines as the first. so that there's proper spacing between both.

This technique has served me rather well with my time in HTML5.

Setting up enviromental variables in Windows 10 to use java and javac

if you have any version problems (javac -version=15.0.1, java -version=1.8.0)
windows search : edit environment variables for your account
then delete these in your windows Environment variable: system variable: Path
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
C:\Program Files\Common Files\Oracle\Java\javapath

then if you're using java 15
environment variable: system variable : Path
add path C:\Program Files\Java\jdk-15.0.1\bin
is enough

if you're using java 8

  • create JAVA_HOME
  • environment variable: system variable : JAVA_HOME
    JAVA_HOME = C:\Program Files\Java\jdk1.8.0_271
  • environment variable: system variable : Path
    add path = %JAVA_HOME%\bin
  • What's the difference between 'int?' and 'int' in C#?

    the symbol ? after the int means that it can be nullable.

    The ? symbol is usually used in situations whereby the variable can accept a null or an integer or alternatively, return an integer or null.

    Hope the context of usage helps. In this way you are not restricted to solely dealing with integers.

    jQuery $("#radioButton").change(...) not firing during de-selection

    With Ajax, for me worked:

    Html:

    <div id='anID'>
     <form name="nameOfForm">
                <p><b>Your headline</b></p>
                <input type='radio' name='nameOfRadio' value='seed' 
                 <?php if ($interviewStage == 'seed') {echo" checked ";}?> 
                onchange='funcInterviewStage()'><label>Your label</label><br>
     </form>
    </div>
    

    Javascript:

     function funcInterviewStage() {
    
                    var dis = document.nameOfForm.nameOfRadio.value;
    
                    //Auswahltafel anzeigen
                      if (dis == "") {
                          document.getElementById("anID").innerHTML = "";
                          return;
                      } else { 
                          if (window.XMLHttpRequest) {
                              // code for IE7+, Firefox, Chrome, Opera, Safari
                              xmlhttp = new XMLHttpRequest();
                          } else {
                              // code for IE6, IE5
                              xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                          }
                          xmlhttp.onreadystatechange = function() {
                              if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                                  document.getElementById("anID").innerHTML = xmlhttp.responseText;
                              }
                          }
                          xmlhttp.open("GET","/includes/[name].php?id="+dis,true);
                          xmlhttp.send();
                      }
                  }  
    

    And php:

    //// Get Value
    $id = mysqli_real_escape_string($db, $_GET['id']);
    
    //// Insert to database
    $insert = mysqli_query($db, "UPDATE [TABLE] SET [column] = '$id' WHERE [...]");
    
    //// Show radio buttons again
    $mysqliAbfrage = mysqli_query($db, "SELECT [column] FROM [Table] WHERE [...]");
                      while ($row = mysqli_fetch_object($mysqliAbfrage)) {
                        ...
                      }
                      echo" 
                      <form name='nameOfForm'>
                          <p><b>Your headline</b></p>
                          <input type='radio' name='nameOfRadio' value='seed'"; if ($interviewStage == 'seed') {echo" checked ";} echo" onchange='funcInterviewStage()'><label>Yourr Label</label><br>
                          <input type='radio' name='nameOfRadio' value='startup'"; if ($interviewStage == 'startup') {echo" checked ";} echo" onchange='funcInterviewStage()'><label>Your label</label><br>
    
                      </form> ";
    

    Bound method error

    I think you meant print test.sorted_word_list instead of print test.sort_word_list.

    In addition list.sort() sorts a list in place and returns None, so you probably want to change sort_word_list() to do the following:

    self.sorted_word_list = sorted(self.word_list)
    

    You should also consider either renaming your num_words() function, or changing the attribute that the function assigns to, because currently you overwrite the function with an integer on the first call.

    What does numpy.random.seed(0) do?

    A random seed specifies the start point when a computer generates a random number sequence.

    For example, let’s say you wanted to generate a random number in Excel (Note: Excel sets a limit of 9999 for the seed). If you enter a number into the Random Seed box during the process, you’ll be able to use the same set of random numbers again. If you typed “77” into the box, and typed “77” the next time you run the random number generator, Excel will display that same set of random numbers. If you type “99”, you’ll get an entirely different set of numbers. But if you revert back to a seed of 77, then you’ll get the same set of random numbers you started with.

    For example, “take a number x, add 900 +x, then subtract 52.” In order for the process to start, you have to specify a starting number, x (the seed). Let’s take the starting number 77:

    Add 900 + 77 = 977 Subtract 52 = 925 Following the same algorithm, the second “random” number would be:

    900 + 925 = 1825 Subtract 52 = 1773 This simple example follows a pattern, but the algorithms behind computer number generation are much more complicated

    Clear dropdown using jQuery Select2

    For Ajax, use $(".select2").val("").trigger("change"). That should solve the issue.

    Excel to CSV with UTF8 encoding

    What about using Powershell.

    Get-Content 'C:\my.csv' | Out-File 'C:\my_utf8.csv' -Encoding UTF8
    

    How to receive POST data in django

    res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data.

    Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise:

    $payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''
    

    The equivalent in python is to use the get() method with a default argument:

    payment_id = request.POST.get('payment_id', '')
    

    while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}>

    It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.

    Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.

    Swift - how to make custom header for UITableView?

    Did you set the section header height in the viewDidLoad?

    self.tableView.sectionHeaderHeight = 70
    

    Plus you should replace

    self.view.addSubview(view)
    

    by

    view.addSubview(label)
    

    Finally you have to check your frames

    let view = UIView(frame: CGRect.zeroRect)
    

    and eventually the desired text color as it seems to be currently white on white.

    0xC0000005: Access violation reading location 0x00000000

    This line looks suspicious:

    invaders[i] = inv;
    

    You're never incrementing i, so you keep assigning to invaders[0]. If this is just an error you made when reducing your code to the example, check how you calculate i in the real code; you could be exceeding the size of invaders.

    If as your comment suggests, you're creating 55 invaders, then check that invaders has been initialised correctly to handle this number.

    Make a borderless form movable?

    Another simpler way to do the same thing.

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            // set this.FormBorderStyle to None here if needed
            // if set to none, make sure you have a way to close the form!
        }
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == WM_NCHITTEST)
                m.Result = (IntPtr)(HT_CAPTION);
        }
    
        private const int WM_NCHITTEST = 0x84;
        private const int HT_CLIENT = 0x1;
        private const int HT_CAPTION = 0x2;
    }
    

    HTML -- two tables side by side

    With CSS: table {float:left;}? ?

    How can I write a heredoc to a file in Bash script?

    When root permissions are required

    When root permissions are required for the destination file, use |sudo tee instead of >:

    cat << 'EOF' |sudo tee /tmp/yourprotectedfilehere
    The variable $FOO will *not* be interpreted.
    EOF
    
    cat << "EOF" |sudo tee /tmp/yourprotectedfilehere
    The variable $FOO *will* be interpreted.
    EOF
    

    How can I open two pages from a single click without using JavaScript?

    Without JavaScript, it's not possible to open two pages by clicking one link unless both pages are framed on the one page that opens from clicking the link. With JS it's trivial:

    <p><a href="#" onclick="window.open('http://google.com');
        window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>
    

    Do note that this will be blocked by popup blockers built into web browsers but you are usually notified of this.

    Setting table column width

    Depending on your body (or the div which is wrapping your table) 'settings' you should be able to do this:

    body {
      width: 98%;
    }
    
    table {
      width: 100%;
    }
    
    
    th {
      border: 1px solid black;
    }
    
    
    th.From, th.Date {
      width: 15%;
    }
    
    th.Date {
      width: 70%;
    }
    
    
    <table>
      <thead>
        <tr>
          <th class="From">From</th>
          <th class="Subject">Subject</th>
          <th class="Date">Date</th>
        </tr>
       </thead>
       <tbody>
         <tr>
           <td>Me</td>
           <td>Your question</td>
           <td>5/30/2009 2:41:40 AM UTC</td>
         </tr>
       </tbody>
    </table>
    

    Demo

    Error Handler - Exit Sub vs. End Sub

    Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

    Public Sub SubA()
      On Error Goto ProcError
    
      Connection.Open
      Open File for Writing
      SomePreciousResource.GrabIt
    
    ProcExit:  
      Connection.Close
      Connection = Nothing
      Close File
      SomePreciousResource.Release
    
      Exit Sub
    
    ProcError:  
      MsgBox Err.Description  
      Resume ProcExit
    End Sub
    

    How to find all occurrences of a substring?

    def find_index(string, let):
        enumerated = [place  for place, letter in enumerate(string) if letter == let]
        return enumerated
    

    for example :

    find_index("hey doode find d", "d") 
    

    returns:

    [4, 7, 13, 15]
    

    How can I create my own comparator for a map?

    Since C++11, you can also use a lambda expression instead of defining a comparator struct:

    auto comp = [](const string& a, const string& b) { return a.length() < b.length(); };
    map<string, string, decltype(comp)> my_map(comp);
    
    my_map["1"]      = "a";
    my_map["three"]  = "b";
    my_map["two"]    = "c";
    my_map["fouuur"] = "d";
    
    for(auto const &kv : my_map)
        cout << kv.first << endl;
    

    Output:

    1
    two
    three
    fouuur

    I'd like to repeat the final note of Georg's answer: When comparing by length you can only have one string of each length in the map as a key.

    Code on Ideone

    Razor/CSHTML - Any Benefit over what we have?

    Ex Microsoft Developer's Opinion

    I worked on a core team for the MSDN website. Now, I use c# razor for ecommerce sites with my programming team and we focus heavy on jQuery front end with back end c# razor pages and LINQ-Entity memory database so the pages are 1-2 millisecond response times even on nested for loops with queries and no page caching. We don't use MVC, just plain ASP.NET with razor pages being mapped with URL Rewrite module for IIS 7, no ASPX pages or ViewState or server-side event programming at all. It doesn't have the extra (unnecessary) layers MVC puts in code constructs for the regex challenged. Less is more for us. Its all lean and mean but I give props to MVC for its testability but that's all.

    Razor pages have no event life cycle like ASPX pages. Its just rendering as one requested page. C# is such a great language and Razor gets out of its way nicely to let it do its job. The anonymous typing with generics and linq make life so easy with c# and razor pages. Using Razor pages will help you think and code lighter.

    One of the drawback of Razor and MVC is there is no ViewState-like persistence. I needed to implement a solution for that so I ended up writing a jQuery plugin for that here -> http://www.jasonsebring.com/dumbFormState which is an HTML 5 offline storage supported plugin for form state that is working in all major browsers now. It is just for form state currently but you can use window.sessionStorage or window.localStorage very simply to store any kind of state across postbacks or even page requests, I just bothered to make it autosave and namespace it based on URL and form index so you don't have to think about it.

    Excel VBA Run Time Error '424' object required

    The first code line, Option Explicit means (in simple terms) that all of your variables have to be explicitly declared by Dim statements. They can be any type, including object, integer, string, or even a variant.

    This line: Dim envFrmwrkPath As Range is declaring the variable envFrmwrkPath of type Range. This means that you can only set it to a range.

    This line: Set envFrmwrkPath = ActiveSheet.Range("D6").Value is attempting to set the Range type variable to a specific Value that is in cell D6. This could be a integer or a string for example (depends on what you have in that cell) but it's not a range.

    I'm assuming you want the value stored in a variable. Try something like this:

    Dim MyVariableName As Integer
    MyVariableName = ActiveSheet.Range("D6").Value
    

    This assumes you have a number (like 5) in cell D6. Now your variable will have the value.

    For simplicity sake of learning, you can remove or comment out the Option Explicit line and VBA will try to determine the type of variables at run time.


    Try this to get through this part of your code

    Dim envFrmwrkPath As String
    Dim ApplicationName As String
    Dim TestIterationName As String
    

    Abstract Class vs Interface in C++

    Pure Virtual Functions are mostly used to define:

    a) abstract classes

    These are base classes where you have to derive from them and then implement the pure virtual functions.

    b) interfaces

    These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.

    Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.

    capture div into image using html2canvas

    window.open didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target.

    _x000D_
    _x000D_
    $("#btn_screenshot").click(function(){_x000D_
         element_to_png("container", "testhtmltocanvasimg");_x000D_
    });_x000D_
    _x000D_
    _x000D_
    function element_to_png(srcElementID, targetIMGid){_x000D_
        console.log("element_to_png called for element id " + srcElementID);_x000D_
        html2canvas($("#"+srcElementID)[0]).then( function (canvas) {_x000D_
            var myImage = canvas.toDataURL("image/png");_x000D_
            $("#"+targetIMGid).attr("src", myImage);_x000D_
      console.log("html2canvas completed.  png rendered to " + targetIMGid);_x000D_
        });_x000D_
    }
    _x000D_
    <div id="testhtmltocanvasdiv" class="mt-3">_x000D_
       <img src="" id="testhtmltocanvasimg">_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    I can then right-click on the rendered png and "save as". May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!

    Sum values from an array of key-value pairs in JavaScript

    I think the simplest way might be:

    values.reduce(function(a, b){return a+b;})
    

    PHP: How to get current time in hour:minute:second?

    You can combine both in the same date function call

    date("d-m-Y H:i:s");  
    

    java Arrays.sort 2d array

    Welcome Java 8:

    Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0]));
    

    Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

    Difference is first one returns an MvcHtmlString but second (Render..) outputs straight to the response.

    How do I encrypt and decrypt a string in python?

    You can do this easily by using the library cryptocode. Here is how you install:

    pip install cryptocode
    

    Encrypting a message (example code):

    import cryptocode
    
    encoded = cryptocode.encrypt("mystring","mypassword")
    ## And then to decode it:
    decoded = cryptocode.decrypt(encoded, "mypassword")
    

    Documentation can be found here

    Pass command parameter to method in ViewModel in WPF?

    If you are that particular to pass elements to viewmodel You can use

     CommandParameter="{Binding ElementName=ManualParcelScanScreen}"
    

    Creating Dynamic button with click event in JavaScript

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>Click the button to make a BUTTON element with text.</p>
    
    <button onclick="myFunction()">Try it</button>
    
    <script>
    function myFunction() {
        var btn = document.createElement("BUTTON");
        var t = document.createTextNode("CLICK ME");
    
        btn.setAttribute("style","color:red;font-size:23px");
    
        btn.appendChild(t);
        document.body.appendChild(btn);
    
        btn.setAttribute("onclick", alert("clicked"));
    
    }
    </script>
    
    </body>
    </html>
    

    Arduino Tools > Serial Port greyed out

    The following steps install the IDE and remove the error java.lang.NullPointerException thrown while loading gnu.io.RXTXCommDriver which usually comes with arduino installed with apt-get command in Ubuntu.

    Install the IDE

    sudo apt-get install arduino
    

    for removing java error in IDE

    sudo add-apt-repository ppa:webupd8team/java
    sudo apt update
    sudo apt install oracle-java8-set-default
    

    This also shows the Serial Port which was grayed out due to the error.

    rbenv not changing ruby version

    When I had these symptoms, the problem turned out to be that install had failed halfway through for the new Ruby version I was trying to switch to, without me noticing. The fix was to delete & reinstall it.

    (This meant that even though ruby 1.9.3 showed up in the rbenv list of available versions, it didn't have an executable on the path where rbenv assumed it would. Since rbenv tries to change your ruby version just by prepending a location to your path, if there's nothing actually in the location it prepends, your OS will happily continue searching your default path and find your system version, in my case like the question's 1.8.7.)

    How to create a collapsing tree table in html/css/js?

    I'll throw jsTree into the ring, too. I've found it fairly adaptable to your particular situation. It's packed as a jQuery plugin.

    It can run from a variety of data sources, but my favorite is a simple nested list, as described by @joe_coolish or here:

    <ul>
      <li>
        Item 1
        <ul>
          <li>Item 1.1</li>
          ...
        </ul>
      </li>
      ...
    </ul>
    

    This structure fails gracefully into a static tree when JS is not available in the client, and is easy enough to read and understand from a coding perspective.

    If else on WHERE clause

    Here is a sample query for a table having a foreign key relationship to the same table with a query parameter.

    enter image description here

    SET @x = -1;
    SELECT id, categoryName 
    FROM Catergory WHERE IF(@x > 0,category_ParentId = @x,category_ParentId IS NOT NULL);
    

    @x can be changed.

    Convert the first element of an array to a string in PHP

    For completeness and simplicity sake, the following should be fine:

    $str = var_export($array, true);
    

    It does the job quite well in my case, but others seem to have issues with whitespace. In that case, the answer from ucefkh provides a workaround from a comment in the PHP manual.

    How to create helper file full of functions in react native?

    Quick note: You are importing a class, you can't call properties on a class unless they are static properties. Read more about classes here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

    There's an easy way to do this, though. If you are making helper functions, you should instead make a file that exports functions like this:

    export function HelloChandu() {
    
    }
    
    export function HelloTester() {
    
    }
    

    Then import them like so:

    import { HelloChandu } from './helpers'

    or...

    import functions from './helpers' then functions.HelloChandu

    Solving sslv3 alert handshake failure when trying to use a client certificate

    Not a definite answer but too much to fit in comments:

    I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl and openssl client paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.

    Do openssl x509 <clientcert.pem -noout -subject -issuer and the same on the cert from the test P12 that works. Do openssl s_client (or check the one you did) and look under Acceptable client certificate CA names; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.

    If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.

    If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.

    How does numpy.histogram() work?

    Another useful thing to do with numpy.histogram is to plot the output as the x and y coordinates on a linegraph. For example:

    arr = np.random.randint(1, 51, 500)
    y, x = np.histogram(arr, bins=np.arange(51))
    fig, ax = plt.subplots()
    ax.plot(x[:-1], y)
    fig.show()
    

    enter image description here

    This can be a useful way to visualize histograms where you would like a higher level of granularity without bars everywhere. Very useful in image histograms for identifying extreme pixel values.

    Using curl to upload POST data with files

    The issue that lead me here turned out to be a basic user error - I wasn't including the @ sign in the path of the file and so curl was posting the path/name of the file rather than the contents. The Content-Length value was therefore 8 rather than the 479 I expected to see given the legnth of my test file.

    The Content-Length header will be automatically calculated when curl reads and posts the file.

    curl -i -H "Content-Type: application/xml" --data "@test.xml" -v -X POST https://<url>/<uri/

    ... < Content-Length: 479 ...

    Posting this here to assist other newbies in future.

    Array and string offset access syntax with curly braces is deprecated

    It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

    Let's say you have something like this in your code:

    $str = "test";
    echo($str{0});
    

    since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

    $str = "test";
    echo($str[0]);
    

    Fixing the code in the question will look something like this:

    public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
    {
        $records = $this->listRecords($zoneID, $type, $name);
        if (isset($records->result[0]->id)) {
            return $records->result[0]->id;
        }
        return false;
    }
    

    Change Image of ImageView programmatically in Android

    If the above solutions are not working just delete this entire line from XML

    android:src="@drawable/image"
    

    & only try

    imageView.setBackgroundResource(R.drawable.image);
    

    Package structure for a Java project?

    There are a few existing resources you might check:

    1. Properly Package Your Java Classes
    2. Spring 2.5 Architecture
    3. Java Tutorial - Naming a Package
    4. SUN Naming Conventions

    For what it's worth, my own personal guidelines that I tend to use are as follows:

    1. Start with reverse domain, e.g. "com.mycompany".
    2. Use product name, e.g. "myproduct". In some cases I tend to have common packages that do not belong to a particular product. These would end up categorized according to the functionality of these common classes, e.g. "io", "util", "ui", etc.
    3. After this it becomes more free-form. Usually I group according to project, area of functionality, deployment, etc. For example I might have "project1", "project2", "ui", "client", etc.

    A couple of other points:

    1. It's quite common in projects I've worked on for package names to flow from the design documentation. Usually products are separated into areas of functionality or purpose already.
    2. Don't stress too much about pushing common functionality into higher packages right away. Wait for there to be a need across projects, products, etc., and then refactor.
    3. Watch inter-package dependencies. They're not all bad, but it can signify tight coupling between what might be separate units. There are tools that can help you keep track of this.

    Does it make sense to use Require.js with Angular.js?

    Yes it makes sense to use requireJS with Angular, I spent several days to test several technical solutions.

    I made an Angular Seed with RequireJS on Server Side. Very simple one. I use SHIM notation for no AMD module and not AMD because I think it's very difficult to deal with two different Dependency injection system.

    I use grunt and r.js to concatenate js files on server depends on the SHIM configuration (dependency) file. So I refer only one js file in my app.

    For more information go on my github Angular Seed : https://github.com/matohawk/angular-seed-requirejs

    Hidden Features of Xcode

    "Ctrl+Left/Right Arrow" to do intra-word text navigation. I use this feature to jump the cursor from the one "camel hump" in a variable to the next.

    Get the current URL with JavaScript?

    Try

    location+''
    

    _x000D_
    _x000D_
    let url = location+'';_x000D_
    _x000D_
    console.log(url);
    _x000D_
    _x000D_
    _x000D_

    error: member access into incomplete type : forward declaration of

    You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

    Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

    class B;
    
    class A
    {
        B* b;
    
        void doSomething();
    };
    
    class B
    {
        A* a;
    
        void add() {}
    };
    
    void A::doSomething()
    {
        b->add();
    }
    

    What is a method group in C#?

    Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup).

    So, for example, I have:

    private string DoSomethingToMyString(string input)
    {
        // blah
    }
    

    Instead of explicitly stating the variable to be used like this:

    public List<string> GetStringStuff()
    {
        return something.getStringsFromSomewhere.Select(str => DoSomethingToMyString(str));
    }
    

    I can just omit the name of the var:

    public List<string> GetStringStuff()
    {
        return something.getStringsFromSomewhere.Select(DoSomethingToMyString);
    }
    

    How to assign pointer address manually in C programming language?

    let's say you want a pointer to point at the address 0x28ff4402, the usual way is

    uint32_t *ptr;
    ptr = (uint32_t*) 0x28ff4402 //type-casting the address value to uint32_t pointer
    *ptr |= (1<<13) | (1<<10); //access the address how ever you want
    

    So the short way is to use a MACRO,

    #define ptr *(uint32_t *) (0x28ff4402)
    

    Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

    Changed all dependencies to compile rather than implementation, then I rebuild the project without errors. Then I switched back to implementation rather than leaving it as compile.

    How do I turn off Unicode in a VC++ project?

    use #undef UNICODE at the top of your main file.

    How to check empty DataTable

    As from MSDN for GetChanges

    A filtered copy of the DataTable that can have actions performed on it, and later be merged back in the DataTable using Merge. If no rows of the desired DataRowState are found, the method returns Nothing (null).

    dataTable1 is null so just check before you iterate over it.

    alter the size of column in table containing data

    Case 1 : Yes, this works fine.

    Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

    Share and enjoy.

    Submit form using a button outside the <form> tag

    Update: In modern browsers you can use the form attribute to do this.


    As far as I know, you cannot do this without javascript.

    Here's what the spec says

    The elements used to create controls generally appear inside a FORM element, but may also appear outside of a FORM element declaration when they are used to build user interfaces. This is discussed in the section on intrinsic events. Note that controls outside a form cannot be successful controls.

    That's my bold

    A submit button is considered a control.

    http://www.w3.org/TR/html4/interact/forms.html#h-17.2.1

    From the comments

    I have a multi tabbed settings area with a button to update all, due to the design of it the button would be outside of the form.

    Why not place the input inside the form, but use CSS to position it elsewhere on the page?

    Export MySQL database using PHP only

    Best way to export database using php script.

    Or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables

    <?php 
        //ENTER THE RELEVANT INFO BELOW
        $mysqlUserName      = "Your Username";
        $mysqlPassword      = "Your Password";
        $mysqlHostName      = "Your Host";
        $DbName             = "Your Database Name here";
        $backup_name        = "mybackup.sql";
        $tables             = "Your tables";
    
       //or add 5th parameter(array) of specific tables:    array("mytable1","mytable2","mytable3") for multiple tables
    
        Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName,  $tables=false, $backup_name=false );
    
        function Export_Database($host,$user,$pass,$name,  $tables=false, $backup_name=false )
        {
            $mysqli = new mysqli($host,$user,$pass,$name); 
            $mysqli->select_db($name); 
            $mysqli->query("SET NAMES 'utf8'");
    
            $queryTables    = $mysqli->query('SHOW TABLES'); 
            while($row = $queryTables->fetch_row()) 
            { 
                $target_tables[] = $row[0]; 
            }   
            if($tables !== false) 
            { 
                $target_tables = array_intersect( $target_tables, $tables); 
            }
            foreach($target_tables as $table)
            {
                $result         =   $mysqli->query('SELECT * FROM '.$table);  
                $fields_amount  =   $result->field_count;  
                $rows_num=$mysqli->affected_rows;     
                $res            =   $mysqli->query('SHOW CREATE TABLE '.$table); 
                $TableMLine     =   $res->fetch_row();
                $content        = (!isset($content) ?  '' : $content) . "\n\n".$TableMLine[1].";\n\n";
    
                for ($i = 0, $st_counter = 0; $i < $fields_amount;   $i++, $st_counter=0) 
                {
                    while($row = $result->fetch_row())  
                    { //when started (and every after 100 command cycle):
                        if ($st_counter%100 == 0 || $st_counter == 0 )  
                        {
                                $content .= "\nINSERT INTO ".$table." VALUES";
                        }
                        $content .= "\n(";
                        for($j=0; $j<$fields_amount; $j++)  
                        { 
                            $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); 
                            if (isset($row[$j]))
                            {
                                $content .= '"'.$row[$j].'"' ; 
                            }
                            else 
                            {   
                                $content .= '""';
                            }     
                            if ($j<($fields_amount-1))
                            {
                                    $content.= ',';
                            }      
                        }
                        $content .=")";
                        //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                        if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) 
                        {   
                            $content .= ";";
                        } 
                        else 
                        {
                            $content .= ",";
                        } 
                        $st_counter=$st_counter+1;
                    }
                } $content .="\n\n\n";
            }
            //$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
            $backup_name = $backup_name ? $backup_name : $name.".sql";
            header('Content-Type: application/octet-stream');   
            header("Content-Transfer-Encoding: Binary"); 
            header("Content-disposition: attachment; filename=\"".$backup_name."\"");  
            echo $content; exit;
        }
    ?>
    

    Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

    Please note that adding the get_author function would slow the list_display in the admin, because showing each person would make a SQL query.

    To avoid this, you need to modify get_queryset method in PersonAdmin, for example:

    def get_queryset(self, request):
        return super(PersonAdmin,self).get_queryset(request).select_related('book')
    

    Before: 73 queries in 36.02ms (67 duplicated queries in admin)

    After: 6 queries in 10.81ms

    Missing MVC template in Visual Studio 2015

    Visual Studio 2015 (Community update 3, in my scenario) uses a default template for the MVC project. You don't have to select it.

    I found this tutorial and I think it answers the question: https://docs.asp.net/en/latest/tutorials/first-mvc-app/start-mvc.html

    check out the old versions of this: http://www.asp.net/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part1

    http://www.asp.net/mvc/overview/getting-started/introduction/getting-started

    Times have changed. Including .NET

    Bootstrap col-md-offset-* not working

    In bootstrap 3 the format is

    col-md-6 col-md-offset-3
    

    For the same grid in Bootstrap 4 the format is

    col-md-6 offset-md-3
    

    How to drop a table if it exists?

    Is it correct to do the following?

    IF EXISTS(SELECT *
              FROM   dbo.Scores)
      DROP TABLE dbo.Scores
    

    No. That will drop the table only if it contains any rows (and will raise an error if the table does not exist).

    Instead, for a permanent table you can use

    IF OBJECT_ID('dbo.Scores', 'U') IS NOT NULL 
      DROP TABLE dbo.Scores; 
    

    Or, for a temporary table you can use

    IF OBJECT_ID('tempdb.dbo.#TempTableName', 'U') IS NOT NULL
      DROP TABLE #TempTableName; 
    

    SQL Server 2016+ has a better way, using DROP TABLE IF EXISTS …. See the answer by @Jovan.

    NSAttributedString add text alignment

    Swift 4.0+

    let titleParagraphStyle = NSMutableParagraphStyle()
    titleParagraphStyle.alignment = .center
    
    let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
    let title = NSMutableAttributedString(string: "You Are Registered", 
        attributes: [.font: titleFont,    
        .foregroundColor: UIColor.red, 
        .paragraphStyle: titleParagraphStyle])
    

    Swift 3.0+

    let titleParagraphStyle = NSMutableParagraphStyle()
    titleParagraphStyle.alignment = .center
    
    let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
    let title = NSMutableAttributedString(string: "You Are Registered", 
        attributes: [NSFontAttributeName:titleFont,    
        NSForegroundColorAttributeName:UIColor.red, 
        NSParagraphStyleAttributeName: titleParagraphStyle])
    

    (original answer below)

    Swift 2.0+

    let titleParagraphStyle = NSMutableParagraphStyle()
    titleParagraphStyle.alignment = .Center
    
    let titleFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
    let title = NSMutableAttributedString(string: "You Are Registered",
        attributes:[NSFontAttributeName:titleFont,   
        NSForegroundColorAttributeName:UIColor.redColor(), 
        NSParagraphStyleAttributeName: titleParagraphStyle])
    

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

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

    UPDATE table SET columnB = columnA;

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

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

    How to base64 encode image in linux bash / shell

    Single line result:

    base64 -w 0 DSC_0251.JPG
    

    For HTML:

    echo "data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"
    

    As file:

    base64 -w 0 DSC_0251.JPG > DSC_0251.JPG.base64
    

    In variable:

    IMAGE_BASE64="$(base64 -w 0 DSC_0251.JPG)"
    

    In variable for HTML:

    IMAGE_BASE64="data:image/jpeg;base64,$(base64 -w 0 DSC_0251.JPG)"
    

    Get you readable data back:

    base64 -d DSC_0251.base64 > DSC_0251.JPG 
    

    See: http://www.greywyvern.com/code/php/binary2base64

    Deploying Java webapp to Tomcat 8 running in Docker container

    Tomcat will only extract the war which is copied to webapps directory. Change Dockerfile as below:

    FROM tomcat:8.0.20-jre8
    COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war
    

    You might need to access the url as below unless you have specified the webroot

    http://192.168.59.103:8888/myapp/getData

    android - how to convert int to string and place it in a EditText?

    Try using String.format() :

    ed = (EditText) findViewById (R.id.box); 
    int x = 10; 
    ed.setText(String.format("%s",x)); 
    

    Can't ping a local VM from the host

    I had a similar issue. You won't be able to ping the VM's from external devices if using NAT setting from within VMware's networking options. I switched to bridged connection so that the guest virtual machine will get it's own IP address and and then I added a second adapter set to NAT for the guest to get to the Internet.

    Oracle date "Between" Query

    Following query also can be used:

    select * 
      from t23
     where trunc(start_date) between trunc(to_date('01/15/2010','mm/dd/yyyy')) and trunc(to_date('01/17/2010','mm/dd/yyyy'))
    

    Serialize object to query string in JavaScript/jQuery

    Alternatively YUI has http://yuilibrary.com/yui/docs/api/classes/QueryString.html#method_stringify.

    For example:

    var data = { one: 'first', two: 'second' };
    var result = Y.QueryString.stringify(data);
    

    Select method in List<t> Collection

    I have used a script but to make a join, maybe I can help you

    string Email = String.Join(", ", Emails.Where(i => i.Email != "").Select(i => i.Email).Distinct());
    

    gulp command not found - error after installing gulp

    Add this path in your Environment Variables PATH C:\Users\USERNAME\AppData\Roaming\npm\

    Float a DIV on top of another DIV

    Use this css

    .close-image {
        cursor: pointer;
        z-index: 3;
        right: 5px;
        top: 5px;
        position: absolute;
    }
    

    DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

    That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

    DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
    

    Double check your table definition. Maybe you just missed adding something.

    I also tried google-ing this problem and saw this:

    http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

    Why use String.Format?

    Several reasons:

    1. String.Format() is very powerful. You can use simple format indicators (like fixed width, currency, character lengths, etc) right in the format string. You can even create your own format providers for things like expanding enums, mapping specific inputs to much more complicated outputs, or localization.
    2. You can do some powerful things by putting format strings in configuration files.
    3. String.Format() is often faster, as it uses a StringBuilder and an efficient state machine behind the scenes, whereas string concatenation in .Net is relatively slow. For small strings the difference is negligible, but it can be noticable as the size of the string and number of substituted values increases.
    4. String.Format() is actually more familiar to many programmers, especially those coming from backgrounds that use variants of the old C printf() function.

    Finally, don't forget StringBuilder.AppendFormat(). String.Format() actually uses this method behind the scenes*, and going to the StringBuilder directly can give you a kind of hybrid approach: explicitly use .Append() (analogous to concatenation) for some parts of a large string, and use .AppendFormat() in others.


    * [edit] Original answer is now 8 years old, and I've since seen an indication this may have changed when string interpolation was added to .Net. However, I haven't gone back to the reference source to verify the change yet.

    How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

    Codeigniter generates an "IS NULL" query by just leaving the call with no parameters:

    $this->db->where('column');
    

    The generated query is:

    WHERE `column` IS NULL
    

    MVC 4 Data Annotations "Display" Attribute

    In addition to the other answers, there is a big benefit to using the DisplayAttribute when you want to localize the fields. You can lookup the name in a localization database using the DisplayAttribute and it will use whatever translation you wish.

    Also, you can let MVC generate the templates for you by using Html.EditorForModel() and it will generate the correct label for you.

    Ultimately, it's up to you. But the MVC is very "Model-centric", which is why data attributes are applied to models, so that metadata exists in a single place. It's not like it's a huge amount of extra typing you have to do.

    Reset IntelliJ UI to Default

    Recent Versions

    Window -> Restore Default Layout

    (Thanks to Seven4X's answer)

    Older Versions

    You can simply delete the whole configuration folder ${user.home}/.IntelliJIdea60/config while IntelliJ IDEA is not running. Next time it restarts, everything is restored from the default settings.

    It depends on the OS:

    https://intellij-support.jetbrains.com/entries/23358108

    How to check if array element exists or not in javascript?

    (typeof files[1] === undefined)?
                this.props.upload({file: files}):
                this.props.postMultipleUpload({file: files widgetIndex: 0, id})
    

    Check if the second item in the array is undefined using the typeof and checking for undefined

    How to to send mail using gmail in Laravel?

    Note: Laravel 7 replaced MAIL_DRIVER by MAIL_MAILER

    MAIL_MAILER=smtp    
    MAIL_HOST=smtp.gmail.com   
    MAIL_PORT=587      
    MAIL_USERNAME=yourgmailaddress
    MAIL_PASSWORD=yourgmailpassword
    MAIL_ENCRYPTION=tls
    

    Allow less secure apps from "Google Account" - https://myaccount.google.com/ - Settings - Less secure app access (Turn On)

    Flush cache config:

    php artisan config:cache
    

    For Apache:

    sudo service apache2 restart
    

    Creating a UICollectionView programmatically

    For Swift 2.0

    Instead of implementing the methods that are required to draw the CollectionViewCells:

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
        {
            return CGSizeMake(50, 50);
        }
    
        func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets
        {
            return UIEdgeInsetsMake(5, 5, 5, 5); //top,left,bottom,right
        }
    

    Use UICollectionViewFlowLayout

    func createCollectionView() {
        let flowLayout = UICollectionViewFlowLayout()
    
        // Now setup the flowLayout required for drawing the cells
        let space = 5.0 as CGFloat
    
        // Set view cell size
        flowLayout.itemSize = CGSizeMake(50, 50)
    
        // Set left and right margins
        flowLayout.minimumInteritemSpacing = space
    
        // Set top and bottom margins
        flowLayout.minimumLineSpacing = space
    
        // Finally create the CollectionView
        let collectionView = UICollectionView(frame: CGRectMake(10, 10, 300, 400), collectionViewLayout: flowLayout)
    
        // Then setup delegates, background color etc.
        collectionView?.dataSource = self
        collectionView?.delegate = self
        collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID")
        collectionView?.backgroundColor = UIColor.whiteColor()
        self.view.addSubview(collectionView!)
    }
    

    Then implement the UICollectionViewDataSource methods as required:

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 20;
        }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        var cell:UICollectionViewCell=collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as UICollectionViewCell;
        cell.backgroundColor = UIColor.greenColor();
        return cell;
    }
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    

    What is the proper way to format a multi-line dict in Python?

    First of all, like Steven Rumbalski said, "PEP8 doesn't address this question", so it is a matter of personal preference.

    I would use a similar but not identical format as your format 3. Here is mine, and why.

    my_dictionary = { # Don't think dict(...) notation has more readability
        "key1": 1, # Indent by one press of TAB (i.e. 4 spaces)
        "key2": 2, # Same indentation scale as above
        "key3": 3, # Keep this final comma, so that future addition won't show up as 2-lines change in code diff
        } # My favorite: SAME indentation AS ABOVE, to emphasize this bracket is still part of the above code block!
    the_next_line_of_code() # Otherwise the previous line would look like the begin of this part of code
    
    bad_example = {
                   "foo": "bar", # Don't do this. Unnecessary indentation wastes screen space
                   "hello": "world" # Don't do this. Omitting the comma is not good.
    } # You see? This line visually "joins" the next line when in a glance
    the_next_line_of_code()
    
    btw_this_is_a_function_with_long_name_or_with_lots_of_parameters(
        foo='hello world',  # So I put one parameter per line
        bar=123,  # And yeah, this extra comma here is harmless too;
                  # I bet not many people knew/tried this.
                  # Oh did I just show you how to write
                  # multiple-line inline comment here?
                  # Basically, same indentation forms a natural paragraph.
        ) # Indentation here. Same idea as the long dict case.
    the_next_line_of_code()
    
    # By the way, now you see how I prefer inline comment to document the very line.
    # I think this inline style is more compact.
    # Otherwise you will need extra blank line to split the comment and its code from others.
    
    some_normal_code()
    
    # hi this function is blah blah
    some_code_need_extra_explanation()
    
    some_normal_code()
    

    How to find which version of Oracle is installed on a Linux server (In terminal)

    As the user running the Oracle Database one can also try $ORACLE_HOME/OPatch/opatch lsinventory which shows the exact version and patches installed.

    For example this is a quick oneliner which should only return the version number:

    $ORACLE_HOME/OPatch/opatch lsinventory | awk '/^Oracle Database/ {print $NF}'
    

    java.lang.OutOfMemoryError: GC overhead limit exceeded

    Don't store the whole structure in memory while waiting to get to the end.

    Write intermediate results to a temporary table in the database instead of hashmaps - functionally, a database table is the equivalent of a hashmap, i.e. both support keyed access to data, but the table is not memory bound, so use an indexed table here rather than the hashmaps.

    If done correctly, your algorithm should not even notice the change - correctly here means to use a class to represent the table, even giving it a put(key, value) and a get(key) method just like a hashmap.

    When the intermediate table is complete, generate the required sql statement(s) from it instead of from memory.

    Authorize attribute in ASP.NET MVC

    Using Authorize attribute seems more convenient and feels more 'MVC way'. As for technical advantages there are some.

    One scenario that comes to my mind is when you're using output caching in your app. Authorize attribute handles that well.

    Another would be extensibility. The Authorize attribute is just basic out of the box filter, but you can override its methods and do some pre-authorize actions like logging etc. I'm not sure how you would do that through configuration.

    When are static variables initialized?

    From See Java Static Variable Methods:

    • It is a variable which belongs to the class and not to object(instance)
    • Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables
    • A single copy to be shared by all instances of the class
    • A static variable can be accessed directly by the class name and doesn’t need any object.

    Instance and class (static) variables are automatically initialized to standard default values if you fail to purposely initialize them. Although local variables are not automatically initialized, you cannot compile a program that fails to either initialize a local variable or assign a value to that local variable before it is used.

    What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded.

    In case of inner classes, they can not have static fields

    An inner class is a nested class that is not explicitly or implicitly declared static.

    ...

    Inner classes may not declare static initializers (§8.7) or member interfaces...

    Inner classes may not declare static members, unless they are constant variables...

    See JLS 8.1.3 Inner Classes and Enclosing Instances

    final fields in Java can be initialized separately from their declaration place this is however can not be applicable to static final fields. See the example below.

    final class Demo
    {
        private final int x;
        private static final int z;  //must be initialized here.
    
        static 
        {
            z = 10;  //It can be initialized here.
        }
    
        public Demo(int x)
        {
            this.x=x;  //This is possible.
            //z=15; compiler-error - can not assign a value to a final variable z
        }
    }
    

    This is because there is just one copy of the static variables associated with the type, rather than one associated with each instance of the type as with instance variables and if we try to initialize z of type static final within the constructor, it will attempt to reinitialize the static final type field z because the constructor is run on each instantiation of the class that must not occur to static final fields.

    SQL Server stored procedure parameters

    You are parsing wrong parameter combination.here you passing @TaskName = and @ID instead of @TaskName = .SP need only one parameter.

    Force IE10 to run in IE10 Compatibility View?

    You can try :

    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" >
    

    Just like you tried before, but caution:

    It seems like the X-UA-Compatible tag has to be the first tag in the < head > section

    If this conclusion is correct, then I believe it is undocumented in Microsoft’s blogs/msdn (and if it is documented, then it isn’t sticking out well enough from the docs). Ensuring that this was the first meta tag in the forced IE9 to switch to IE8 mode successfully

    Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

    I found a need for this while programming an iOS-Phone monotouch app controller in a visual studio winforms prototype project outside of xamarin stuidio. Preferring to program in VS over xamarin studio as much as possible, I wanted the controller to be completely decoupled from the phone framework. This way implementing this for other frameworks like Android and Windows Phone would be much easier for future uses.

    I wanted a solution where the GUI could respond to events without the burden of dealing with the cross threading switching code behind every button click. Basically let the class controller handle that to keep the client code simple. You could possibly have many events on the GUI where as if you could handle it in one place in the class would be cleaner. I am not a multi theading expert, let me know if this is flawed.

    public partial class Form1 : Form
    {
        private ExampleController.MyController controller;
    
        public Form1()
        {          
            InitializeComponent();
            controller = new ExampleController.MyController((ISynchronizeInvoke) this);
            controller.Finished += controller_Finished;
        }
    
        void controller_Finished(string returnValue)
        {
            label1.Text = returnValue; 
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            controller.SubmitTask("Do It");
        }
    }
    

    The GUI form is unaware the controller is running asynchronous tasks.

    public delegate void FinishedTasksHandler(string returnValue);
    
    public class MyController
    {
        private ISynchronizeInvoke _syn; 
        public MyController(ISynchronizeInvoke syn) {  _syn = syn; } 
        public event FinishedTasksHandler Finished; 
    
        public void SubmitTask(string someValue)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(state => submitTask(someValue));
        }
    
        private void submitTask(string someValue)
        {
            someValue = someValue + " " + DateTime.Now.ToString();
            System.Threading.Thread.Sleep(5000);
    //Finished(someValue); This causes cross threading error if called like this.
    
            if (Finished != null)
            {
                if (_syn.InvokeRequired)
                {
                    _syn.Invoke(Finished, new object[] { someValue });
                }
                else
                {
                    Finished(someValue);
                }
            }
        }
    }
    

    Why is it bad style to `rescue Exception => e` in Ruby?

    Because this captures all exceptions. It's unlikely that your program can recover from any of them.

    You should handle only exceptions that you know how to recover from. If you don't anticipate a certain kind of exception, don't handle it, crash loudly (write details to the log), then diagnose logs and fix code.

    Swallowing exceptions is bad, don't do this.

    Regular expression field validation in jQuery

    I believe this does it:

    http://bassistance.de/jquery-plugins/jquery-plugin-validation/

    It's got built-in patterns for stuff like URLs and e-mail addresses, and I think you can have it use your own as well.

    How to check if a string contains an element from a list in Python

    Check if it matches this regex:

    '(\.pdf$|\.doc$|\.xls$)'
    

    Note: if you extensions are not at the end of the url, remove the $ characters, but it does weaken it slightly

    build-impl.xml:1031: The module has not been deployed

    • Close Netbeans.
    • Delete all libraries in the folder "yourprojectfolder"\build\web\WEB-INF\lib
    • Open Netbeans.
    • Clean and Build project.
    • Deploy project.

    Redirect to external URL with return in laravel

    Also, adding class

          use Illuminate\Http\RedirectResponse;
    

    and after, like this:

     public function show($id){
    
        $link = Link::findOrFail($id);  // get data from db table Links
    
        return new RedirectResponse($link->url);  // and this my external link, 
     }
    

    or -

     return  new RedirectResponse("http://www.google.com?andParams=yourParams"); 
    

    For external links have to be used full URL string with 'http' in begin.

    How could others, on a local network, access my NodeJS app while it's running on my machine?

    I had the same question and solved the problem. In my case, the Windows Firewall (not the router) was blocking the V8 machine I/O on the hosting machine.

    1. Go to windows button
    2. Search "Firewall"
    3. Choose "Allow programs to communicate through Firewall"
    4. Click Change Setup
    5. Tick all of "Evented I/O for V8 Javascript" OR "Node.js: Server-side Javascript"

    My guess is that "Evented I/O for V8 Javascript" is the I/O process that node.js communicates to outside world and we need to free it before it can send packets outside of the local computer. After enabling this program to communicate over Windows firewall, I could use any port numbers to listen.

    WPF Data Binding and Validation Rules Best Practices

    If your business class is directly used by your UI is preferrable to use IDataErrorInfo because it put logic closer to their owner.

    If your business class is a stub class created by a reference to an WCF/XmlWeb service then you can not/must not use IDataErrorInfo nor throw Exception for use with ExceptionValidationRule. Instead you can:

    • Use custom ValidationRule.
    • Define a partial class in your WPF UI project and implements IDataErrorInfo.

    JavaScript Chart.js - Custom data formatting to display on tooltip

    For chart.js 2.0+, this has changed (no more tooltipTemplate/multiTooltipTemplate). For those that just want to access the current, unformatted value and start tweaking it, the default tooltip is the same as:

    options: {
        tooltips: {
            callbacks: {
                label: function(tooltipItem, data) {
                    return tooltipItem.yLabel;
                }
            }
        }
    }
    

    I.e., you can return modifications to tooltipItem.yLabel, which holds the y-axis value. In my case, I wanted to add a dollar sign, rounding, and thousands commas for a financial chart, so I used:

    options: {
        tooltips: {
            callbacks: {
                label: function(tooltipItem, data) {
                    return "$" + Number(tooltipItem.yLabel).toFixed(0).replace(/./g, function(c, i, a) {
                        return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
                    });
                }
            }
        }
    }
    

    Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

    #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    u = u'moçambique'
    print u.encode("utf-8")
    print u
    
    chmod +x test.py
    ./test.py
    moçambique
    moçambique
    
    ./test.py > output.txt
    Traceback (most recent call last):
      File "./test.py", line 5, in <module>
        print u
    UnicodeEncodeError: 'ascii' codec can't encode character 
    u'\xe7' in position 2: ordinal not in range(128)
    

    on shell works , sending to sdtout not , so that is one workaround, to write to stdout .

    I made other approach, which is not run if sys.stdout.encoding is not define, or in others words , need export PYTHONIOENCODING=UTF-8 first to write to stdout.

    import sys
    if (sys.stdout.encoding is None):            
        print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout." 
        exit(1)
    


    so, using same example:

    export PYTHONIOENCODING=UTF-8
    ./test.py > output.txt
    

    will work

    The AWS Access Key Id does not exist in our records

    Adding one more answer since all the above cases didn't work for me.

    In AWS console, check your credentials(My Security Credentials) and see if you have entered the right credentials.

    Thanks to this discussion: https://forums.aws.amazon.com/message.jspa?messageID=771815