Programs & Examples On #Oledragdrop

Accessing the index in 'for' loops?

In your question, you write "how do I access the loop index, from 1 to 5 in this case?"

However, the index for a list runs from zero. So, then we need to know if what you actually want is the index and item for each item in a list, or whether you really want numbers starting from 1. Fortunately, in Python, it is easy to do either or both.

First, to clarify, the enumerate function iteratively returns the index and corresponding item for each item in a list.

alist = [1, 2, 3, 4, 5]

for n, a in enumerate(alist):
    print("%d %d" % (n, a))

The output for the above is then,

0 1
1 2
2 3
3 4
4 5

Notice that the index runs from 0. This kind of indexing is common among modern programming languages including Python and C.

If you want your loop to span a part of the list, you can use the standard Python syntax for a part of the list. For example, to loop from the second item in a list up to but not including the last item, you could use

for n, a in enumerate(alist[1:-1]):
    print("%d %d" % (n, a))

Note that once again, the output index runs from 0,

0 2
1 3
2 4

That brings us to the start=n switch for enumerate(). This simply offsets the index, you can equivalently simply add a number to the index inside the loop.

for n, a in enumerate(alist, start=1):
    print("%d %d" % (n, a))

for which the output is

1 1
2 2
3 3
4 4
5 5

How to use requirements.txt to install all dependencies in a python project

pip install -r requirements.txt for python 2.x

pip3 install -r requirements.txt for python 3.x (in case multiple versions are installed)

Is there any difference between DECIMAL and NUMERIC in SQL Server?

This is what then SQL2003 standard (ยง6.1 Data Types) says about the two:

 <exact numeric type> ::=
    NUMERIC [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | DECIMAL [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | DEC [ <left paren> <precision> [ <comma> <scale> ] <right paren> ]
  | SMALLINT
  | INTEGER
  | INT
  | BIGINT

 ...

21) NUMERIC specifies the data type
    exact numeric, with the decimal
    precision and scale specified by the
    <precision> and <scale>.

22) DECIMAL specifies the data type
    exact numeric, with the decimal scale
    specified by the <scale> and the
    implementation-defined decimal
    precision equal to or greater than the
    value of the specified <precision>.

Ruby on Rails form_for select field with class

You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select

Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.

= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}

What is pipe() function in Angular

Two very different types of Pipes Angular - Pipes and RxJS - Pipes

Angular-Pipe

A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.

import { Component } from '@angular/core';

@Component({
  selector: 'app-hero-birthday',
  template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
  birthday = new Date(1988, 3, 15); // April 15, 1988
}

RxJS - Pipe

Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.

import {Observable, range} from 'rxjs';
import {map, filter} from 'rxjs/operators';

const source$: Observable<number> = range(0, 10);

source$.pipe(
    map(x => x * 2),
    filter(x => x % 3 === 0)
).subscribe(x => console.log(x));

The output for this in the console would be the following:

0

6

12

18

For any variable holding an observable, we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.

So this example takes each number in the range of 0 to 10, and multiplies it by 2. Then, the filter function to filter the result down to only the odd numbers.

Placing/Overlapping(z-index) a view above another view in android

I use this, if you want only one view to be bring to front when needed:

containerView.bringChildToFront(topView);

containerView is container of views to be sorted, topView is view which i want to have as top most in container.

for multiple views to arrange is about to use setChildrenDrawingOrderEnabled(true) and overriding getChildDrawingOrder(int childCount, int i) as mentioned above.

Java swing application, close one window and open another when button is clicked

Use this.dispose for current window to close and next_window.setVisible(true) to show next window behind button property ActionPerformed , Example is shown below in pic for your help.

enter image description here

Error Code: 2013. Lost connection to MySQL server during query

Try please to uncheck limit rows in in Edit ? Preferences ?SQL Queries

because You should set the 'interactive_timeout' and 'wait_timeout' properties in the mysql config file to the values you need.

android.content.Context.getPackageName()' on a null object reference

  public MessageAdapter(Context context, List<Messages> mMessageList) {

    this.mContext = context;
    this.mMessageList = mMessageList;

  }

Node.js fs.readdir recursive directory search

Just in case anyone finds it useful, I also put together a synchronous version.

var walk = function(dir) {
    var results = [];
    var list = fs.readdirSync(dir);
    list.forEach(function(file) {
        file = dir + '/' + file;
        var stat = fs.statSync(file);
        if (stat && stat.isDirectory()) { 
            /* Recurse into a subdirectory */
            results = results.concat(walk(file));
        } else { 
            /* Is a file */
            results.push(file);
        }
    });
    return results;
}

Tip: To use less resources when filtering. Filter within this function itself. E.g. Replace results.push(file); with below code. Adjust as required:

    file_type = file.split(".").pop();
    file_name = file.split(/(\\|\/)/g).pop();
    if (file_type == "json") results.push(file);

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

Short answer: dispatchTouchEvent() will be called first of all.

Short advice: should not override dispatchTouchEvent() since it's hard to control, sometimes it can slow down your performance. IMHO, I suggest overriding onInterceptTouchEvent().


Because most answers mention pretty clearly about the flow touch event on activity/ view group/ view, I only add more detail about code on these methods in ViewGroup (ignoring dispatchTouchEvent()):

onInterceptTouchEvent() will be called first, ACTION event will be called respectively down -> move -> up. There are 2 cases:

  1. If you return false in 3 cases (ACTION_DOWN, ACTION_MOVE, ACTION_UP), it will consider as the parent won't need this touch event, so onTouch() of the parents never calls, but onTouch() of the children will call instead; however please notice:

    • The onInterceptTouchEvent() still continue to receive touch event, as long as its children don't call requestDisallowInterceptTouchEvent(true).
    • If there are no children receiving that event (it can happen in 2 cases: no children at the position the users touch, or there are children but it returns false at ACTION_DOWN), the parents will send that event back to onTouch() of the parents.
  2. Vice versa, if you return true, the parent will steal this touch event immediately, and onInterceptTouchEvent() will stop immediately, instead onTouch() of the parents will be called as well as all onTouch() of children will receive the last action event - ACTION_CANCEL (thus, it means the parents stole touch event, and children cannot handle it from then on). The flow of onInterceptTouchEvent() return false is normal, but there is a little confusion with return true case, so I list it here:

    • Return true at ACTION_DOWN, onTouch() of the parents will receive ACTION_DOWN again and following actions (ACTION_MOVE, ACTION_UP).
    • Return true at ACTION_MOVE, onTouch() of the parents will receive next ACTION_MOVE (not the same ACTION_MOVE in onInterceptTouchEvent()) and following actions (ACTION_MOVE, ACTION_UP).
    • Return true at ACTION_UP, onTouch() of the parents will NOT called at all since it's too late for the parents to steal touch event.

One more thing important is ACTION_DOWN of the event in onTouch() will determine if the view would like to receive more action from that event or not. If the view returns true at ACTION_DOWN in onTouch(), it means the view is willing to receive more action from that event. Otherwise, return false at ACTION_DOWN in onTouch() will imply that the view won't receive any more action from that event.

Read a XML (from a string) and get some fields - Problems reading XML

You should use LoadXml method, not Load:

xmlDoc.LoadXml(myXML); 

Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);

string xpath = "myDataz/listS/sog";
var nodes = xmlDoc.SelectNodes(xpath);

foreach (XmlNode childrenNode in nodes)
{
    HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//field1").Value);
} 

Node.js spawn child process and get terminal output live

Adding an answer related to child_process.exec as I too had needed live feedback and wasn't getting any until after the script finished. This also supplements my comment to the accepted answer, but as it's formatted it will a bit more understandable and easier to read.

Basically, I have a npm script that calls Gulp, invoking a task which subsequently uses child_process.exec to execute a bash or batch script depending on the OS. Either script runs a build process via Gulp and then makes some calls to some binaries that work with the Gulp output.

It's exactly like the others (spawn, etc.), but for the sake of completion, here's exactly how to do it:

// INCLUDES
import * as childProcess from 'child_process'; // ES6 Syntax


// GLOBALS
let exec = childProcess.exec; // Or use 'var' for more proper 
                              // semantics, though 'let' is 
                              // true-to-scope


// Assign exec to a variable, or chain stdout at the end of the call
// to exec - the choice, yours (i.e. exec( ... ).stdout.on( ... ); )
let childProcess = exec
(
    './binary command -- --argument argumentValue',
    ( error, stdout, stderr ) =>
    {
        if( error )
        {
            // This won't show up until the process completes:
            console.log( '[ERROR]: "' + error.name + '" - ' + error.message );
            console.log( '[STACK]: ' + error.stack );

            console.log( stdout );
            console.log( stderr );
            callback();            // Gulp stuff
            return;
        }

        // Neither will this:
        console.log( stdout );
        console.log( stderr );
        callback();                // Gulp stuff
    }
);

Now its as simple as adding an event listener. For stdout:

childProcess.stdout.on
(
    'data',
    ( data ) =>
    {
        // This will render 'live':
        console.log( '[STDOUT]: ' + data );
    }
);

And for stderr:

childProcess.stderr.on
(
    'data',
    ( data ) =>
    {
        // This will render 'live' too:
        console.log( '[STDERR]: ' + data );
    }
);

Not too bad at all - HTH

Intent from Fragment to Activity

Remove this

android:onClick="goToAttract"

Then

View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Button b = (Button)rootView.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
     public void onClick(View v)
     {
        Intent intent = new Intent(getActivity(), MainActivityList.class);
        startActivity(intent);

     } 

});
return rootView;

The error says you need to public void goToAttract(View v) in Activity class

Could not find method goToAttract(View) in the activity class

Reason pls check the answer by PareshMayani @

Android app crashing (fragment and xml onclick)

Edit:

Caused by: java.lang.OutOfMemoryError

I guess you have a image that is too big to fit in and it needs to be scaled down. Hence the OutOfMemoryError.

Create comma separated strings C#?

If you put all your values in an array, at least you can use string.Join.

string[] myValues = new string[] { ... };
string csvString = string.Join(",", myValues);

You can also use the overload of string.Join that takes params string as the second parameter like this:

string csvString = string.Join(",", value1, value2, value3, ...);

Updating a JSON object using Javascript

var i = jsonObj.length;
while ( i --> 0 ) {
    if ( jsonObj[i].Id === 3 ) {
        jsonObj[ i ].Username = 'Thomas';
        break;
    }
}

Or, if the array is always ordered by the IDs:

jsonObj[ 2 ].Username = 'Thomas';

How do I commit only some files?

This is a simple approach if you don't have much code changes:

1. git stash
2. git stash apply
3. remove the files/code you don't want to commit
4. commit the remaining files/code you do want

Then if you want the code you removed (bits you didn't commit) in a separate commit or another branch, then while still on this branch do:

5. git stash apply
6. git stash

With step 5 as you already applied the stash and committed the code you did want in step 4, the diff and untracked in the newly applied stash is just the code you removed in step 3 before you committed in step 4.

As such step 6 is a stash of the code you didn't [want to] commit, as you probably don't really want to lose those changes right? So the new stash from step 6 can now be committed to this or any other branch by doing git stash apply on the correct branch and committing.

Obviously this presumes you do the steps in one flow, if you stash at any other point in these steps you'll need to note the stash ref for each step above (rather than just basic stash and apply the most recent stash).

How to correctly assign a new string value?

The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array:

strcpy(p.name, "Jane");

Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure that the name will fit into 19 characters (not 20 because one character is always needed to store the terminating zero value).

Conversely, pointers are better if you don't know the possible maximum size of your string, and/or you want to optimize your memory usage, e.g. avoid reserving 512 characters for the name "John". However, with pointers you need to dynamically allocate the buffer they point to, and free it when not needed anymore, to avoid memory leaks.

Update: example of dynamically allocated buffers (using the struct definition in your 2nd example):

char* firstName = "Johnnie";
char* surname = "B. Goode";
person p;

p.name = malloc(strlen(firstName) + 1);
p.surname = malloc(strlen(surname) + 1);

p.age = 25;
strcpy(p.name, firstName);
strcpy(p.surname, surname);

printf("Name: %s; Age: %d\n",p.name,p.age);

free(p.surname);
free(p.name);

Create a data.frame with m columns and 2 rows

Does m really need to be a data.frame() or will a matrix() suffice?

m <- matrix(0, ncol = 30, nrow = 2)

You can wrap a data.frame() around that if you need to:

m <- data.frame(m)

or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))

Text File Parsing in Java

While calling/invoking your programme you can use this command : java [-options] className [args...]
in place of [-options] provide more memory e.g -Xmx1024m or more. but this is just a workaround, u have to change ur parsing mechanism.

Where do I find old versions of Android NDK?

Here are the links for Windows, Mac and Linux. Latest revision of 18.x, 17.x, 16.x, 15.x, 14.x, 13.x, 12.x, 11.x, 10.x, 9.x, 8.x and 7.x versions.

Update: Download Latest and Old NDK releases from Android official site.


Android NDK, Revision 18b (January 2019)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 17c (June 2018)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 16b (December 2017)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 15c (July 2017)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 14b (March 2017)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 13b (October 2016)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 12b (June 2016)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 11c (March 2016)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK, Revision 10e (May 2015)

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK r9d

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK r8e

Windows 32-bit | Windows 64-bit | Mac OS X 64-bit | Linux 64-bit

Android NDK r7c

Windows 32-bit | Mac OS X 64-bit | Linux 64-bit

Int to byte array

Update for 2020 - BinaryPrimitives should now be preferred over BitConverter. It provides endian-specific APIs, and is less allocatey.


byte[] bytes = BitConverter.GetBytes(i);

although note also that you might want to check BitConverter.IsLittleEndian to see which way around that is going to appear!

Note that if you are doing this repeatedly you might want to avoid all those short-lived array allocations by writing it yourself via either shift operations (>> / <<), or by using unsafe code. Shift operations also have the advantage that they aren't affected by your platform's endianness; you always get the bytes in the order you expect them.

Upgrade python without breaking yum

I recommend, instead, updating the path in the associated script(s) (such as /usr/bin/yum) to point at your previous Python as the interpreter.

Ideally, you want to upgrade yum and its associated scripts so that they are supported by the default Python installed.

If that is not possible, the above is entirely workable and tested.

Change:

#!/usr/bin/python

to whatever the path is of your old version until you can make the above yum improvement.

Cases where you couldn't do the above are if you have an isolated machine, don't have the time to upgrade rpm manually or can't connect temporarily or permanently to a standard yum repository.

css 'pointer-events' property alternative for IE

You can also just "not" add a url inside the <a> tag, i do this for menus that are <a> tag driven with drop downs as well. If there is not drop down then i add the url but if there are drop downs with a <ul> <li> list i just remove it.

Best way to parseDouble with comma as decimal separator?

As E-Riz points out, NumberFormat.parse(String) parse "1,23abc" as 1.23. To take the entire input we can use:

public double parseDecimal(String input) throws ParseException{
  NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault());
  ParsePosition parsePosition = new ParsePosition(0);
  Number number = numberFormat.parse(input, parsePosition);

  if(parsePosition.getIndex() != input.length()){
    throw new ParseException("Invalid input", parsePosition.getIndex());
  }

  return number.doubleValue();
}

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

TRY BELOW SOLUTIONS.

SOLUTION 1:

-> Run Android Studio as Administrator (this is only required for first run or when any issues arise due to automatic updates on any run in future).

Though it shows API 23 is or any other updates are not installed (and wouldn't show any 'Retry' button), BUT still the download and installation of rest of the updates would proceed (you can see the download progress incrementing even after seeing the above errors). So, DO NOT ABORT the operation.

-> At the end of installation (after rest of successful updates are installed) it would this time display the "Retry" button to retry installation for API 23 or any other versions which had failed earlier. Then click the "Retry" button, it would work this time.

This would resolve your issue with successful installation.

-> Next time onward no need to run Android studio as Administrator, unless it does any automatic updates and shows similar issues.

SOLUTION 2:

-> Alternative approach is to install any updates (which ever failed in earlier attempt) from Android SDK Manager first and then later launch Android Studio (which would not need any check for updates and any additional installations).

To install any features or updates, run Android SDK manager as administrator (run as administrator is not mandatory for this but preferred to avoid any permissions related issues) and check the required options and proceed with the installation without any issues.

SOLUTION 3:

-> If still your issue is not resolved, then try the proxy solution as suggested by others or check your internet connectivity if it's working properly or not.

*Any of the above solutions should resolve your issues.

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

In my case I had to move the @Service annotation from the interface to the implementation class.

$_POST not working. "Notice: Undefined index: username..."

You should check if the POST['username'] is defined. Use this above:

$username = "";

if(isset($_POST['username'])){
    $username = $_POST['username'];
}

"SELECT password FROM users WHERE username='".$username."'"

Unable to execute dex: Multiple dex files define

Even after going through multiple answers, no solution worked for me.

I deleted "Android Dependencies" from the build path. Added all the jar files again to the build path and the error was gone. Somehow eclipse seemed to cache the things.

iOS: present view controller programmatically

LandingScreenViewController *nextView=[self.storyboard instantiateViewControllerWithIdentifier:@"nextView"];
[self presentViewController:nextView animated:YES completion:^{}];

Convert NSArray to NSString in Objective-C

One approach would be to iterate over the array, calling the description message on each item:

NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
    [result appendString:[obj description]];
}
NSLog(@"The concatenated string is %@", result);

Another approach would be to do something based on each item's class:

NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
    if ([obj isKindOfClass:[NSNumber class]])
    {
        // append something
    }
    else
    {
        [result appendString:[obj description]];
    }
}
NSLog(@"The concatenated string is %@", result);

If you want commas and other extraneous information, you can just do:

NSString * result = [array description];

Default value of function parameter

In C++ the requirements imposed on default arguments with regard to their location in parameter list are as follows:

  1. Default argument for a given parameter has to be specified no more than once. Specifying it more than once (even with the same default value) is illegal.

  2. Parameters with default arguments have to form a contiguous group at the end of the parameter list.

Now, keeping that in mind, in C++ you are allowed to "grow" the set of parameters that have default arguments from one declaration of the function to the next, as long as the above requirements are continuously satisfied.

For example, you can declare a function with no default arguments

void foo(int a, int b);

In order to call that function after such declaration you'll have to specify both arguments explicitly.

Later (further down) in the same translation unit, you can re-declare it again, but this time with one default argument

void foo(int a, int b = 5);

and from this point on you can call it with just one explicit argument.

Further down you can re-declare it yet again adding one more default argument

void foo(int a = 1, int b);

and from this point on you can call it with no explicit arguments.

The full example might look as follows

void foo(int a, int b);

int main()
{
  foo(2, 3);

  void foo(int a, int b = 5); // redeclare
  foo(8); // OK, calls `foo(8, 5)`

  void foo(int a = 1, int b); // redeclare again
  foo(); // OK, calls `foo(1, 5)`
}

void foo(int a, int b)
{
  // ...
}

As for the code in your question, both variants are perfectly valid, but they mean different things. The first variant declares a default argument for the second parameter right away. The second variant initially declares your function with no default arguments and then adds one for the second parameter.

The net effect of both of your declarations (i.e. the way it is seen by the code that follows the second declaration) is exactly the same: the function has default argument for its second parameter. However, if you manage to squeeze some code between the first and the second declarations, these two variants will behave differently. In the second variant the function has no default arguments between the declarations, so you'll have to specify both arguments explicitly.

"static const" vs "#define" vs "enum"

Another drawback of const in C is that you can't use the value in initializing another const.

static int const NUMBER_OF_FINGERS_PER_HAND = 5;
static int const NUMBER_OF_HANDS = 2;

// initializer element is not constant, this does not work.
static int const NUMBER_OF_FINGERS = NUMBER_OF_FINGERS_PER_HAND 
                                     * NUMBER_OF_HANDS;

Even this does not work with a const since the compiler does not see it as a constant:

static uint8_t const ARRAY_SIZE = 16;
static int8_t const lookup_table[ARRAY_SIZE] = {
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // ARRAY_SIZE not a constant!

I'd be happy to use typed const in these cases, otherwise...

What does ':' (colon) do in JavaScript?

You guys are forgetting that the colon is also used in the ternary operator (though I don't know if jquery uses it for this purpose).

the ternary operator is an expression form (expressions return a value) of an if/then statement. it's used like this:

var result = (condition) ? (value1) : (value2) ;

A ternary operator could also be used to produce side effects just like if/then, but this is profoundly bad practice.

Create list of single item repeated N times

As others have pointed out, using the * operator for a mutable object duplicates references, so if you change one you change them all. If you want to create independent instances of a mutable object, your xrange syntax is the most Pythonic way to do this. If you are bothered by having a named variable that is never used, you can use the anonymous underscore variable.

[e for _ in xrange(n)]

Properties order in Margin

Margin="1,2,3,4"
  1. Left,
  2. Top,
  3. Right,
  4. Bottom

It is also possible to specify just two sizes like this:

Margin="1,2"
  1. Left AND right
  2. Top AND bottom

Finally you can specify a single size:

Margin="1"
  1. used for all sides

The order is the same as in WinForms.

How can one change the timestamp of an old commit in Git?

A better way to handle all of these suggestions in one command is

LC_ALL=C GIT_COMMITTER_DATE="$(date)" git commit --amend --no-edit --date "$(date)"

This will set the last commit's commit and author date to "right now."

WorksheetFunction.CountA - not working post upgrade to Office 2010

This code works for me:

Sub test()
    Dim myRange As Range
    Dim NumRows As Integer

    Set myRange = Range("A:A")
    NumRows = Application.WorksheetFunction.CountA(myRange)

    MsgBox NumRows
End Sub

Programmatically register a broadcast receiver

Define a broadcast receiver anywhere in Activity/Fragment like this:

mReceiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
     Log.d(TAG," onRecieve"); //do something with intent
   }
 };

Define IntentFilter in onCreate()

mIntentFilter=new IntentFilter("action_name");

Now register the BroadcastReciever in onResume() and Unregister it in onPause() [because there is no use of broadcast if the activity is paused].

@Override
protected void onResume() {
     super.onResume();
     registerReceiver(mReceiver, mIntentFilter);
}

@Override
protected void onPause() {
    if(mReceiver != null) {
            unregisterReceiver(mReceiver);
            mReceiver = null;
    }
    super.onPause();
}

For detail tutorial, have a look at broadcast receiver-two ways to implement.

How to read a string one letter at a time in python

Create a lookup table first:

morse = [None] * (ord('z') - ord('a') + 1)
for line in moreCodeFile:
    morse[ord(line[0].lower()) - ord('a')] = line[2:]

Then convert using the table:

for ch in userInput:
    print morse[ord(ch.lower()) - ord('a')]

Is Java a Compiled or an Interpreted programming language ?

Java is compiled to bytecode, which then goes into the Java VM, which interprets it.

How to keep onItemSelected from firing off on a newly instantiated Spinner?

After having had the same problem, I came to this solutions using tags. The idea behind it is simple: Whenever the spinner is changed programatically, make sure the tag reflects the selected position. In the listener then you check if the selected position equals the tag. If it does, the spinner selection was changed programatically.

Below is my new "spinner proxy" class:

package com.samplepackage;

import com.samplepackage.R;
import android.widget.Spinner;

public class SpinnerFixed {

    private Spinner mSpinner;

    public SpinnerFixed(View spinner) {
         mSpinner = (Spinner)spinner;
         mSpinner.setTag(R.id.spinner_pos, -2);
    }

    public boolean isUiTriggered() {
         int tag = ((Integer)mSpinner.getTag(R.id.spinner_pos)).intValue();
         int pos = mSpinner.getSelectedItemPosition();
         mSpinner.setTag(R.id.spinner_pos, pos);
         return (tag != -2 && tag != pos);
    }

    public void setSelection(int position) {
        mSpinner.setTag(R.id.spinner_pos, position);
        mSpinner.setSelection(position);
    }

    public void setSelection(int position, boolean animate) {
        mSpinner.setTag(R.id.spinner_pos, position);
        mSpinner.setSelection(position, animate);
    }

    // If you need to proxy more methods, use "Generate Delegate Methods"
    // from the context menu in Eclipse.
}

You will also need an XML file with the tag setup in your Values directory. I named my file spinner_tag.xml, but that's up to you. It looks like this:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
  <item name="spinner_pos" type="id" />
</resources>

Now replace

Spinner myspinner;
...
myspinner = (Spinner)findViewById(R.id.myspinner);

in your code with

SpinnerFixed myspinner;
...
myspinner = new SpinnerFixed(findViewById(R.id.myspinner));

And make your handler somewhat look like this:

myspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (myspinner.isUiTriggered()) {
            // Code you want to execute only on UI selects of the spinner
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
});

The function isUiTriggered() will return true if and only if the spinner has been changed by the user. Note that this function has a side effect - it will set the tag, so a second call in the same listener call will always return false.

This wrapper will also handle the problem with the listener being called during layout creation.

Have fun, Jens.

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

How to do Base64 encoding in node.js?

The accepted answer previously contained new Buffer(), which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).

The Buffer constructor is deprecated according to the documentation.

Here is an example of a vulnerability that can result from using it in the ws library.

The code snippets should read:

console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));

After this answer was written, it has been updated and now matches this.

Change icon-bar (?) color in bootstrap

Try over-riding CSS using !important

like this

.icon-bar {
   background-color:#FF0000 !important;
}

"Unmappable character for encoding UTF-8" error

I'm in the process of setting up a CI build server on a Linux box for a legacy system started in 2000. There is a section that generates a PDF that contains non-UTF8 characters. We are in the final steps of a release, so I cannot replace the characters giving me grief, yet for Dilbertesque reasons, I cannot wait a week to solve this issue after the release. Fortunately, the "javac" command in Ant has an "encoding" parameter.

 <javac destdir="${classes.dir}" classpathref="production-classpath" debug="on"
     includeantruntime="false" source="${java.level}" target="${java.level}"

     encoding="iso-8859-1">

     <src path="${production.dir}" />
 </javac>

String.Replace(char, char) method in C#

As replacing "\n" with "" doesn't give you the result that you want, that means that what you should replace is actually not "\n", but some other character combination.

One possibility is that what you should replace is the "\r\n" character combination, which is the newline code in a Windows system. If you replace only the "\n" (line feed) character it will leave the "\r" (carriage return) character, which still may be interpreted as a line break, depending on how you display the string.

If the source of the string is system specific you should use that specific string, otherwise you should use Environment.NewLine to get the newline character combination for the current system.

string temp = mystring.Replace("\r\n", string.Empty);

or:

string temp = mystring.Replace(Environment.NewLine, string.Empty);

Finding local maxima/minima with Numpy in a 1D numpy array

Why not use Scipy built-in function signal.find_peaks_cwt to do the job ?

from scipy import signal
import numpy as np

#generate junk data (numpy 1D arr)
xs = np.arange(0, np.pi, 0.05)
data = np.sin(xs)

# maxima : use builtin function to find (max) peaks
max_peakind = signal.find_peaks_cwt(data, np.arange(1,10))

# inverse  (in order to find minima)
inv_data = 1/data
# minima : use builtin function fo find (min) peaks (use inversed data)
min_peakind = signal.find_peaks_cwt(inv_data, np.arange(1,10))

#show results
print "maxima",  data[max_peakind]
print "minima",  data[min_peakind]

results:

maxima [ 0.9995736]
minima [ 0.09146464]

Regards

Float vs Decimal in ActiveRecord

In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.

  def change
    change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13
    change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13
  end

Angular 4 setting selected option in Dropdown

Here is my example:

<div class="form-group">
    <label for="contactMethod">Contact method</label>
    <select 
        name="contactMethod" 
        id="contactMethod" 
        class="form-control"
        [(ngModel)]="contact.contactMethod">
        <option *ngFor="let method of contactMethods" [value]="method.id">{{ method.label }}</option>
    </select>
</div>

And in component you must get values from select:

contactMethods = [
    { id: 1, label: "Email" },
    { id: 2, label: "Phone" }
]

So, if you want select to have a default value selected (and proabbly you want that):

contact = {
    firstName: "CFR",
    comment: "No comment",
    subscribe: true,
    contactMethod: 2 // this id you'll send and get from backend
}

How to use XPath preceding-sibling correctly

I also like to build locators from up to bottom like:

//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']

It's pretty simple, as we just search btn-group with button[contains(.,'Arcade Reader')] and get it's button[@name='settings']

That's just another option to build xPath locators

What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:

getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");

or even simplify more

getGroupButton("Arcade Reader", "delete").click();

How do I add a margin between bootstrap columns without wrapping

If you do not need to add a border on columns, you can also simply add a transparent border on them:

[class*="col-"] {
    background-clip: padding-box;
    border: 10px solid transparent;
}

Custom exception type

In short:

Option 1: use babel-plugin-transform-builtin-extend

Option 2: do it yourself (inspired from that same library)

    function CustomError(...args) {
      const instance = Reflect.construct(Error, args);
      Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this));
      return instance;
    }
    CustomError.prototype = Object.create(Error.prototype, {
      constructor: {
        value: Error,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    Reflect.setPrototypeOf(CustomError, Error);
  • If you are using pure ES5:

    function CustomError(message, fileName, lineNumber) {
      const instance = new Error(message, fileName, lineNumber);
      Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
      return instance;
    }
    CustomError.prototype = Object.create(Error.prototype, {
      constructor: {
        value: Error,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    if (Object.setPrototypeOf){
        Object.setPrototypeOf(CustomError, Error);
    } else {
        CustomError.__proto__ = Error;
    }
    
  • Alternative: use Classtrophobic framework

Explanation:

Why extending the Error class using ES6 and Babel is a problem?

Because an instance of CustomError is not anymore recognized as such.

class CustomError extends Error {}
console.log(new CustomError('test') instanceof Error);// true
console.log(new CustomError('test') instanceof CustomError);// false

In fact, from the official documentation of Babel, you cannot extend any built-in JavaScript classes such as Date, Array, DOM or Error.

The issue is described here:

What about the other SO answers?

All the given answers fix the instanceof issue but you lose the regular error console.log:

console.log(new CustomError('test'));
// output:
// CustomError {name: "MyError", message: "test", stack: "Error?    at CustomError (<anonymous>:4:19)?    at <anonymous>:1:5"}

Whereas using the method mentioned above, not only you fix the instanceof issue but you also keep the regular error console.log:

console.log(new CustomError('test'));
// output:
// Error: test
//     at CustomError (<anonymous>:2:32)
//     at <anonymous>:1:5

org.json.simple cannot be resolved

Probably your simple json.jar file isn't in your classpath.

Optional args in MATLAB functions

A simple way of doing this is via nargin (N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.

It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b and c. Will exit if a is not present.

function [ output_args ] = input_example( a, b, c )
if nargin < 1
  error('input_example :  a is a required input')
end

if nargin < 2
  b = 20
end

if nargin < 3
  c = 30
end
end

How can I convert a zero-terminated byte array to string?

  • Use slices instead of arrays for reading. For example, io.Reader accepts a slice, not an array.

  • Use slicing instead of zero padding.

Example:

buf := make([]byte, 100)
n, err := myReader.Read(buf)
if n == 0 && err != nil {
    log.Fatal(err)
}

consume(buf[:n]) // consume() will see an exact (not padded) slice of read data

location.host vs location.hostname and cross-browser compatibility?

Your primary question has been answered above. I just wanted to point out that the regex you're using has a bug. It will also succeed on foo-domain.com which is not a subdomain of domain.com

What you really want is this:

/(^|\.)domain\.com$/

Changing element style attribute dynamically using JavaScript

document.getElementById("xyz").setAttribute('style','padding-top:10px');

would also do the job.

ld cannot find -l<library>

You may install your coinhsl library in one of your standard libraries directories and run 'ldconfig` before doing your ppyipopt install

How to get html table td cell value by JavaScript?

You can use:

<td onclick='javascript:someFunc(this);'></td>

With passing this you can access the DOM object via your function parameters.

PHP mysql insert date format

The simplest method is

$dateArray = explode('/', $_POST['date']);
$date = $dateArray[2].'-'.$dateArray[0].'-'.$dateArray[1];

$sql = mysql_query("INSERT INTO user_date (column,column,column) VALUES('',$name,$date)") or die (mysql_error());

How to open select file dialog via js?

In HTML only:

<label>
  <input type="file" name="input-name" style="display: none;" />
  <span>Select file</span>
</label>

Edit: I hadn't tested this in Blink, it actually doesn't work with a <button>, but it should work with most other elementsโ€“at least in recent browsers.

Check this fiddle with the code above.

Options for initializing a string array

string[] str = new string[]{"1","2"};
string[] str = new string[4];

jQuery checkbox event handling

$('#myform :checkbox').change(function() {
    // this will contain a reference to the checkbox   
    if (this.checked) {
        // the checkbox is now checked 
    } else {
        // the checkbox is now no longer checked
    }
});

How do you run a crontab in Cygwin on Windows?

I figured out how to get the Cygwin cron service running automatically when I logged on to Windows 7. Here's what worked for me:

Using Notepad, create file C:\cygwin\bin\Cygwin_launch_crontab_service_input.txt with content no on the first line and yes on the second line (without the quotes). These are your two responses to prompts for cron-config.

Create file C:\cygwin\Cygwin_launch_crontab_service.bat with content:

@echo off
C:
chdir C:\cygwin\bin
bash  cron-config < Cygwin_launch_crontab_service_input.txt

Add a Shortcut to the following in the Windows Startup folder: Cygwin_launch_crontab_service.bat

See http://www.sevenforums.com/tutorials/1401-startup-programs-change.html if you need help on how to add to Startup. BTW, you can optionally add these in Startup if you would like:

Cygwin

XWin Server

The first one executes

C:\cygwin\Cygwin.bat

and the second one executes

C:\cygwin\bin\run.exe /usr/bin/bash.exe -l -c /usr/bin/startxwin.exe

how to display a javascript var in html body

Index.html:

<html>
<body>
    Javascript Version: <b id="version"></b>
    <script src="app.js"></script>
</body>
</html>

app.js:

var ver="1.1";
document.getElementById("version").innerHTML = ver;

Powershell Log Off Remote Session

You can use Invoke-RDUserLogoff

An example logging off Active Directory users of a specific Organizational Unit:

$users = Get-ADUser -filter * -SearchBase "ou=YOUR_OU_NAME,dc=contoso,dc=com"

Get-RDUserSession | where { $users.sAMAccountName -contains $_.UserName } | % { $_ | Invoke-RDUserLogoff -Force }

At the end of the pipe, if you try to use only foreach (%), it will log off only one user. But using this combination of foreach and pipe:

| % { $_ | command }

will work as expected.

Ps. Run as Adm.

Single vs double quotes in JSON

Two issues with answers given so far, if , for instance, one streams such non-standard JSON. Because then one might have to interpret an incoming string (not a python dictionary).

Issue 1 - demjson: With Python 3.7.+ and using conda I wasn't able to install demjson since obviosly it does not support Python >3.5 currently. So I need a solution with simpler means, for instance astand/or json.dumps.

Issue 2 - ast & json.dumps: If a JSON is both single quoted and contains a string in at least one value, which in turn contains single quotes, the only simple yet practical solution I have found is applying both:

In the following example we assume line is the incoming JSON string object :

>>> line = str({'abc':'008565','name':'xyz','description':'can control TV\'s and more'})

Step 1: convert the incoming string into a dictionary using ast.literal_eval()
Step 2: apply json.dumps to it for the reliable conversion of keys and values, but without touching the contents of values:

>>> import ast
>>> import json
>>> print(json.dumps(ast.literal_eval(line)))
{"abc": "008565", "name": "xyz", "description": "can control TV's and more"}

json.dumps alone would not do the job because it does not interpret the JSON, but only see the string. Similar for ast.literal_eval(): although it interprets correctly the JSON (dictionary), it does not convert what we need.

Convert Enum to String

I create a "Description" extension method and attach it to the enum so that i can get truly user-friendly naming that includes spaces and casing. I have never liked using the enum value itself as displayable text because it is something we developers use to create more readable code. It is not intended for UI display purposes. I want to be able to change the UI without going through and changing enums all over.

The program can't start because cygwin1.dll is missing... in Eclipse CDT

This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.

There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.

What does MissingManifestResourceException mean and how to fix it?

Recently stumbled upon this issue, in my case I did a few things:

  1. Make sure the namespaces are consistent in the Designer.cs file of the resx file

  2. Make sure the default namespace of the Assembly(right click the project and choose Properties) is set the same to the namespace the resources file is in.

Once I did step 2, the exception went away.

How to access my localhost from another PC in LAN?

You have to edit httpd.conf and find this line: Listen 127.0.0.1:80

Then write down your desired IP you set for LAN. Don't use automatic IP.
e.g.: Listen 192.168.137.1:80

I used 192.167.137.1 as my LAN IP of Windows 7. Restart Apache and enjoy sharing.

Linux: where are environment variables stored?

It's stored in the process (shell) and since you've exported it, any processes that process spawns.

Doing the above doesn't store it anywhere in the filesystem like /etc/profile. You have to put it there explicitly for that to happen.

Adding new files to a subversion repository

Probably svn import would be the best option around. Check out Getting Data into Your Repository (in Version Control with Subversion, For Subversion).

The svn import command is a quick way to copy an unversioned tree of files into a repository, creating intermediate directories as necessary. svn import doesn't require a working copy, and your files are immediately committed to the repository. You typically use this when you have an existing tree of files that you want to begin tracking in your Subversion repository. For example:

$ svn import /path/to/mytree \
             http://svn.example.com/svn/repo/some/project \
             -m "Initial import"
Adding         mytree/foo.c
Adding         mytree/bar.c
Adding         mytree/subdir
Adding         mytree/subdir/quux.h

Committed revision 1.
$

The previous example copied the contents of the local directory mytree into the directory some/project in the repository. Note that you didn't have to create that new directory firstโ€”svn import does that for you. Immediately after the commit, you can see your data in the repository:

$ svn list http://svn.example.com/svn/repo/some/project
bar.c
foo.c
subdir/
$

Note that after the import is finished, the original local directory is not converted into a working copy. To begin working on that data in a versioned fashion, you still need to create a fresh working copy of that tree.

Note: if you are on the same machine as the Subversion repository you can use the file:// specifier with a path rather than the https:// with a URL specifier.

What is android:weightSum in android, and how does it work?

One thing which seems like no one else mentioned: let's say you have a vertical LinearLayout, so in order for the weights in layout/element/view inside it to work 100% properly - all of them must have layout_height property (which must exist in your xml file) set to 0dp. Seems like any other value would mess things up in some cases.

Java: Check if enum contains a given string?

  Set.of(CustomType.values())
     .contains(customTypevalue) 

html table cell width for different rows

You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.

You can however have cells span multiple columns, such as:

<table>
    <tr>
        <td>25</td>
        <td>50</td>
        <td>25</td>
    </tr>
    <tr>
        <td colspan="2">75</td>
        <td>20</td>
    </tr>
</table>

As an aside, you should avoid using style attributes like border and bgcolor and prefer CSS for those.

How to set top-left alignment for UILabel for iOS application?

The simplest and easiest way is to embed Label in StackView and setting StackView's Axis to Horizontal, Alignment to Top in Attribute Inspector from Storyboard like shown here.

Symfony 2 EntityManager injection in service

Your class's constructor method should be called __construct(), not __constructor():

public function __construct(EntityManager $entityManager)
{
    $this->em = $entityManager;
}

How to delete object?

Use a collection that is a static property of your Car class. Every time you create a new instance of a Car, store the reference in this collection.

To destroy all Cars, just set all items to null.

Free Rest API to retrieve current datetime as string (timezone irrelevant)

This API gives you the current time and several formats in JSON - https://market.mashape.com/parsify/format#time. Here's a sample response:

{
  "time": {
    "daysInMonth": 31,
    "millisecond": 283,
    "second": 42,
    "minute": 55,
    "hour": 1,
    "date": 6,
    "day": 3,
    "week": 10,
    "month": 2,
    "year": 2013,
    "zone": "+0000"
  },
  "formatted": {
    "weekday": "Wednesday",
    "month": "March",
    "ago": "a few seconds",
    "calendar": "Today at 1:55 AM",
    "generic": "2013-03-06T01:55:42+00:00",
    "time": "1:55 AM",
    "short": "03/06/2013",
    "slim": "3/6/2013",
    "hand": "Mar 6 2013",
    "handTime": "Mar 6 2013 1:55 AM",
    "longhand": "March 6 2013",
    "longhandTime": "March 6 2013 1:55 AM",
    "full": "Wednesday, March 6 2013 1:55 AM",
    "fullSlim": "Wed, Mar 6 2013 1:55 AM"
  },
  "array": [
    2013,
    2,
    6,
    1,
    55,
    42,
    283
  ],
  "offset": 1362534942283,
  "unix": 1362534942,
  "utc": "2013-03-06T01:55:42.283Z",
  "valid": true,
  "integer": false,
  "zone": 0
}

How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010

if you have 2 versions of any of your code file (*.cs, *.vb etc.) inside your "app_code" folder then you will get this error because dot net would include both the files in your project and will get 2 different implementations of the same class (because of same name in 2 versions of same code file in app_code folder)

Android: Create spinner programmatically from array

this work for me:-

String[] array = {"A", "B", "C"};
String abc = "";


Spinner spinner = new Spinner(getContext());
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, array); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);

I am using a Fragment.

How to write dynamic variable in Ansible playbook

I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:

   vars:
    myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"

How to POST the data from a modal form of Bootstrap?

You need to handle it via ajax submit.

Something like this:

$(function(){
    $('#subscribe-email-form').on('submit', function(e){
        e.preventDefault();
        $.ajax({
            url: url, //this is the submit URL
            type: 'GET', //or POST
            data: $('#subscribe-email-form').serialize(),
            success: function(data){
                 alert('successfully submitted')
            }
        });
    });
});

A better way would be to use a django form, and then render the following snippet:

<form>
    <div class="modal-body">
        <input type="email" placeholder="email"/>
        <p>This service will notify you by email should any issue arise that affects your plivo service.</p>
    </div>
    <div class="modal-footer">
        <input type="submit" value="SUBMIT" class="btn"/>
    </div>
</form>

via the context - example : {{form}}.

Cannot get to $rootScope

You can not ask for instance during configuration phase - you can ask only for providers.

var app = angular.module('modx', []);

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  // you can inject any provider here
});

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

See http://docs.angularjs.org/guide/module for more info.

How to set Grid row and column positions programmatically

Try this:

                Grid grid = new Grid(); //Define the grid
                for (int i = 0; i < 36; i++) //Add 36 rows
                {
                    ColumnDefinition columna = new ColumnDefinition()
                    {
                        Name = "Col_" + i,
                        Width = new GridLength(32.5),
                    };
                    grid.ColumnDefinitions.Add(columna);
                }

                for (int i = 0; i < 36; i++) //Add 36 columns
                {
                    RowDefinition row = new RowDefinition();
                    row.Height = new GridLength(40, GridUnitType.Pixel);
                    grid.RowDefinitions.Add(row);
                }

                for (int i = 0; i < 36; i++)
                {
                    for (int j = 0; j < 36; j++)
                    {
                        Label t1 = new Label()
                        {
                            FontSize = 10,
                            FontFamily = new FontFamily("consolas"),
                            FontWeight = FontWeights.SemiBold,
                            BorderBrush = Brushes.LightGray,
                            BorderThickness = new Thickness(2),
                            HorizontalContentAlignment = HorizontalAlignment.Center,
                            VerticalContentAlignment = VerticalAlignment.Center,
                        };
                        Grid.SetRow(t1, i);
                        Grid.SetColumn(t1, j);
                        grid.Children.Add(t1); //Add the Label Control to the Grid created
                    }
                }

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Explicitly filling in the ContentDisposition fields did the trick.

if (attachmentFilename != null)
{
    Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
    ContentDisposition disposition = attachment.ContentDisposition;
    disposition.CreationDate = File.GetCreationTime(attachmentFilename);
    disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
    disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
    disposition.FileName = Path.GetFileName(attachmentFilename);
    disposition.Size = new FileInfo(attachmentFilename).Length;
    disposition.DispositionType = DispositionTypeNames.Attachment;
    message.Attachments.Add(attachment);                
}

BTW, in case of Gmail, you may have some exceptions about ssl secure or even port!

smtpClient.EnableSsl = true;
smtpClient.Port = 587;

Is it possible to decrypt MD5 hashes?

The only thing that can be work is (if we mention that the passwords are just hashed, without adding any kind of salt to prevent the replay attacks, if it is so you must know the salt)by the way, get an dictionary attack tool, the files of many words, numbers etc. then create two rows, one row is word,number (in dictionary) the other one is hash of the word, and compare the hashes if matches you get it...

that's the only way, without going into cryptanalysis.

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

You can use below code for your solution:-

public void Linq94() 
{ 
    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
    int[] numbersB = { 1, 3, 5, 7, 8 }; 

    var allNumbers = numbersA.Concat(numbersB); 

    Console.WriteLine("All numbers from both arrays:"); 
    foreach (var n in allNumbers) 
    { 
        Console.WriteLine(n); 
    } 
}

Hide text using css

If we can edit the markup, life can be easier, just remove text and be happy. But sometimes the markup was placed by JS code or we just aren't allowed to edit it at all, too bad css turned to be the only weapon placed at our disposal.

We cannot place a <span> wrapping the text and hide the whole tag. By the way, some browsers do not only hides elements with display:none but also disables the components inside.

Both font-size:0px and color:transparent may be good solutions, but some browsers don't understand them. We can't rely on them.

I suggest:

h1 {
  background-image: url(/LOGO.png);  /* Our image */
  text-indent: -3000px;  /* Send text out of viewable area */
  height: 100px; width: 600px;  /* height and width are a must, agree */
  overflow:hidden;  /* make sure our size is respected */
}

Using overflow:hidden enforces our width & height. Some browsers (will not name them... IE) may read width and height as min-width and min-height. I want to prevent box to be enlarged.

Remove blank attributes from an Object in Javascript

Here's an alternative

Typescript:

function objectDefined <T>(obj: T): T {
  const acc: Partial<T> = {};
  for (const key in obj) {
    if (obj[key] !== undefined) acc[key] = obj[key];
  }
  return acc as T;
}

Javascript:

function objectDefined(obj) {
  const acc = {};
  for (const key in obj) {
    if (obj[key] !== undefined) acc[key] = obj[key];
  }
  return acc;
}

How to enable C++11/C++0x support in Eclipse CDT?

Neither the hack nor the cleaner version work for Indigo. The hack is ignored, and the required configuration options are missing. For no apparent reason, build started working after not working and not providing any useful reason why. At least from the command line, I get reproducible results.

When to use @QueryParam vs @PathParam

I think that if the parameter identifies a specific entity you should use a path variable. For example, to get all the posts on my blog I request

GET: myserver.com/myblog/posts

to get the post with id = 123, I would request

GET: myserver.com/myblog/posts/123

but to filter my list of posts, and get all posts since Jan 1, 2013, I would request

GET: myserver.com/myblog/posts?since=2013-01-01

In the first example "posts" identifies a specific entity (the entire collection of blog posts). In the second example, "123" also represents a specific entity (a single blog post). But in the last example, the parameter "since=2013-01-01" is a request to filter the posts collection not a specific entity. Pagination and ordering would be another good example, i.e.

GET: myserver.com/myblog/posts?page=2&order=backward

Hope that helps. :-)

Auto Generate Database Diagram MySQL

MySQL Workbench worked like a charm.

I just backed up database structure to SQL script and used it in "Create EER Model From SQL Script" of MWB 5.2.37 for Windows.

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

I just tried with PHP 5.2, and that constant seems to exists :

var_dump(PDO::MYSQL_ATTR_INIT_COMMAND);

Gives me :

int 1002


But it seems there is a bug in PHP 5.3, that causes this constant to not exists anymore -- or, at least, not when the mysqlnd driver is used (and it's the one that's configured by default)

I suppose a temporary solution, as suggested on this bug report, could be to directly use the integer 1002 value, instead of the contant...

But note that you should go back to using the constant as soon as possible -- as this makes the code easier to understand.

User Control - Custom Properties

It is very simple, just add a property:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes to put it back in working order:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always), Bindable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override string Text {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

How can I convert JSON to a HashMap using Gson?

JSONObject typically uses HashMap internally to store the data. So, you can use it as Map in your code.

Example,

JSONObject obj = JSONObject.fromObject(strRepresentation);
Iterator i = obj.entrySet().iterator();
while (i.hasNext()) {
   Map.Entry e = (Map.Entry)i.next();
   System.out.println("Key: " + e.getKey());
   System.out.println("Value: " + e.getValue());
}

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

If you don't need the code to be portable to old unices, you can use clock_gettime(), which will give you the time in nanoseconds (if your processor supports that resolution). It's POSIX, but from 2001.

Run script on mac prompt "Permission denied"

use source before file name,,

like my file which i want to run from terminal is ./jay/bin/activate

so i used command "source ./jay/bin/activate"

Show space, tab, CRLF characters in editor of Visual Studio

My problem was hitting CTRL+F and space

This marked all spaces brown. Spent 10 minutes to "turn it off" :P

Javascript receipt printing using POS Printer

Maybe you could have a look at this if your printer is an epson. There is a javascript driver

http://spsrprofessionals.com/ClientSite/readers/ePOS-Print_SDK_141020E/JavaScript/ePOS-Print_SDK_JS_en_revB.pdf

EDIT:

Previous link seems to be broken

All details about how to use epos of epson are on epson website:

https://reference.epson-biz.com/modules/ref_epos_device_js_en/index.php?content_id=139

"Sub or Function not defined" when trying to run a VBA script in Outlook

I had a similar situation with this issue. In this case it would have looked like this

Sub Test()
   MsqBox ("Hello world")
End Sub

The problem was, that I had a lot more code there and couldn't recognize, that there was a misspelling in "MsqBox" (q instead of g) and therefore I had an error, it was really misleading, but since you can get on this error like that, maybe someone else will notice that it was cause by a misspelling like this...

Yahoo Finance API

IMHO the best place to find this information is: http://code.google.com/p/yahoo-finance-managed/

I used to use the "gummy-stuff" too but then I found this page which is far more organized and full of easy to use examples. I am using it now to get the data in CSV files and use the files in my C++/Qt project.

E: Unable to locate package npm

This will resolve your error. Run these commands in your terminal. These commands will add the older versions. You can update them later or you can change version here too before running these commands one by one.

sudo apt-get install build-essential
wget http://nodejs.org/dist/v0.8.16/node-v0.8.16.tar.gz
tar -xzf node-v0.8.16.tar.gz
cd node-v0.8.16/
./configure
make
sudo make install

Adding a new entry to the PATH variable in ZSH

  1. Added path to ~/.zshrc

    sudo vi ~/.zshrc

    add new path

    export PATH="$PATH:[NEW_DIRECTORY]/bin"
    
  2. Update ~/.zshrc

    Save ~/.zshrc

    source ~/.zshrc

  3. Check PATH

    echo $PATH

How do I output lists as a table in Jupyter notebook?

I just discovered that tabulate has a HTML option and is rather simple to use.
Quite similar to Wayne Werner's answer:

from IPython.display import HTML, display
import tabulate
table = [["Sun",696000,1989100000],
         ["Earth",6371,5973.6],
         ["Moon",1737,73.5],
         ["Mars",3390,641.85]]
display(HTML(tabulate.tabulate(table, tablefmt='html')))

Still looking for something simple to use to create more complex table layouts like with latex syntax and formatting to merge cells and do variable substitution in a notebook:
Allow references to Python variables in Markdown cells #2958

How to include files outside of Docker's build context?

In my case, my Dockerfile is written like a template containing placeholders which I'm replacing with real value using my configuration file.

So I couldn't specify this file directly but pipe it into the docker build like this:

sed "s/%email_address%/$EMAIL_ADDRESS/;" ./Dockerfile | docker build -t katzda/bookings:latest . -f -;

But because of the pipe, the COPY command didn't work. But the above way solves it by -f - (explicitly saying file not provided). Doing only - without the -f flag, the context AND the Dockerfile are not provided which is a caveat.

How can I display a tooltip on an HTML "option" tag?

If increasing the number of visible options is available, the following might work for you:

<html>
    <head>
        <title>Select Option Tooltip Test</title>
        <script>
            function showIETooltip(e){
                if(!e){var e = window.event;}
                var obj = e.srcElement;
                var objHeight = obj.offsetHeight;
                var optionCount = obj.options.length;
                var eX = e.offsetX;
                var eY = e.offsetY;

                //vertical position within select will roughly give the moused over option...
                var hoverOptionIndex = Math.floor(eY / (objHeight / optionCount));

                var tooltip = document.getElementById('dvDiv');
                tooltip.innerHTML = obj.options[hoverOptionIndex].title;

                mouseX=e.pageX?e.pageX:e.clientX;
                mouseY=e.pageY?e.pageY:e.clientY;

                tooltip.style.left=mouseX+10;
                tooltip.style.top=mouseY;

                tooltip.style.display = 'block';

                var frm = document.getElementById("frm");
                frm.style.left = tooltip.style.left;
                frm.style.top = tooltip.style.top;
                frm.style.height = tooltip.offsetHeight;
                frm.style.width = tooltip.offsetWidth;
                frm.style.display = "block";
            }
            function hideIETooltip(e){
                var tooltip = document.getElementById('dvDiv');
                var iFrm = document.getElementById('frm');
                tooltip.innerHTML = '';
                tooltip.style.display = 'none';
                iFrm.style.display = 'none';
            }
        </script>
    </head>
    <body>
        <select onmousemove="showIETooltip();" onmouseout="hideIETooltip();" size="10">
            <option title="Option #1" value="1">Option #1</option>
            <option title="Option #2" value="2">Option #2</option>
            <option title="Option #3" value="3">Option #3</option>
            <option title="Option #4" value="4">Option #4</option>
            <option title="Option #5" value="5">Option #5</option>
            <option title="Option #6" value="6">Option #6</option>
            <option title="Option #7" value="7">Option #7</option>
            <option title="Option #8" value="8">Option #8</option>
            <option title="Option #9" value="9">Option #9</option>
            <option title="Option #10" value="10">Option #10</option>
        </select>
        <div id="dvDiv" style="display:none;position:absolute;padding:1px;border:1px solid #333333;;background-color:#fffedf;font-size:smaller;z-index:999;"></div>
        <iframe id="frm" style="display:none;position:absolute;z-index:998"></iframe>
    </body>
</html>

How to install latest version of Node using Brew

Just go old skool - https://nodejs.org/en/download/current/ From there you can get the current or LTS versions

Create an Excel file using vbscripts

'Create Excel

Set objExcel = Wscript.CreateObject("Excel.Application")

objExcel.visible = True

Set objWb = objExcel.Workbooks.Add

objWb.Saveas("D:\Example.xlsx")

objExcel.Quit

Debian 8 (Live-CD) what is the standard login and password?

I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:

login : Debian Live User
password : live

I hope this helps

json parsing error syntax error unexpected end of input

I can't say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.

Anyway, you shouldn't hardcode your JSON as strings as you have done. Instead the proper way to send JSON data to the server is to use a JSON serializer:

data: JSON.stringify({ name : "AA" }),

Now on the server also make sure that you have the proper view model expecting to receive this input:

public class UserViewModel
{
    public string Name { get; set; }
}

and the corresponding action:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
}

Now there's one more thing. You have specified dataType: 'json'. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It's when jQuery attempts to parse the response from the server:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
    return Json(new { Foo = "bar" });
}

This being said, in most cases, usually you don't need to set the dataType property when making AJAX request to an ASP.NET MVC controller action. The reason for this is because when you return some specific ActionResult (such as a ViewResult or a JsonResult), the framework will automatically set the correct Content-Type response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.

I suspect that the problem you are having here is that your server didn't return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).

One more thing that I just noticed:

async: false,

Please, avoid setting this attribute to false. If you set this attribute to false you are are freezing the client browser during the entire execution of the request. You could just make a normal request in this case. If you want to use AJAX, start thinking in terms of asynchronous events and callbacks.

Python - Get path of root project structure

Other answers advice to use a file in the top-level of the project. This is not necessary if you use pathlib.Path and parent (Python 3.4 and up). Consider the following directory structure where all files except README.md and utils.py have been omitted.

project
ยฆ   README.md
|
+---src
ยฆ   ยฆ   utils.py
|   |   ...
|   ...

In utils.py we define the following function.

from pathlib import Path

def get_project_root() -> Path:
    return Path(__file__).parent.parent

In any module in the project we can now get the project root as follows.

from src.utils import get_project_root

root = get_project_root()

Benefits: Any module which calls get_project_root can be moved without changing program behavior. Only when the module utils.py is moved we have to update get_project_root and the imports (refactoring tools can be used to automate this).

How to connect to mysql with laravel?

You probably only forgot to create database. Enter your PHPMyAdmin and do it from there.

Edit: Definitely don't go with Maulik's answer. Not only it is using mysql_ extenstion (which is commonly recognized bad practice), Laravel is also taking care of your connections using PDO.

no overload for matches delegate 'system.eventhandler'

Yes there is a problem with Click event handler (klik) - First argument must be an object type and second must be EventArgs.

public void klik(object sender, EventArgs e) {
  //
}

If you want to paint on a form or control then use CreateGraphics method.

public void klik(object sender, EventArgs e) {
    Bitmap c = this.DrawMandel();
    Graphics gr = CreateGraphics();  // Graphics gr=(sender as Button).CreateGraphics();
    gr.DrawImage(b, 150, 200);
}

what is this value means 1.845E-07 in excel?

Highlight the cells, format cells, select Custom then select zero.

Clicking URLs opens default browser

Arulx Z's answer was exactly what I was looking for.

I'm writing an app with Navigation Drawer with recyclerview and webviews, for keeping the web browsing inside the app regardless of hyperlinks clicked (thus not launching the external web browser). For that it will suffice to put the following 2 lines of code:

mWebView.setWebChromeClient(new WebChromeClient()); mWebView.setWebViewClient(new WebViewClient());?

exactly under your WebView statement.

Here's a example of my implemented WebView code:

public class WebView1 extends AppCompatActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    WebView wv = (WebView) findViewById(R.id.wv1); //webview statement
    wv.setWebViewClient(new WebViewClient());    //the lines of code added
    wv.setWebChromeClient(new WebChromeClient()); //same as above

    wv.loadUrl("http://www.google.com");
}}

this way, every link clicked in the website will load inside your WebView. (Using Android Studio 1.2.2 with all SDK's updated)

How do I install SciPy on 64 bit Windows?

Short answer: Windows 64 bit support is still work in progress at this time. The superpack will certainly not work on a 64-bits Python (but it should work fine on a 32 bits Python, even on Windows 64 bit).

The main issue with Windows 64 bit is that building with mingw-w64 is not stable at this point: it may be our's (NumPy developers) fault, Python's fault or mingw-w64. Most likely a combination of all those :). So you have to use proprietary compilers: anything other than the Microsoft compiler crashes NumPy randomly; for the Fortran compiler, ifort is the one to use. As of today, both NumPy and SciPy source code can be compiled with Visual Studio 2008 and ifort (all tests passing), but building it is still quite a pain, and not well supported by the NumPy build infrastructure.

What exactly are DLL files, and how do they work?

Letโ€™s say you are making an executable that uses some functions found in a library.

If the library you are using is static, the linker will copy the object code for these functions directly from the library and insert them into the executable.

Now if this executable is run it has every thing it needs, so the executable loader just loads it into memory and runs it.

If the library is dynamic the linker will not insert object code but rather it will insert a stub which basically says this function is located in this DLL at this location.

Now if this executable is run, bits of the executable are missing (i.e the stubs) so the loader goes through the executable fixing up the missing stubs. Only after all the stubs have been resolved will the executable be allowed to run.

To see this in action delete or rename the DLL and watch how the loader will report a missing DLL error when you try to run the executable.

Hence the name Dynamic Link Library, parts of the linking process is being done dynamically at run time by the executable loader.

One a final note, if you don't link to the DLL then no stubs will be inserted by the linker, but Windows still provides the GetProcAddress API that allows you to load an execute the DLL function entry point long after the executable has started.

Center a position:fixed element

Just add:

left: calc(-50vw + 50%);
right: calc(-50vw + 50%);
margin-left: auto;
margin-right: auto;

Download file of any type in Asp.Net MVC using FileResult?

Phil Haack has a nice article where he created a Custom File Download Action Result class. You only need to specify the virtual path of the file and the name to be saved as.

I used it once and here's my code.

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Download(int fileID)
        {
            Data.LinqToSql.File file = _fileService.GetByID(fileID);

            return new DownloadResult { VirtualPath = GetVirtualPath(file.Path),
                                        FileDownloadName = file.Name };
        }

In my example i was storing the physical path of the files so i used this helper method -that i found somewhere i can't remember- to convert it to a virtual path

        private string GetVirtualPath(string physicalPath)
        {
            string rootpath = Server.MapPath("~/");

            physicalPath = physicalPath.Replace(rootpath, "");
            physicalPath = physicalPath.Replace("\\", "/");

            return "~/" + physicalPath;
        }

Here's the full class as taken from Phill Haack's article

public class DownloadResult : ActionResult {

    public DownloadResult() {}

    public DownloadResult(string virtualPath) {
        this.VirtualPath = virtualPath;
    }

    public string VirtualPath {
        get;
        set;
    }

    public string FileDownloadName {
        get;
        set;
    }

    public override void ExecuteResult(ControllerContext context) {
        if (!String.IsNullOrEmpty(FileDownloadName)) {
            context.HttpContext.Response.AddHeader("content-disposition", 
            "attachment; filename=" + this.FileDownloadName)
        }

        string filePath = context.HttpContext.Server.MapPath(this.VirtualPath);
        context.HttpContext.Response.TransmitFile(filePath);
    }
}

Identifying country by IP address

Yes, you can download the IP address ranges by country from https://lite.ip2location.com/ip-address-ranges-by-country

You can see that each country has multiple ranges and changes frequently.

Change bootstrap datepicker date format on select

for me with bootstrap 4 datetime picker (http://www.eyecon.ro/bootstrap-datepicker/) format worked only with upper case:

$('.datepicker').datetimepicker({
            format: 'DD/MM/YYYY'
        });

Adding integers to an int array

Arrays are different than ArrayLists, on which you could call add. You'll need an index first. Declare i before the for loop. Then you can use an array access expression to assign the element to the array.

num[i] = s;
i++;

Typescript: React event types

for update: event: React.ChangeEvent for submit: event: React.FormEvent for click: event: React.MouseEvent

How to know if docker is already logged in to a docker registry server

If you want a simple true/false value, you can pipe your docker.json to jq.

is_logged_in() {
  cat ~/.docker/config.json | jq -r --arg url "${REPOSITORY_URL}" '.auths | has($url)'
}

if [[ "$(is_logged_in)" == "false" ]]; then
  # do stuff, log in
fi

Recommended way to insert elements into map

To quote:

Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.

So insert will not change the value if the key already exists, the [] operator will.

EDIT:

This reminds me of another recent question - why use at() instead of the [] operator to retrieve values from a vector. Apparently at() throws an exception if the index is out of bounds whereas [] operator doesn't. In these situations it's always best to look up the documentation of the functions as they will give you all the details. But in general, there aren't (or at least shouldn't be) two functions/operators that do the exact same thing.

My guess is that, internally, insert() will first check for the entry and afterwards itself use the [] operator.

Checking if form has been submitted - PHP

Actually, the submit button already performs this function.

Try in the FORM:

<form method="post">
<input type="submit" name="treasure" value="go!">
</form>

Then in the PHP handler:

if (isset($_POST['treasure'])){
echo "treasure will be set if the form has been submitted (to TRUE, I believe)";
}

What USB driver should we use for the Nexus 5?

The one from Google USB Driver worked fine for me on two machines (Windows 7 x64 on both). Once Windows failed to auto-install the driver, I just right-clicked on the phone in Device Manager, chose "update driver" and gave it the path that I'd unzipped that driver into.

How to prevent Browser cache on Angular 2 site?

A combination of @Jack's answer and @ranierbit's answer should do the trick.

Set the ng build flag for --output-hashing so:

ng build --output-hashing=all

Then add this class either in a service or in your app.module

@Injectable()
export class NoCacheHeadersInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler) {
        const authReq = req.clone({
            setHeaders: {
                'Cache-Control': 'no-cache',
                 Pragma: 'no-cache'
            }
        });
        return next.handle(authReq);    
    }
}

Then add this to your providers in your app.module:

providers: [
  ... // other providers
  {
    provide: HTTP_INTERCEPTORS,
    useClass: NoCacheHeadersInterceptor,
    multi: true
  },
  ... // other providers
]

This should prevent caching issues on live sites for client machines

Adding a column to a data.frame

Easily: Your data frame is A

b <- A[,1]
b <- b==1
b <- cumsum(b)

Then you get the column b.

How to open a workbook specifying its path

Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")

Or, in a more structured way...

Sub openwb()
    Dim sPath As String, sFile As String
    Dim wb As Workbook

    sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
    sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"

    Set wb = Workbooks.Open(sFile)
End Sub

Differences between ConstraintLayout and RelativeLayout

Relative Layout and Constraint Layout equivalent properties

Relative Layout and Constraint Layout equivalent properties

(1) Relative Layout:

android:layout_centerInParent="true"    

(1) Constraint Layout equivalent :

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"

(2) Relative Layout:

android:layout_centerHorizontal="true"

(2) Constraint Layout equivalent:

app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintEnd_toEndOf="parent"

(3) Relative Layout:

android:layout_centerVertical="true"    

(3) Constraint Layout equivalent:

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"

(4) Relative Layout:

android:layout_alignParentLeft="true"   

(4) Constraint Layout equivalent:

app:layout_constraintLeft_toLeftOf="parent"

(5) Relative Layout:

android:layout_alignParentStart="true"

(5) Constraint Layout equivalent:

app:layout_constraintStart_toStartOf="parent"

(6) Relative Layout:

android:layout_alignParentRight="true"

(6) Constraint Layout equivalent:

app:layout_constraintRight_toRightOf="parent"

(7) Relative Layout:

android:layout_alignParentEnd="true"    

(7) Constraint Layout equivalent:

app:layout_constraintEnd_toEndOf="parent"

(8) Relative Layout:

android:layout_alignParentTop="true"

(8) Constraint Layout equivalent:

app:layout_constraintTop_toTopOf="parent"

(9) Relative Layout:

android:layout_alignParentBottom="true" 

(9) Constraint Layout equivalent:

app:layout_constraintBottom_toBottomOf="parent"

(10) Relative Layout:

android:layout_alignStart="@id/view"

(10) Constraint Layout equivalent:

app:layout_constraintStart_toStartOf="@id/view"

(11) Relative Layout:

android:layout_alignLeft="@id/view" 

(11) Constraint Layout equivalent:

app:layout_constraintLeft_toLeftOf="@id/view"

(12) Relative Layout:

android:layout_alignEnd="@id/view"  

(12) Constraint Layout equivalent:

app:layout_constraintEnd_toEndOf="@id/view"

(13) Relative Layout:

android:layout_alignRight="@id/view"

(13) Constraint Layout equivalent:

app:layout_constraintRight_toRightOf="@id/view"

(14) Relative Layout:

android:layout_alignTop="@id/view"  

(14) Constraint Layout equivalent:

app:layout_constraintTop_toTopOf="@id/view"

(15) Relative Layout:

android:layout_alignBaseline="@id/view" 

(15) Constraint Layout equivalent:

app:layout_constraintBaseline_toBaselineOf="@id/view"

(16) Relative Layout:

android:layout_alignBottom="@id/view"

(16) Constraint Layout equivalent:

app:layout_constraintBottom_toBottomOf="@id/view"

(17) Relative Layout:

android:layout_toStartOf="@id/view"

(17) Constraint Layout equivalent:

app:layout_constraintEnd_toStartOf="@id/view"

(18) Relative Layout:

android:layout_toLeftOf="@id/view"  

(18) Constraint Layout equivalent:

app:layout_constraintRight_toLeftOf="@id/view"

(19) Relative Layout:

android:layout_toEndOf="@id/view"

(19) Constraint Layout equivalent:

app:layout_constraintStart_toEndOf="@id/view"

(20) Relative Layout:

android:layout_toRightOf="@id/view"

(20) Constraint Layout equivalent:

app:layout_constraintLeft_toRightOf="@id/view"

(21) Relative Layout:

android:layout_above="@id/view" 

(21) Constraint Layout equivalent:

app:layout_constraintBottom_toTopOf="@id/view"

(22) Relative Layout:

android:layout_below="@id/view" 

(22) Constraint Layout equivalent:

app:layout_constraintTop_toBottomOf="@id/view"

What is the difference between Integrated Security = True and Integrated Security = SSPI?

Note that connection strings are specific to what and how you are connecting to data. These are connecting to the same database but the first is using .NET Framework Data Provider for SQL Server. Integrated Security=True will not work for OleDb.

  • Data Source=.;Initial Catalog=aspnetdb;Integrated Security=True
  • Provider=SQLOLEDB;Data Source=.;Integrated Security=SSPI;Initial Catalog=aspnetdb

When in doubt use the Visual Studio Server Explorer Data Connections.

Under what conditions is a JSESSIONID created?

Beware if your page is including other .jsp or .jspf (fragment)! If you don't set

<%@ page session="false" %>

on them as well, the parent page will end up starting a new session and setting the JSESSIONID cookie.

For .jspf pages in particular, this happens if you configured your web.xml with such a snippet:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jspf</url-pattern>
    </jsp-property-group>
</jsp-config>

in order to enable scriptlets inside them.

How do I declare an array variable in VBA?

Further to RolandTumble's answer to Cody Gray's answer, both fine answers, here is another very simple and flexible way, when you know all of the array contents at coding time - e.g. you just want to build an array that contains 1, 10, 20 and 50. This also uses variant declaration, but doesn't use ReDim. Like in Roland's answer, the enumerated count of the number of array elements need not be specifically known, but is obtainable by using uBound.

sub Demo_array()
    Dim MyArray as Variant, MyArray2 as Variant, i as Long

    MyArray = Array(1, 10, 20, 50)  'The key - the powerful Array() statement
    MyArray2 = Array("Apple", "Pear", "Orange") 'strings work too

    For i = 0 to UBound(MyArray)
        Debug.Print i, MyArray(i)
    Next i
    For i = 0 to UBound(MyArray2)
        Debug.Print i, MyArray2(i)
    Next i
End Sub

I love this more than any of the other ways to create arrays. What's great is that you can add or subtract members of the array right there in the Array statement, and nothing else need be done to code. To add Egg to your 3 element food array, you just type

, "Egg"

in the appropriate place, and you're done. Your food array now has the 4 elements, and nothing had to be modified in the Dim, and ReDim is omitted entirely.

If a 0-based array is not desired - i.e., using MyArray(0) - one solution is just to jam a 0 or "" for that first element.

Note, this might be regarded badly by some coding purists; one fair objection would be that "hard data" should be in Const statements, not code statements in routines. Another beef might be that, if you stick 36 elements into an array, you should set a const to 36, rather than code in ignorance of that. The latter objection is debatable, because it imposes a requirement to maintain the Const with 36 rather than relying on uBound. If you add a 37th element but leave the Const at 36, trouble is possible.

How to empty a Heroku database

The current, ie. 2017 way to do this is:

heroku pg:reset DATABASE

https://devcenter.heroku.com/articles/heroku-postgresql#pg-reset

How to draw lines in Java

Store the lines in some type of list. When it comes time to paint them, iterate the list and draw each one. Like this:

Screenshot

enter image description here

DrawLines

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.geom.Line2D;

import javax.swing.JOptionPane;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;

import java.util.ArrayList;
import java.util.Random;

class DrawLines {

    public static void main(String[] args) {

        Runnable r = new Runnable() {
            public void run() {
                LineComponent lineComponent = new LineComponent(400,400);
                for (int ii=0; ii<30; ii++) {
                    lineComponent.addLine();
                }
                JOptionPane.showMessageDialog(null, lineComponent);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

class LineComponent extends JComponent {

    ArrayList<Line2D.Double> lines;
    Random random;

    LineComponent(int width, int height) {
        super();
        setPreferredSize(new Dimension(width,height));
        lines = new ArrayList<Line2D.Double>();
        random = new Random();
    }

    public void addLine() {
        int width = (int)getPreferredSize().getWidth();
        int height = (int)getPreferredSize().getHeight();
        Line2D.Double line = new Line2D.Double(
            random.nextInt(width),
            random.nextInt(height),
            random.nextInt(width),
            random.nextInt(height)
            );
        lines.add(line);
        repaint();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.white);
        g.fillRect(0, 0, getWidth(), getHeight());
        Dimension d = getPreferredSize();
        g.setColor(Color.black);
        for (Line2D.Double line : lines) {
            g.drawLine(
                (int)line.getX1(),
                (int)line.getY1(),
                (int)line.getX2(),
                (int)line.getY2()
                );
        }
    }
}

MySQL select with CONCAT condition

Try:

SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
  FROM users 
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"

Your alias firstlast is not available in the where clause of the query unless you do the query as a sub-select.

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

In httpd.conf instead:

Listen *:443

you need write Listen 127.0.0.1:443 It works for me.

Uninstalling an MSI file from the command line without using msiexec

The msi file extension is mapped to msiexec (same way typing a .txt filename on a command prompt launches Notepad/default .txt file handler to display the file).

Thus typing in a filename with an .msi extension really runs msiexec with the MSI file as argument and takes the default action, install. For that reason, uninstalling requires you to invoke msiexec with uninstall switch to unstall it.

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
        <TD>
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
                Log:
            </div>
        </TD>
        <TD>
            <!-- The 2nd column -->
        </TD>
        <TD>
            <!-- The 3rd column -->
        </TD>
    </TR>
</TABLE>

file_get_contents behind a proxy?

There's a similar post here: http://techpad.co.uk/content.php?sid=137 which explains how to do it.

function file_get_contents_proxy($url,$proxy){

    // Create context stream
    $context_array = array('http'=>array('proxy'=>$proxy,'request_fulluri'=>true));
    $context = stream_context_create($context_array);

    // Use context stream with file_get_contents
    $data = file_get_contents($url,false,$context);

    // Return data via proxy
    return $data;

}

What is the difference between Trap and Interrupt?

Traps and interrupts are closely related. Traps are a type of exception, and exceptions are similar to interrupts.

Intel x86 defines two overlapping categories, vectored events (interrupts vs exceptions), and exception classes (faults vs traps vs aborts).

All of the quotes in this post are from the April 2016 version of the Intel Software Developer Manual. For the (definitive and complex) x86 perspective, I recommend reading the SDM's chapter on Interrupt and Exception handling.

Vectored Events

Vectored Events (interrupts and exceptions) cause the processor to jump into an interrupt handler after saving much of the processor's state (enough such that execution can continue from that point later).

Exceptions and interrupts have an ID, called a vector, that determines which interrupt handler the processor jumps to. Interrupt handlers are described within the Interrupt Descriptor Table.

Interrupts

Interrupts occur at random times during the execution of a program, in response to signals from hardware. System hardware uses interrupts to handle events external to the processor, such as requests to service peripheral devices. Software can also generate interrupts by executing the INT n instruction.

Exceptions

Exceptions occur when the processor detects an error condition while executing an instruction, such as division by zero. The processor detects a variety of error conditions including protection violations, page faults, and internal machine faults.

Exception Classifications

Exceptions are classified as faults, traps, or aborts depending on the way they are reported and whether the instruction that caused the exception can be restarted without loss of program or task continuity.

Summary: traps increment the instruction pointer, faults do not, and aborts 'explode'.

Trap

A trap is an exception that is reported immediately following the execution of the trapping instruction. Traps allow execution of a program or task to be continued without loss of program continuity. The return address for the trap handler points to the instruction to be executed after the trapping instruction.

Fault

A fault is an exception that can generally be corrected and that, once corrected, allows the program to be restarted with no loss of continuity. When a fault is reported, the processor restores the machine state to the state prior to the beginning of execution of the faulting instruction. The return address (saved contents of the CS and EIP registers) for the fault handler points to the faulting instruction, rather than to the instruction following the faulting instruction.

Example: A page fault is often recoverable. A piece of an application's address space may have been swapped out to disk from ram. The application will trigger a page fault when it tries to access memory that was swapped out. The kernel can pull that memory from disk to ram, and hand control back to the application. The application will continue where it left off (at the faulting instruction that was accessing swapped out memory), but this time the memory access should succeed without faulting.

An illegal-instruction fault handler that emulates floating-point or other missing instructions would have to manually increment the return address to get the trap-like behaviour it needs, after seeing if the faulting instruction was one it could handle. x86 #UD is a "fault", not a "trap". (The handler would need a pointer to the faulting instruction to figure out which instruction it was.)

Abort

An abort is an exception that does not always report the precise location of the instruction causing the exception and does not allow a restart of the program or task that caused the exception. Aborts are used to report severe errors, such as hardware errors and inconsistent or illegal values in system tables.

Edge Cases

Software invoked interrupts (triggered by the INT instruction) behave in a trap-like manner. The instruction completes before the processor saves its state and jumps to the interrupt handler.

Angular-cli from css to scss

For Angular 6 check the Official documentation

Note: For @angular/cli versions older than 6.0.0-beta.6 use ng set in place of ng config.

For existing projects

In an existing angular-cli project that was set up with the default css styles you will need to do a few things:

  1. Change the default style extension to scss

Manually change in .angular-cli.json (Angular 5.x and older) or angular.json (Angular 6+) or run:

ng config defaults.styleExt=scss

if you get an error: Value cannot be found. use the command:

ng config schematics.@schematics/angular:component.styleext scss

(*source: Angular CLI SASS options)

  1. Rename your existing .css files to .scss (i.e. styles.css and app/app.component.css)

  2. Point the CLI to find styles.scss

Manually change the file extensions in apps[0].styles in angular.json

  1. Point the components to find your new style files

Change the styleUrls in your components to match your new file names

For future projects

As @Serginho mentioned you can set the style extension when running the ng new command

ng new your-project-name --style=scss

If you want to set the default for all projects you create in the future run the following command:

ng config --global defaults.styleExt=scss

Get full path of the files in PowerShell

Get-ChildItem -Recurse *.txt | Format-Table FullName

That is what I used. I feel it is more understandable as it doesn't contain any loop syntax.

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

http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html covers catching multiple exceptions in the same block.

 try {
     // your code
} catch (Exception1 | Exception2 ex) {
     // Handle 2 exceptions in Java 7
}

I'm making study cards, and this thread was helpful, just wanted to put in my two cents.

jQuery - Create hidden form element on the fly

if you want to add more attributes just do like:

$('<input>').attr('type','hidden').attr('name','foo[]').attr('value','bar').appendTo('form');

Or

$('<input>').attr({
    type: 'hidden',
    id: 'foo',
    name: 'foo[]',
    value: 'bar'
}).appendTo('form');

Find and extract a number from a string

Did the reverse of one of the answers to this question: How to remove numbers from string using Regex.Replace?

// Pull out only the numbers from the string using LINQ

var numbersFromString = new String(input.Where(x => x >= '0' && x <= '9').ToArray());

var numericVal = Int32.Parse(numbersFromString);

python capitalize first letter only

a one-liner: ' '.join(sub[:1].upper() + sub[1:] for sub in text.split(' '))

Render a string in HTML and preserve spaces and linebreaks

You would want to replace all spaces with &nbsp; (non-breaking space) and all new lines \n with <br> (line break in html). This should achieve the result you're looking for.

body = body.replace(' ', '&nbsp;').replace('\n', '<br>');

Something of that nature.

NTFS performance and large volumes of files and directories

Here's some advice from someone with an environment where we have folders containing tens of millions of files.

  1. A folder stores the index information (links to child files & child folder) in an index file. This file will get very large when you have a lot of children. Note that it doesn't distinguish between a child that's a folder and a child that's a file. The only difference really is the content of that child is either the child's folder index or the child's file data. Note: I am simplifying this somewhat but this gets the point across.
  2. The index file will get fragmented. When it gets too fragmented, you will be unable to add files to that folder. This is because there is a limit on the # of fragments that's allowed. It's by design. I've confirmed it with Microsoft in a support incident call. So although the theoretical limit to the number of files that you can have in a folder is several billions, good luck when you start hitting tens of million of files as you will hit the fragmentation limitation first.
  3. It's not all bad however. You can use the tool: contig.exe to defragment this index. It will not reduce the size of the index (which can reach up to several Gigs for tens of million of files) but you can reduce the # of fragments. Note: The Disk Defragment tool will NOT defrag the folder's index. It will defrag file data. Only the contig.exe tool will defrag the index. FYI: You can also use that to defrag an individual file's data.
  4. If you DO defrag, don't wait until you hit the max # of fragment limit. I have a folder where I cannot defrag because I've waited until it's too late. My next test is to try to move some files out of that folder into another folder to see if I could defrag it then. If this fails, then what I would have to do is 1) create a new folder. 2) move a batch of files to the new folder. 3) defrag the new folder. repeat #2 & #3 until this is done and then 4) remove the old folder and rename the new folder to match the old.

To answer your question more directly: If you're looking at 100K entries, no worries. Go knock yourself out. If you're looking at tens of millions of entries, then either:

a) Make plans to sub-divide them into sub-folders (e.g., lets say you have 100M files. It's better to store them in 1000 folders so that you only have 100,000 files per folder than to store them into 1 big folder. This will create 1000 folder indices instead of a single big one that's more likely to hit the max # of fragments limit or

b) Make plans to run contig.exe on a regular basis to keep your big folder's index defragmented.

Read below only if you're bored.

The actual limit isn't on the # of fragment, but on the number of records of the data segment that stores the pointers to the fragment.

So what you have is a data segment that stores pointers to the fragments of the directory data. The directory data stores information about the sub-directories & sub-files that the directory supposedly stored. Actually, a directory doesn't "store" anything. It's just a tracking and presentation feature that presents the illusion of hierarchy to the user since the storage medium itself is linear.

Meaning of "n:m" and "1:n" in database design

Imagine you have have a Book model and a Page model,

1:N means:
One book can have **many** pages. One page can only be in **one** book.


N:N means:
One book can have **many** pages. And one page can be in **many** books.

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

Disabling of EditText in Android

This works for me:

android:focusable="false"

Converting String to "Character" array in Java

Converting String to Character Array and then Converting Character array back to String

   //Givent String
   String given = "asdcbsdcagfsdbgdfanfghbsfdab";

   //Converting String to Character Array(It's an inbuild method of a String)
   char[] characterArray = given.toCharArray();
   //returns = [a, s, d, c, b, s, d, c, a, g, f, s, d, b, g, d, f, a, n, f, g, h, b, s, f, d, a, b]

//ONE WAY : Converting back Character array to String

  int length = Arrays.toString(characterArray).replaceAll("[, ]","").length();

  //First Way to get the string back
  Arrays.toString(characterArray).replaceAll("[, ]","").substring(1,length-1)
  //returns asdcbsdcagfsdbgdfanfghbsfdab
  or 
  // Second way to get the string back
  Arrays.toString(characterArray).replaceAll("[, ]","").replace("[","").replace("]",""))
 //returns asdcbsdcagfsdbgdfanfghbsfdab

//Second WAY : Converting back Character array to String

String.valueOf(characterArray);

//Third WAY : Converting back Character array to String

Arrays.stream(characterArray)
           .mapToObj(i -> (char)i)
           .collect(Collectors.joining());

Converting string to Character Array

Character[] charObjectArray =
                           givenString.chars().
                               mapToObj(c -> (char)c).
                               toArray(Character[]::new);

Converting char array to Character Array

 String givenString = "MyNameIsArpan";
char[] givenchararray = givenString.toCharArray();


     String.valueOf(givenchararray).chars().mapToObj(c -> 
                         (char)c).toArray(Character[]::new);

benefits of Converting char Array to Character Array you can use the Arrays.stream funtion to get the sub array

String subStringFromCharacterArray = 

              Arrays.stream(charObjectArray,2,6).
                          map(String::valueOf).
                          collect(Collectors.joining());

How to remove specific element from an array using python

There is an alternative solution to this problem which also deals with duplicate matches.

We start with 2 lists of equal length: emails, otherarray. The objective is to remove items from both lists for each index i where emails[i] == '[email protected]'.

This can be achieved using a list comprehension and then splitting via zip:

emails = ['[email protected]', '[email protected]', '[email protected]']
otherarray = ['some', 'other', 'details']

from operator import itemgetter

res = [(i, j) for i, j in zip(emails, otherarray) if i!= '[email protected]']
emails, otherarray = map(list, map(itemgetter(0, 1), zip(*res)))

print(emails)      # ['[email protected]', '[email protected]']
print(otherarray)  # ['some', 'details']

Get each line from textarea

It works for me:

if (isset($_POST['MyTextAreaName'])){
    $array=explode( "\r\n", $_POST['MyTextAreaName'] );

now, my $array will have all the lines I need

    for ($i = 0; $i <= count($array); $i++) 
    {
        echo (trim($array[$i]) . "<br/>");
    }

(make sure to close the if block with another curly brace)

}

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

I have no idea why the other answers didn't work for me (error 500) but this works

@GetMapping("")
public String getAll() {
    List<Entity> entityList = entityManager.findAll();
    List<JSONObject> entities = new ArrayList<JSONObject>();
    for (Entity n : entityList) {
        JSONObject Entity = new JSONObject();
        entity.put("id", n.getId());
        entity.put("address", n.getAddress());
        entities.add(entity);
    }
    return entities.toString();
}

Python virtualenv questions

Normally virtualenv creates environments in the current directory. Unless you're intending to create virtual environments in C:\Windows\system32 for some reason, I would use a different directory for environments.

You shouldn't need to mess with paths: use the activate script (in <env>\Scripts) to ensure that the Python executable and path are environment-specific. Once you've done this, the command prompt changes to indicate the environment. You can then just invoke easy_install and whatever you install this way will be installed into this environment. Use deactivate to set everything back to how it was before activation.

Example:

c:\Temp>virtualenv myenv
New python executable in myenv\Scripts\python.exe
Installing setuptools..................done.
c:\Temp>myenv\Scripts\activate
(myenv) C:\Temp>deactivate
C:\Temp>

Notice how I didn't need to specify a path for deactivate - activate does that for you, so that when activated "Python" will run the Python in the virtualenv, not your system Python. (Try it - do an import sys; sys.prefix and it should print the root of your environment.)

You can just activate a new environment to switch between environments/projects, but you'll need to specify the whole path for activate so it knows which environment to activate. You shouldn't ever need to mess with PATH or PYTHONPATH explicitly.

If you use Windows Powershell then you can take advantage of a wrapper. On Linux, the virtualenvwrapper (the link points to a port of this to Powershell) makes life with virtualenv even easier.

Update: Not incorrect, exactly, but perhaps not quite in the spirit of virtualenv. You could take a different tack: for example, if you install Django and anything else you need for your site in your virtualenv, then you could work in your project directory (where you're developing your site) with the virtualenv activated. Because it was activated, your Python would find Django and anything else you'd easy_installed into the virtual environment: and because you're working in your project directory, your project files would be visible to Python, too.

Further update: You should be able to use pip, distribute instead of setuptools, and just plain python setup.py install with virtualenv. Just ensure you've activated an environment before installing something into it.

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

This is a fix for people who are not using maven. You also need to add standard.jar to your lib folder for the core tag library to work. Works for jstl version 1.1.

<%@taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>

Case-Insensitive List Search

Based on Adam Sills answer above - here's a nice clean extensions method for Contains... :)

///----------------------------------------------------------------------
/// <summary>
/// Determines whether the specified list contains the matching string value
/// </summary>
/// <param name="list">The list.</param>
/// <param name="value">The value to match.</param>
/// <param name="ignoreCase">if set to <c>true</c> the case is ignored.</param>
/// <returns>
///   <c>true</c> if the specified list contais the matching string; otherwise, <c>false</c>.
/// </returns>
///----------------------------------------------------------------------
public static bool Contains(this List<string> list, string value, bool ignoreCase = false)
{
    return ignoreCase ?
        list.Any(s => s.Equals(value, StringComparison.OrdinalIgnoreCase)) :
        list.Contains(value);
}

Change New Google Recaptcha (v2) Width

A bit late but I've got an easy workaround:

Just add this code to your "g-recaptcha" class:

width: desired_width;

border-radius: 4px;
border-right: 1px solid #d8d8d8;
overflow: hidden;

How to convert time milliseconds to hours, min, sec format in JavaScript?

How about doing this by creating a function in javascript as shown below:

_x000D_
_x000D_
function msToTime(duration) {_x000D_
  var milliseconds = parseInt((duration % 1000) / 100),_x000D_
    seconds = Math.floor((duration / 1000) % 60),_x000D_
    minutes = Math.floor((duration / (1000 * 60)) % 60),_x000D_
    hours = Math.floor((duration / (1000 * 60 * 60)) % 24);_x000D_
_x000D_
  hours = (hours < 10) ? "0" + hours : hours;_x000D_
  minutes = (minutes < 10) ? "0" + minutes : minutes;_x000D_
  seconds = (seconds < 10) ? "0" + seconds : seconds;_x000D_
_x000D_
  return hours + ":" + minutes + ":" + seconds + "." + milliseconds;_x000D_
}_x000D_
console.log(msToTime(300000))
_x000D_
_x000D_
_x000D_

From ND to 1D arrays

In [14]: b = np.reshape(a, (np.product(a.shape),))

In [15]: b
Out[15]: array([1, 2, 3, 4, 5, 6])

or, simply:

In [16]: a.flatten()
Out[16]: array([1, 2, 3, 4, 5, 6])

Python Save to file

You need to open the file again using open(), but this time passing 'w' to indicate that you want to write to the file. I would also recommend using with to ensure that the file will be closed when you are finished writing to it.

with open('Failed.txt', 'w') as f:
    for ip in [k for k, v in ips.iteritems() if v >=5]:
        f.write(ip)

Naturally you may want to include newlines or other formatting in your output, but the basics are as above.

The same issue with closing your file applies to the reading code. That should look like this:

ips = {}
with open('today','r') as myFile:
    for line in myFile:
        parts = line.split(' ')
        if parts[1] == 'Failure':
            if parts[0] in ips:
                ips[pars[0]] += 1
            else:
                ips[parts[0]] = 0

Is 'bool' a basic datatype in C++?

yes, it was introduced in 1993.

for further reference: Boolean Datatype

Function to return only alpha-numeric characters from string?

Rather than preg_replace, you could always use PHP's filter functions using the filter_var() function with FILTER_SANITIZE_STRING.

Order Bars in ggplot2 bar graph

I agree with zach that counting within dplyr is the best solution. I've found this to be the shortest version:

dplyr::count(theTable, Position) %>%
          arrange(-n) %>%
          mutate(Position = factor(Position, Position)) %>%
          ggplot(aes(x=Position, y=n)) + geom_bar(stat="identity")

This will also be significantly faster than reordering the factor levels beforehand since the count is done in dplyr not in ggplot or using table.

Android Recyclerview vs ListView with Viewholder

If you use RecycleView, first you need more efford to setup. You need to give more time to setup simple Item onclick, border, touch event and other simple thing. But end product will be perfect.

So decision is yours. I suggest, if you design simple app like phonebook loading, where simple click of item is enough, you can implement listview. But if you design like social media home page with unlimited scrolling. Several different decoration between item, much control of individual item than use recycle view.

Build android release apk on Phonegap 3.x CLI

I know this question asks about Phonegap 3.X specifically, but just for reference any Phonegap version above 4.0.0 uses Gradle instead of Ant to build by default. To use Ant instead of Gradle you can add this to your config.xml:

<preference name="android-build-tool" value="ant" />

When using Gradle the keystore signing information now needs to go into a new location (as outlined in this post). Create new file called 'release-signing.properties' in the same folder as "build.gradle" file and put inside the following content:

storeFile=..\\..\\some-keystore.keystore
storeType=jks
keyAlias=some-key
// if you don't want to enter the password at every build, you can store it with this
keyPassword=your-key-password
storePassword=your-store-password

get an element's id

This would work too:

document.getElementsByTagName('p')[0].id

(If element where the 1st paragraph in your document)

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

SOAP 1.1 uses namespace http://schemas.xmlsoap.org/wsdl/soap/

SOAP 1.2 uses namespace http://schemas.xmlsoap.org/wsdl/soap12/

The wsdl is able to define operations under soap 1.1 and soap 1.2 at the same time in the same wsdl. Thats useful if you need to evolve your wsdl to support new functionality that requires soap 1.2 (eg. MTOM), in this case you dont need to create a new service but just evolve the original one.

Spring Data JPA Update @Query not updating?

The EntityManager doesn't flush change automatically by default. You should use the following option with your statement of query:

@Modifying(clearAutomatically = true)
@Query("update RssFeedEntry feedEntry set feedEntry.read =:isRead where feedEntry.id =:entryId")
void markEntryAsRead(@Param("entryId") Long rssFeedEntryId, @Param("isRead") boolean isRead);

Current user in Magento?

I don't know this off the top of my head, but look in the file which shows the user's name, etc in the header of the page after the user has logged in. It might help if you turned on template hints (see this tutorial.

When you find the line such as "Hello <? //code for showing username?>", just copy that line and show it where you need to

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

How to rotate a 3D object on axis three.js?

Since release r59, three.js provides those three functions to rotate a object around object axis.

object.rotateX(angle);
object.rotateY(angle);
object.rotateZ(angle);

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

This is a bug in pycharm. PyCharm seems to be expecting the referenced module to be included in an __all__ = [] statement.

For proper coding etiquette, should you include the __all__ statement from your modules? ..this is actually the question we hear young Spock answering while he was being tested, to which he responded: "It is morally praiseworthy but not morally obligatory."

To get around it, you can simply disable that (extremely non-critical) (highly useful) inspection globally, or suppress it for the specific function or statement.

To do so:

  • put the caret over the erroring text ('choice', from your example above)
  • Bring up the intention menu (alt-enter by default, mine is set to alt-backspace)
  • hit the right arrow to open the submenu, and select the relevant action

PyCharm has its share of small bugs like this, but in my opinion its benefits far outweigh its drawbacks. If you'd like to try another good IDE, there's also Spyder/Spyderlib.

I know this is quite a bit after you asked your question, but I hope this helps (you, or someone else).

Edited: Originally, I thought that this was specific to checking __all__, but it looks like it's the more general 'Unresolved References' check, which can be very useful. It's probably best to use statement-level disabling of the feature, either by using the menu as mentioned above, or by specifying # noinspection PyUnresolvedReferences on the line preceding the statement.

What do multiple arrow functions mean in javascript?

The example in your question is that of a curried function which makes use of arrow function and has an implicit return for the first argument.

Arrow function lexically bind this i.e they do not have their own this argument but take the this value from the enclosing scope

An equivalent of the above code would be

const handleChange = (field) {
  return function(e) {
     e.preventDefault();
     /// Do something here
  }.bind(this);
}.bind(this);

One more thing to note about your example is that define handleChange as a const or a function. Probably you are using it as part of a class method and it uses a class fields syntax

so instead of binding the outer function directly, you would bind it in the class constructor

class Something{
    constructor(props) {
       super(props);
       this.handleChange = this.handleChange.bind(this);
    }
    handleChange(field) {
        return function(e) {
           e.preventDefault();
           // do something
        }
    }
}

Another thing to note in the example is the difference between implicit and explicit return.

const abc = (field) => field * 2;

Above is an example of implicit return ie. it takes the value field as argument and returns the result field*2 which explicitly specifying the function to return

For an explicit return you would explicitly tell the method to return the value

const abc = () => { return field*2; }

Another thing to note about arrow functions is that they do not have their own arguments but inherit that from the parents scope as well.

For example if you just define an arrow function like

const handleChange = () => {
   console.log(arguments) // would give an error on running since arguments in undefined
}

As an alternative arrow functions provide the rest parameters that you can use

const handleChange = (...args) => {
   console.log(args);
}

How do you redirect to a page using the POST verb?

HTTP doesn't support redirection to a page using POST. When you redirect somewhere, the HTTP "Location" header tells the browser where to go, and the browser makes a GET request for that page. You'll probably have to just write the code for your page to accept GET requests as well as POST requests.

SQL Server - after insert trigger - update another column in the same table

Yes, it will recursively call your trigger unless you turn the recursive triggers setting off:

ALTER DATABASE db_name SET RECURSIVE_TRIGGERS OFF 

MSDN has a good explanation of the behavior at http://msdn.microsoft.com/en-us/library/aa258254(SQL.80).aspx under the Recursive Triggers heading.

Creating a DateTime in a specific Time Zone in c#

I altered Jon Skeet answer a bit for the web with extension method. It also works on azure like a charm.

public static class DateTimeWithZone
{

private static readonly TimeZoneInfo timeZone;

static DateTimeWithZone()
{
//I added web.config <add key="CurrentTimeZoneId" value="Central Europe Standard Time" />
//You can add value directly into function.
    timeZone = TimeZoneInfo.FindSystemTimeZoneById(ConfigurationManager.AppSettings["CurrentTimeZoneId"]);
}


public static DateTime LocalTime(this DateTime t)
{
     return TimeZoneInfo.ConvertTime(t, timeZone);   
}
}

Aligning textviews on the left and right edges in Android layout

In case you want the left and right elements to wrap content but have the middle space

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    <Space
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"/>
    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
</LinearLayout>

How do I delete a local repository in git?

To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:

$ rm -rf .git

Or to delete .gitignore and .gitmodules if any (via @aragaer):

$ rm -rf .git*

Then from the same ex-repository folder, to see if hidden folder .git is still there:

$ ls -lah

If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).

To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:

defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder

Source: http://lifehacker.com/188892/show-hidden-files-in-finder.

Build a simple HTTP server in C

I have written my own that you can use. This one works has sqlite, is thread safe and is in C++ for UNIX.

You should be able to pick it apart and use the C compatible code.

http://code.google.com/p/mountain-cms/

Change background color on mouseover and remove it after mouseout

Try this , its working and simple

HTML

?????????????????????<html>
<head></head>
<body>
    <div class="forum">
        test
    </div>
</body>
</html>?????????????????????????????????????????????

Javascript

$(document).ready(function() {
    var colorOrig=$(".forum").css('background-color');
    $(".forum").hover(
    function() {
        //mouse over
        $(this).css('background', '#ff0')
    }, function() {
        //mouse out
        $(this).css('background', colorOrig)
    });
});?

css ?

.forum{
    background:#f0f;
}?

live demo

http://jsfiddle.net/caBzg/

How to insert data using wpdb

The recommended way (as noted in codex):

$wpdb->insert( $table_name, array('column_name_1'=>'hello', 'other'=> 123), array( '%s', '%d' ) );

So, you'd better to sanitize values - ALWAYS CONSIDER THE SECURITY.

Load JSON text into class object in c#

copy your Json and paste at textbox on http://json2csharp.com/ and click on Generate button,

A cs class will be generated use that cs file as below:

var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);

where RootObject is the name of the generated cs file;

How can I have two fixed width columns with one flexible column in the center?

Despite setting up dimensions for the columns, they still seem to shrink as the window shrinks.

An initial setting of a flex container is flex-shrink: 1. That's why your columns are shrinking.

It doesn't matter what width you specify (it could be width: 10000px), with flex-shrink the specified width can be ignored and flex items are prevented from overflowing the container.

I'm trying to set up a flexbox with 3 columns where the left and right columns have a fixed width...

You will need to disable shrinking. Here are some options:

.left, .right {
     width: 230px;
     flex-shrink: 0;
 }  

OR

.left, .right {
     flex-basis: 230px;
     flex-shrink: 0;
}

OR, as recommended by the spec:

.left, .right {
    flex: 0 0 230px;    /* don't grow, don't shrink, stay fixed at 230px */
}

7.2. Components of Flexibility

Authors are encouraged to control flexibility using the flex shorthand rather than with its longhand properties directly, as the shorthand correctly resets any unspecified components to accommodate common uses.

More details here: What are the differences between flex-basis and width?

An additional thing I need to do is hide the right column based on user interaction, in which case the left column would still keep its fixed width, but the center column would fill the rest of the space.

Try this:

.center { flex: 1; }

This will allow the center column to consume available space, including the space of its siblings when they are removed.

Revised Fiddle

How can I uninstall npm modules in Node.js?

# Log in as root (might be required depending on install)
su -

# List all global packages
npm ls -g --depth=0

# List all local (project) packages
npm ls -p --depth=0

# Remove all global packages
npm ls -g --depth=0 | awk -F/ '/node_modules/ && !/\/npm$/ {print $NF}' | xargs npm -g rm

# Remove all local packges
npm ls -p --depth=0 | awk -F/ '/node_modules/ && !/\/npm$/ {print $NF}' | xargs npm -p rm

# NOTE (optional): to use node with sudo you can add the bins to /usr/bin
# NOTE $PATHTONODEINSTALL is where node is installed (e.g. /usr/local/node)
sudo ln -s $PATHTONODEINSTALL/bin/node /usr/bin/node
sudo ln -s $PATHTONODEINSTALL/bin/npm /usr/bin/npm

EXTRACT() Hour in 24 Hour format

select to_char(tran_datetime,'HH24') from test;

TO_CHAR(tran_datetime,'HH24')
------------------
16      

Where can I find MySQL logs in phpMyAdmin?

If you are using XAMPP as your server, you'll find a logs directory as a child of the XAMPP directory. If you have not tried XAMPP, which runs on any system (Windows, Mac OS & Linux) find more here: http://www.apachefriends.org/en/xampp.html

Convert CString to const char*

There is an explicit cast on CString to LPCTSTR, so you can do (provided unicode is not specified):

CString str;
// ....
const char* cstr = (LPCTSTR)str;

How to resize image (Bitmap) to a given size?

The other answers are correct as to "how" to resize them, but I would also thrown in the recommendation to just grab the resolution you are interested in, to begin with. Most Android devices offer a range of resolutions and you should pick one that gives you a file size that you're comfortable with. The biggest reason for this is that the native Android scaling algorithm (as detailed by Jin35 and Padma Kumar) produces pretty crappy results. It's not going to give you Photoshop quality resizing, even downscaling (to say nothing of upscaling, which I know you're not asking about, but that's just a non-starter).

So, you should try their solution and if you're happy with the outcome, great. But if not, I'd write a function that offers a range of width that you're happy with, and looks for that dimension (or whatever's closest) in the device's available picture size array and just set it and use it.