Programs & Examples On #Xap

XAP is an XML-based declarative framework for building, deploying and maintaining rich, interactive Ajax powered web applications.

Getting Image from API in Angular 4/5+?

angular 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

I found it, I was trying to compile my app which is using facebook sdk. I was made that like augst 2016. When I try to open it today i got same error. I had that line in my gradle " compile 'com.facebook.android:facebook-android-sdk:4.+' " and I went https://developers.facebook.com/docs/android/change-log-4x this page and i found the sdk version while i was running this app succesfully and it was 4.14.1 then I changed that line to " compile 'com.facebook.android:facebook-android-sdk:4.14.1' " and it worked.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Try to move:

apply plugin: 'com.google.gms.google-services'

just below:

apply plugin: 'com.android.application'

In your module Gradle file, then make sure all Google service's have the version 9.0.0.

Make sure that only this build tools is used:

classpath 'com.android.tools.build:gradle:2.1.0'

Make sure in gradle-wrapper.properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

After all above is correct, then make menu File -> Invalidate caches and restart.

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

Background info:

My IDE

Android Studio 3.1.3
Build #AI-173.4819257, built on June 4, 2018
JRE: 1.8.0_152-release-1024-b02 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 7 6.1

First solution: Import the project again and don't agree to upgrade the android gradle plug-in.

Second solution: Your files should contain these fragments.

build.gradle:

buildscript {
  repositories {
    jcenter()
    google()//this is important for gradle 4.1 and above
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:3.1.3' //this android plugin for gradle requires gradle version 4.4 and above
  }
}
allprojects {
  //...
  repositories {
    jcenter()
    google()//This was not added by update IDE-wizard-button.
    //I need this when using the latest com.android.support:appcompat-v7:25.4.0 in app/build.gradle
  }
}

Either follow the recommendation of your IDE to upgrade your gradle version to 4.4 or consider to have this in gradle/wrapper/gradle-wrapper.properties

distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

Optional change buildToolsVersion in app/build.gradle:

android {
compileSdkVersion 25
buildToolsVersion '27.0.3'

app/build.gradle: comment out the dependencies and let the build fail (automatically or trigger it)

dependencies {
//compile fileTree(dir: 'libs', include: ['*.jar'])
//compile 'com.android.support:appcompat-v7:25.1.0'
}

app/build.gradle: comment in the dependencies again. It's been advised to change them from compile to implementation, but for now it's just a warning issue.

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.1.0'
}

After project rebuilding, the import statement shouldn't be greyed-out anymore; try to invoke Ctrl+h on the class. But for some reason, the error markers on those class-referencing-statements are still present. To get rid of them, we need to hide and restore the project tree view or alternatively close and reopen the project.

Finally that's it.

Further Readings:

Update Gradle

Use the new dependency configurations

If you prefer a picture trail for my solution, you can visit my blog

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

Convert Java string to Time, NOT Date

You can use the following code for changing the String value into the time equivalent:

 String str = "08:03:10 pm";
 DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
 Date date = (Date)formatter.parse(str);

Hope this helps you.

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:

Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......

The remote server returned an error: (403) Forbidden

This probably won't help too many people, but this was my case: I was using the Jira Rest Api and was using my personal credentials (the ones I use to log into Jira). I had updated my Jira password but forgot to update them in my code. I got the 403 error, I tried updating my password in the code but still got the error.

The solution: I tried logging into Jira (from their login page) and I had to enter the text to prove I wasn't a bot. After that I tried again from the code and it worked. Takeaway: The server may have locked you out.

Crop image in android

This library: Android-Image-Cropper is very powerful to CropImages. It has 3,731 stars on github at this time.

You will crop your images with a few lines of code.

1 - Add the dependecies into buid.gradle (Module: app)

compile 'com.theartofdev.edmodo:android-image-cropper:2.7.+'

2 - Add the permissions into AndroidManifest.xml

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

3 - Add CropImageActivity into AndroidManifest.xml

<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
 android:theme="@style/Base.Theme.AppCompat"/>

4 - Start the activity with one of the cases below, depending on your requirements.

// start picker to get image for cropping and then use the image in cropping activity
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);

// start cropping activity for pre-acquired image saved on the device
CropImage.activity(imageUri)
.start(this);

// for fragment (DO NOT use `getActivity()`)
CropImage.activity()
.start(getContext(), this);

5 - Get the result in onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
    CropImage.ActivityResult result = CropImage.getActivityResult(data);
    if (resultCode == RESULT_OK) {
      Uri resultUri = result.getUri();
    } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
      Exception error = result.getError();
    }
  }
}

You can do several customizations, as set the Aspect Ratio or the shape to RECTANGLE, OVAL and a lot more.

how to save canvas as png image?

try this:

var c=document.getElementById("alpha");
var d=c.toDataURL("image/png");
var w=window.open('about:blank','image from canvas');
w.document.write("<img src='"+d+"' alt='from canvas'/>");

This shows image from canvas on new page, but if you have open popup in new tab setting it shows about:blank in address bar.

EDIT:- though window.open("<img src='"+ c.toDataURL('image/png') +"'/>") does not work in FF or Chrome, following works though rendering is somewhat different from what is shown on canvas, I think transparency is the issue:

window.open(c.toDataURL('image/png'));

Bootstrap Carousel image doesn't align properly

@Art L. Richards 's solution didn't work out. now in bootstrap.css, original code has become like this.

.carousel .item > img {
  display: block;
  line-height: 1;
}

@rnaka530 's code would break the fluid feature of bootstrap.

I don't have a good solution but I did fix it. I observed the bootstrap's carousel example very carefully http://twitter.github.com/bootstrap/javascript.html#carousel.

I find out that img width has to be larger than the grid width. In span9, width is up to 870px, so you have to prepare a image larger than 870px. If you have more container outside the img, as all the container has border or margin something, you can use image with smaller width.

Unexpected end of file error

Change the Platform of your C++ project to "x64" (or whichever platform you are targeting) instead of "Win32". This can be found in Visual Studio under Build -> Configuration Manager. Find your project in the list and change the Platform column. Don't forget to do this for all solution configurations.

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

We use Lucene regularly to index and search tens of millions of documents. Searches are quick enough, and we use incremental updates that do not take a long time. It did take us some time to get here. The strong points of Lucene are its scalability, a large range of features and an active community of developers. Using bare Lucene requires programming in Java.

If you are starting afresh, the tool for you in the Lucene family is Solr, which is much easier to set up than bare Lucene, and has almost all of Lucene's power. It can import database documents easily. Solr are written in Java, so any modification of Solr requires Java knowledge, but you can do a lot just by tweaking configuration files.

I have also heard good things about Sphinx, especially in conjunction with a MySQL database. Have not used it, though.

IMO, you should choose according to:

  • The required functionality - e.g. do you need a French stemmer? Lucene and Solr have one, I do not know about the others.
  • Proficiency in the implementation language - Do not touch Java Lucene if you do not know Java. You may need C++ to do stuff with Sphinx. Lucene has also been ported into other languages. This is mostly important if you want to extend the search engine.
  • Ease of experimentation - I believe Solr is best in this aspect.
  • Interfacing with other software - Sphinx has a good interface with MySQL. Solr supports ruby, XML and JSON interfaces as a RESTful server. Lucene only gives you programmatic access through Java. Compass and Hibernate Search are wrappers of Lucene that integrate it into larger frameworks.

How to configure a HTTP proxy for svn

Most *nixen understand the environment variable 'http_proxy' when performing web requests.

export http_proxy=http://my-proxy-server.com:8080/
svn co http://code.sixapart.com/svn/perlball/

should do the trick. Most http libraries check for this (and other) environment variables.

How to 'insert if not exists' in MySQL?

Any simple constraint should do the job, if an exception is acceptable. Examples :

  • primary key if not surrogate
  • unique constraint on a column
  • multi-column unique constraint

Sorry is this seems deceptively simple. I know it looks bad confronted to the link you share with us. ;-(

But I neverleless give this answer, because it seem to fill your need. (If not, it may trigger your updating your requirements, which would be "a Good Thing"(TM) also).

Edited: If an insert would break the database unique constraint, an exception is throw at the database level, relayed by the driver. It will certainly stop your script, with a failure. It must be possible in PHP to adress that case ...

how to use math.pi in java

You're missing the multiplication operator. Also, you want to do 4/3 in floating point, not integer math.

volume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
           ^^      ^

Using <style> tags in the <body> with other HTML

As others have already mentioned, HTML 4 requires the <style> tag to be placed in the <head> section (even though most browsers allow <style> tags within the body).

However, HTML 5 includes the scoped attribute (see update below), which allows you to create style sheets that are scoped within the parent element of the <style> tag. This also enables you to place <style> tags within the <body> element:

<!DOCTYPE html>
<html>
<head></head>
<body>

<div id="scoped-content">
    <style type="text/css" scoped>
        h1 { color: red; } 
    </style>

    <h1>Hello</h1>
</div>

    <h1>
      World
    </h1>

</body>
</html>

If you render the above code in an HTML-5 enabled browser that supports scoped, you will see the limited scope of the style sheet.

There's just one major caveat...

At the time I'm writing this answer (May, 2013) almost no mainstream browser currently supports the scoped attribute. (Although apparently developer builds of Chromium support it.)

HOWEVER, there is an interesting implication of the scoped attribute that pertains to this question. It means that future browsers are mandated via the standard to allow <style> elements within the <body> (as long as the <style> elements are scoped.)

So, given that:

  • Almost every existing browser currently ignores the scoped attribute
  • Almost every existing browser currently allows <style> tags within the <body>
  • Future implementations will be required to allow (scoped) <style> tags within the <body>

...then there is literally no harm * in placing <style> tags within the body, as long as you future proof them with a scoped attribute. The only problem is that current browsers won't actually limit the scope of the stylesheet - they'll apply it to the whole document. But the point is that, for all practical purposes, you can include <style> tags within the <body> provided that you:

  • Future-proof your HTML by including the scoped attribute
  • Understand that as of now, the stylesheet within the <body> will not actually be scoped (because no mainstream browser support exists yet)


* except of course, for pissing off HTML validators...


Finally, regarding the common (but subjective) claim that embedding CSS within HTML is poor practice, it should be noted that the whole point of the scoped attribute is to accommodate typical modern development frameworks that allow developers to import chunks of HTML as modules or syndicated content. It is very convenient to have embedded CSS that only applies to a particular chunk of HTML, in order to develop encapsulated, modular components with specific stylings.


Update as of Feb 2019, according to the Mozilla documentation, the scoped attribute is deprecated. Chrome stopped supporting it in version 36 (2014) and Firefox in version 62 (2018). In both cases, the feature had to be explicitly enabled by the user in the browsers' settings. No other major browser ever supported it.

CSS /JS to prevent dragging of ghost image?

This work for me, i use some lightbox scripts

_x000D_
_x000D_
.nodragglement {_x000D_
    transform: translate(0px, 0px)!important;_x000D_
}
_x000D_
_x000D_
_x000D_

pandas read_csv index_col=None not working with delimiters at the end of each line

Quick Answer

Use index_col=False instead of index_col=None when you have delimiters at the end of each line to turn off index column inference and discard the last column.

More Detail

After looking at the data, there is a comma at the end of each line. And this quote (the documentation has been edited since the time this post was created):

index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index.

from the documentation shows that pandas believes you have n headers and n+1 data columns and is treating the first column as the index.


EDIT 10/20/2014 - More information

I found another valuable entry that is specifically about trailing limiters and how to simply ignore them:

If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names: ...

Ordinarily, you can achieve this behavior using the index_col option.

There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False: ...

Iterating over a 2 dimensional python list

>>> [el[0] if i < len(mylist) else el[1] for i,el in enumerate(mylist + mylist)]
['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']

do <something> N times (declarative syntax)

Given a function something:

function something() { console.log("did something") }

And a new method times added to the Array prototype:

Array.prototype.times = function(f){
  for(v of this) 
    for(var _ of Array(v))
      f();
}

This code:

[1,2,3].times(something)

Outputs this:

did something
did something
did something
did something
did something
did something

Which I think answers your updated question (5 years later) but I wonder how useful it is to have this work on an array? Wouldn't the effect be the same as calling [6].times(something), which in turn could be written as:

for(_ of Array(6)) something();

(although the use of _ as a junk variable will probably clobber lodash or underscore if you're using it)

What are the different NameID format used for?

It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:

  1. unspecified
  2. emailAddress – e.g. [email protected]
  3. X509SubjectName – e.g. CN=john,O=Company Ltd.,C=US
  4. WindowsDomainQualifiedName – e.g. CompanyDomain\John
  5. kerberos– e.g. john@realm
  6. entity – this one in used to identify entities that provide SAML-based services and looks like a URI
  7. persistent – this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.
  8. transient – opaque identifier which should be treated as temporary.

Is there any way to return HTML in a PHP function? (without building the return value as a string)

If you don't want to have to rely on a third party tool you can use this technique:

function TestBlockHTML($replStr){
  $template = 
   '<html>
     <body>
       <h1>$str</h1>
     </body>
   </html>';
 return strtr($template, array( '$str' => $replStr));
}

Refresh DataGridView when updating data source

Try this Code

List itemStates = new List();

for (int i = 0; i < 10; i++)
{ 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = itemStates;
    dataGridView1.DataBind();
    System.Threading.Thread.Sleep(500);
}

Maintain/Save/Restore scroll position when returning to a ListView

For some looking for a solution to this problem, the root of the issue may be where you are setting your list views adapter. After you set the adapter on the listview, it resets the scroll position. Just something to consider. I moved setting the adapter into my onCreateView after we grab the reference to the listview, and it solved the problem for me. =)

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

I had the same problem and I fixed it just by setting this: <item name="android:windowIsFloating">false</item> in styles.xml

How to edit default dark theme for Visual Studio Code?

The docs now have a whole section about this.

Basically, use npm to install yo, and run the command yo code and you'll get a little text-based wizard -- one of whose options will be to create and edit a copy of the default dark scheme.

PANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value

ok i can run android from cordova, i changed ANDROID_HOME to,

export ANDROID_HOME=/usr/local/opt/android-sdk

Cannot find module cv2 when using OpenCV

I have come accross same as this problem i installed cv2 by

pip install cv2

However when i import cv2 module it displayed no module named cv2 error.
Then i searched and find cv2.pyd files in my computer and i copy and paste to site-packages directory

C:\Python27\Lib\site-packages

then i closed and reopened existing application, it worked.

EDIT I will tell how to install cv2 correctly.

1. Firstly install numpy on your computer by

pip install numpy


2. Download opencv from internet (almost 266 mb).
I download opencv-2.4.12.exe for python 2.7. Then install this opencv-2.4.12.exe file.
I extracted to C:\Users\harun\Downloads to this folder.
After installation go look for cv2.py into the folders.
For me

C:\Users\harun\Downloads\opencv\build\python\2.7\x64

in this folder take thecv2.pyd and copy it in to the

C:\Python27\Lib\site-packages

now you can able to use cv2 in you python scripts.

Convert integer to hex and hex to integer

Given:

declare @hexStr varchar(16), @intVal int

IntToHexStr:

select @hexStr = convert(varbinary, @intVal, 1)

HexStrToInt:

declare
    @query varchar(100),
    @parameters varchar(50)

select
    @query = 'select @result = convert(int,' + @hb + ')',
    @parameters = '@result int output'

exec master.dbo.Sp_executesql @query, @parameters, @intVal output

How do I check whether a file exists without exceptions?

Check file or directory exists

You can follow these three ways:

Note1: The os.path.isfile used only for files

import os.path
os.path.isfile(filename) # True if file exists
os.path.isfile(dirname) # False if directory exists

Note2: The os.path.exists used for both files and directories

import os.path
os.path.exists(filename) # True if file exists
os.path.exists(dirname) #True if directory exists

The pathlib.Path method (included in Python 3+, installable with pip for Python 2)

from pathlib import Path
Path(filename).exists()

What is the difference between baud rate and bit rate?

Replies here are misleading. Saying true, but no one tell that for UART a symbol is not a single character but a single bit and this way the question was tagged.

For example 115200/8n1 is 11520 bytes per second as a single ASCII character is a 1 start bit plus 8 data bit plus 1 stop bit.

Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

EF is looking for a table named dbo.BaseCs. Might be an entity name pluralizing issue. Check out this link.

EDIT: Updated link.

Rails 4 LIKE query - ActiveRecord adds quotes

.find(:all, where: "value LIKE product_%", params: { limit: 20, page: 1 })

Run PowerShell command from command prompt (no ps1 script)

Here is the only answer that managed to work for my problem, got it figured out with the help of this webpage (nice reference).

powershell -command "& {&'some-command' someParam}"

Also, here is a neat way to do multiple commands:

powershell -command "& {&'some-command' someParam}"; "& {&'some-command' -SpecificArg someParam}"

For example, this is how I ran my 2 commands:

powershell -command "& {&'Import-Module' AppLocker}"; "& {&'Set-AppLockerPolicy' -XmlPolicy myXmlFilePath.xml}"

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

There are 4 ways that I know of:

  • import the certificate to your app and use it for the connection
  • disable certificate checking
  • add your certificate to the trusted system certificates in Android
  • buy a verified certificate that is accepted by Android

I assume you don't want to pay for this, so I think the most elegant solution is the first one, what can be accomplished this way:

http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html

How do I restart my C# WinForm Application?

If you are in main app form try to use

System.Diagnostics.Process.Start( Application.ExecutablePath); // to start new instance of application
this.Close(); //to turn off current app

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

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

Named placeholders in string formatting

I created also a util/helper class (using jdk 8) which can format a string an replaces occurrences of variables.

For this purpose I used the Matchers "appendReplacement" method which does all the substitution and loops only over the affected parts of a format string.

The helper class isn't currently well javadoc documented. I will changes this in the future ;) Anyway I commented the most important lines (I hope).

    public class FormatHelper {

    //Prefix and suffix for the enclosing variable name in the format string.
    //Replace the default values with any you need.
    public static final String DEFAULT_PREFIX = "${";
    public static final String DEFAULT_SUFFIX = "}";

    //Define dynamic function what happens if a key is not found.
    //Replace the defualt exception with any "unchecked" exception type you need or any other behavior.
    public static final BiFunction<String, String, String> DEFAULT_NO_KEY_FUNCTION =
            (fullMatch, variableName) -> {
                throw new RuntimeException(String.format("Key: %s for variable %s not found.",
                                                         variableName,
                                                         fullMatch));
            };
    private final Pattern variablePattern;
    private final Map<String, String> values;
    private final BiFunction<String, String, String> noKeyFunction;
    private final String prefix;
    private final String suffix;

    public FormatHelper(Map<String, String> values) {
        this(DEFAULT_NO_KEY_FUNCTION, values);
    }

    public FormatHelper(
            BiFunction<String, String, String> noKeyFunction, Map<String, String> values) {
        this(DEFAULT_PREFIX, DEFAULT_SUFFIX, noKeyFunction, values);
    }

    public FormatHelper(String prefix, String suffix, Map<String, String> values) {
        this(prefix, suffix, DEFAULT_NO_KEY_FUNCTION, values);
    }

    public FormatHelper(
            String prefix,
            String suffix,
            BiFunction<String, String, String> noKeyFunction,
            Map<String, String> values) {
        this.prefix = prefix;
        this.suffix = suffix;
        this.values = values;
        this.noKeyFunction = noKeyFunction;

        //Create the Pattern and quote the prefix and suffix so that the regex don't interpret special chars.
        //The variable name is a "\w+" in an extra capture group.
        variablePattern = Pattern.compile(Pattern.quote(prefix) + "(\\w+)" + Pattern.quote(suffix));
    }

    public static String format(CharSequence format, Map<String, String> values) {
        return new FormatHelper(values).format(format);
    }

    public static String format(
            CharSequence format,
            BiFunction<String, String, String> noKeyFunction,
            Map<String, String> values) {
        return new FormatHelper(noKeyFunction, values).format(format);
    }

    public static String format(
            String prefix, String suffix, CharSequence format, Map<String, String> values) {
        return new FormatHelper(prefix, suffix, values).format(format);
    }

    public static String format(
            String prefix,
            String suffix,
            BiFunction<String, String, String> noKeyFunction,
            CharSequence format,
            Map<String, String> values) {
        return new FormatHelper(prefix, suffix, noKeyFunction, values).format(format);
    }

    public String format(CharSequence format) {

        //Create matcher based on the init pattern for variable names.
        Matcher matcher = variablePattern.matcher(format);

        //This buffer will hold all parts of the formatted finished string.
        StringBuffer formatBuffer = new StringBuffer();

        //loop while the matcher finds another variable (prefix -> name <- suffix) match
        while (matcher.find()) {

            //The root capture group with the full match e.g ${variableName}
            String fullMatch = matcher.group();

            //The capture group for the variable name resulting from "(\w+)" e.g. variableName
            String variableName = matcher.group(1);

            //Get the value in our Map so the Key is the used variable name in our "format" string. The associated value will replace the variable.
            //If key is missing (absent) call the noKeyFunction with parameters "fullMatch" and "variableName" else return the value.
            String value = values.computeIfAbsent(variableName, key -> noKeyFunction.apply(fullMatch, key));

            //Escape the Map value because the "appendReplacement" method interprets the $ and \ as special chars.
            String escapedValue = Matcher.quoteReplacement(value);

            //The "appendReplacement" method replaces the current "full" match (e.g. ${variableName}) with the value from the "values" Map.
            //The replaced part of the "format" string is appended to the StringBuffer "formatBuffer".
            matcher.appendReplacement(formatBuffer, escapedValue);
        }

        //The "appendTail" method appends the last part of the "format" String which has no regex match.
        //That means if e.g. our "format" string has no matches the whole untouched "format" string is appended to the StringBuffer "formatBuffer".
        //Further more the method return the buffer.
        return matcher.appendTail(formatBuffer)
                      .toString();
    }

    public String getPrefix() {
        return prefix;
    }

    public String getSuffix() {
        return suffix;
    }

    public Map<String, String> getValues() {
        return values;
    }
}

You can create a class instance for a specific Map with values (or suffix prefix or noKeyFunction) like:

    Map<String, String> values = new HashMap<>();
    values.put("firstName", "Peter");
    values.put("lastName", "Parker");


    FormatHelper formatHelper = new FormatHelper(values);
    formatHelper.format("${firstName} ${lastName} is Spiderman!");
    // Result: "Peter Parker is Spiderman!"
    // Next format:
    formatHelper.format("Does ${firstName} ${lastName} works as photographer?");
    //Result: "Does Peter Parker works as photographer?"

Further more you can define what happens if a key in the values Map is missing (works in both ways e.g. wrong variable name in format string or missing key in Map). The default behavior is an thrown unchecked exception (unchecked because I use the default jdk8 Function which cant handle checked exceptions) like:

    Map<String, String> map = new HashMap<>();
    map.put("firstName", "Peter");
    map.put("lastName", "Parker");


    FormatHelper formatHelper = new FormatHelper(map);
    formatHelper.format("${missingName} ${lastName} is Spiderman!");
    //Result: RuntimeException: Key: missingName for variable ${missingName} not found.

You can define a custom behavior in the constructor call like:

Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");


FormatHelper formatHelper = new FormatHelper(fullMatch, variableName) -> variableName.equals("missingName") ? "John": "SOMETHING_WRONG", values);
formatHelper.format("${missingName} ${lastName} is Spiderman!");
// Result: "John Parker is Spiderman!"

or delegate it back to the default no key behavior:

...
    FormatHelper formatHelper = new FormatHelper((fullMatch, variableName) ->   variableName.equals("missingName") ? "John" :
            FormatHelper.DEFAULT_NO_KEY_FUNCTION.apply(fullMatch,
                                                       variableName), map);
...

For better handling there are also static method representations like:

Map<String, String> values = new HashMap<>();
values.put("firstName", "Peter");
values.put("lastName", "Parker");

FormatHelper.format("${firstName} ${lastName} is Spiderman!", map);
// Result: "Peter Parker is Spiderman!"

Pass by Reference / Value in C++

I think much confusion is generated by not communicating what is meant by passed by reference. When some people say pass by reference they usually mean not the argument itself, but rather the object being referenced. Some other say that pass by reference means that the object can't be changed in the callee. Example:

struct Object {
    int i;
};

void sample(Object* o) { // 1
    o->i++;
}

void sample(Object const& o) { // 2
    // nothing useful here :)
}

void sample(Object & o) { // 3
    o.i++;
}

void sample1(Object o) { // 4
    o.i++;
}

int main() {
    Object obj = { 10 };
    Object const obj_c = { 10 };

    sample(&obj); // calls 1
    sample(obj) // calls 3
    sample(obj_c); // calls 2
    sample1(obj); // calls 4
}

Some people would claim that 1 and 3 are pass by reference, while 2 would be pass by value. Another group of people say all but the last is pass by reference, because the object itself is not copied.

I would like to draw a definition of that here what i claim to be pass by reference. A general overview over it can be found here: Difference between pass by reference and pass by value. The first and last are pass by value, and the middle two are pass by reference:

    sample(&obj);
       // yields a `Object*`. Passes a *pointer* to the object by value. 
       // The caller can change the pointer (the parameter), but that 
       // won't change the temporary pointer created on the call side (the argument). 

    sample(obj)
       // passes the object by *reference*. It denotes the object itself. The callee
       // has got a reference parameter.

    sample(obj_c);
       // also passes *by reference*. the reference parameter references the
       // same object like the argument expression. 

    sample1(obj);
       // pass by value. The parameter object denotes a different object than the 
       // one passed in.

I vote for the following definition:

An argument (1.3.1) is passed by reference if and only if the corresponding parameter of the function that's called has reference type and the reference parameter binds directly to the argument expression (8.5.3/4). In all other cases, we have to do with pass by value.

That means that the following is pass by value:

void f1(Object const& o);
f1(Object()); // 1

void f2(int const& i);
f2(42); // 2

void f3(Object o);
f3(Object());     // 3
Object o1; f3(o1); // 4

void f4(Object *o);
Object o1; f4(&o1); // 5

1 is pass by value, because it's not directly bound. The implementation may copy the temporary and then bind that temporary to the reference. 2 is pass by value, because the implementation initializes a temporary of the literal and then binds to the reference. 3 is pass by value, because the parameter has not reference type. 4 is pass by value for the same reason. 5 is pass by value because the parameter has not got reference type. The following cases are pass by reference (by the rules of 8.5.3/4 and others):

void f1(Object *& op);
Object a; Object *op1 = &a; f1(op1); // 1

void f2(Object const& op);
Object b; f2(b); // 2

struct A { };
struct B { operator A&() { static A a; return a; } };
void f3(A &);
B b; f3(b); // passes the static a by reference

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

If you have access to a linux box with mdbtools installed, you can use this Bash shell script (save as mdbconvert.sh):

#!/bin/bash

TABLES=$(mdb-tables -1 $1)

MUSER="root"
MPASS="yourpassword"
MDB="$2"

MYSQL=$(which mysql)

for t in $TABLES
do
    $MYSQL -u $MUSER -p$MPASS $MDB -e "DROP TABLE IF EXISTS $t"
done

mdb-schema $1 mysql | $MYSQL -u $MUSER -p$MPASS $MDB

for t in $TABLES
do
    mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t | $MYSQL -u $MUSER -p$MPASS $MDB
done

To invoke it simply call it like this:

./mdbconvert.sh accessfile.mdb mysqldatabasename

It will import all tables and all data.

How to filter empty or NULL names in a QuerySet?

this is another simple way to do it .

Name.objects.exclude(alias=None)

Why am I getting an error "Object literal may only specify known properties"?

As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.

Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash is incorrect and should have been callbackOnLocationHash (note the mis-spelling of "Location").

This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.

Example:

interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

But I meant to do that

There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes

Type-checking only some properties

Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v or v as T) do not check for extra properties, so you can use them in place of a type annotation:

interface Options {
    x?: string;
    y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

These properties and maybe more

Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking

Before

interface Model {
  name: string;
}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});

After

interface Model {
  name: string;
  [others: string]: any;
}
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

This is a dog or a cat or a horse, not sure yet

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };
}

Two good solutions come to mind here

Specify a closed set for x

// Removes all errors
let x: Dog|Cat|Horse;

or Type assert each thing

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

This type is sometimes open and sometimes not

A clean solution to the "data model" problem using intersection types:

interface DataModelOptions {
  name?: string;
  id?: number;
}
interface UserProperties {
  [key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

See also https://github.com/Microsoft/TypeScript/issues/3755

How to kill zombie process

Sometimes the parent ppid cannot be killed, hence kill the zombie pid

kill -9 $(ps -A -ostat,pid | awk '/[zZ]/{ print $2 }')

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

Try the following

_x000D_
_x000D_
var myData = [['2013-01-22', 0], ['2013-01-29', 1], ['2013-02-05', 21]];_x000D_
_x000D_
var myTotal = 0;  // Variable to hold your total_x000D_
_x000D_
for(var i = 0, len = myData.length; i < len; i++) {_x000D_
    myTotal += myData[i][1];  // Iterate over your first array and then grab the second element add the values up_x000D_
}_x000D_
_x000D_
document.write(myTotal); // 22 in this instance
_x000D_
_x000D_
_x000D_

How to replace a substring of a string

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

from javadoc.

Getting distance between two points based on latitude/longitude

import numpy as np


def Haversine(lat1,lon1,lat2,lon2, **kwarg):
    """
    This uses the ‘haversine’ formula to calculate the great-circle distance between two points – that is, 
    the shortest distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the points 
    (ignoring any hills they fly over, of course!).
    Haversine
    formula:    a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)
    c = 2 · atan2( va, v(1-a) )
    d = R · c
    where   f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);
    note that angles need to be in radians to pass to trig functions!
    """
    R = 6371.0088
    lat1,lon1,lat2,lon2 = map(np.radians, [lat1,lon1,lat2,lon2])

    dlat = lat2 - lat1
    dlon = lon2 - lon1
    a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2) **2
    c = 2 * np.arctan2(a**0.5, (1-a)**0.5)
    d = R * c
    return round(d,4)

pandas GroupBy columns with NaN (missing) values

pandas >= 1.1

From pandas 1.1 you have better control over this behavior, NA values are now allowed in the grouper using dropna=False:

pd.__version__
# '1.1.0.dev0+2004.g8d10bfb6f'

# Example from the docs
df

   a    b  c
0  1  2.0  3
1  1  NaN  4
2  2  1.0  3
3  1  2.0  2

# without NA (the default)
df.groupby('b').sum()

     a  c
b        
1.0  2  3
2.0  2  5
# with NA
df.groupby('b', dropna=False).sum()

     a  c
b        
1.0  2  3
2.0  2  5
NaN  1  4

Command to close an application of console?

So you didn't say you wanted the application to quit or exit abruptly, so as another option, perhaps just have the response loop end out elegantly. (I am assuming you have a while loop waiting for user instructions. This is some code from a project I just wrote today.

        Console.WriteLine("College File Processor");
        Console.WriteLine("*************************************");
        Console.WriteLine("(H)elp");
        Console.WriteLine("Process (W)orkouts");
        Console.WriteLine("Process (I)nterviews");
        Console.WriteLine("Process (P)ro Days");
        Console.WriteLine("(S)tart Processing");
        Console.WriteLine("E(x)it");
        Console.WriteLine("*************************************");

        string response = "";
        string videotype = "";
        bool starting = false;
        bool exiting = false;

        response = Console.ReadLine();

        while ( response != "" )
        {
            switch ( response  )
            {
                case "H":
                case "h":
                    DisplayHelp();
                    break;

                case "W":
                case "w":
                    Console.WriteLine("Video Type set to Workout");
                    videotype = "W";
                    break;

                case "I":
                case "i":
                    Console.WriteLine("Video Type set to Interview");
                    videotype = "I";
                    break;

                case "P":
                case "p":
                    Console.WriteLine("Video Type set to Pro Day");
                    videotype = "P";
                    break;

                case "S":
                case "s":
                    if ( videotype == "" )
                    {
                        Console.WriteLine("Please Select Video Type Before Starting");
                    }
                    else
                    {
                        Console.WriteLine("Starting...");
                        starting = true;
                    }
                    break;

                case "E":
                case "e":
                    Console.WriteLine("Good Bye!");
                    System.Threading.Thread.Sleep(100);
                    exiting = true;
                    break;
            }

            if ( starting || exiting)
            {
                break;
            }
            else
            {
                response = Console.ReadLine();
            }
        }

        if ( starting )
        {
            ProcessFiles();
        }

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Start by figuring out what your current working directory is for your running script.
Add this line at the beginning:

puts Dir.pwd.

This will tell you in which current working directory ruby is running your script. You will most likely see it's not where you assume it is. Then make sure you're specifying pathnames properly for windows. See the docs here how to properly format pathnames for windows:

http://www.ruby-doc.org/core/classes/IO.html

Then either use Dir.chdir to change the working directory to the place where text.txt is, or specify the absolute pathname to the file according to the instructions in the IO docs above. That SHOULD do it...

EDIT

Adding a 3rd solution which might be the most convenient one, if you're putting the text files among your script files:

Dir.chdir(File.dirname(__FILE__))

This will automatically change the current working directory to the same directory as the .rb file that is running the script.

Is it possible to modify a string of char in C?

A lot of folks get confused about the difference between char* and char[] in conjunction with string literals in C. When you write:

char *foo = "hello world";

...you are actually pointing foo to a constant block of memory (in fact, what the compiler does with "hello world" in this instance is implementation-dependent.)

Using char[] instead tells the compiler that you want to create an array and fill it with the contents, "hello world". foo is the a pointer to the first index of the char array. They both are char pointers, but only char[] will point to a locally allocated and mutable block of memory.

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

This is called programming to interface. This will be helpful in case if you wish to move to some other implementation of List in the future. If you want some methods in ArrayList then you would need to program to the implementation that is ArrayList a = new ArrayList().

Calculating distance between two geographic locations

Try This Code. here we have two longitude and latitude values and selected_location.distanceTo(near_locations) function returns the distance between those places in meters.

Location selected_location = new Location("locationA");
            selected_location.setLatitude(17.372102);
            selected_location.setLongitude(78.484196);
Location near_locations = new Location("locationB");
            near_locations.setLatitude(17.375775);
            near_locations.setLongitude(78.469218);
double distance = selected_location.distanceTo(near_locations);

here "distance" is distance between locationA & locationB (in Meters)

Get the value of bootstrap Datetimepicker in JavaScript

I tried all the above methods and I did not get the value properly in the same format, then I found this.

$("#datetimepicker1").find("input")[1].value;

The above code will return the value in the same format as in the datetime picker.

This may help you guys in the future.

Hope this was helpful..

Best Practice to Use HttpClient in Multithreaded Environment

My reading of the docs is that HttpConnection itself is not treated as thread safe, and hence MultiThreadedHttpConnectionManager provides a reusable pool of HttpConnections, you have a single MultiThreadedHttpConnectionManager shared by all threads and initialised exactly once. So you need a couple of small refinements to option A.

MultiThreadedHttpConnectionManager connman = new MultiThreadedHttpConnectionManag

Then each thread should be using the sequence for every request, getting a conection from the pool and putting it back on completion of its work - using a finally block may be good. You should also code for the possibility that the pool has no available connections and process the timeout exception.

HttpConnection connection = null
try {
    connection = connman.getConnectionWithTimeout(
                        HostConfiguration hostConfiguration, long timeout) 
    // work
} catch (/*etc*/) {/*etc*/} finally{
    if ( connection != null )
        connman.releaseConnection(connection);
}

As you are using a pool of connections you won't actually be closing the connections and so this should not hit the TIME_WAIT problem. This approach does assuume that each thread doesn't hang on to the connection for long. Note that conman itself is left open.

How to compare values which may both be null in T-SQL

I needed a similar comparison when doing a MERGE:

WHEN MATCHED AND (Target.Field1 <> Source.Field1 OR ...)

The additional checks are to avoid updating rows where all the columns are already the same. For my purposes I wanted NULL <> anyValue to be True, and NULL <> NULL to be False.

The solution evolved as follows:

First attempt:

WHEN MATCHED AND
(
    (
        -- Neither is null, values are not equal
        Target.Field1 IS NOT NULL
            AND Source.Field1 IS NOT NULL
            AND Target.Field1 <> Source.Field1
    )
    OR
    (
        -- Target is null but source is not
        Target.Field1 IS NULL
            AND Source.Field1 IS NOT NULL
    )
    OR
    (
        -- Source is null but target is not
        Target.Field1 IS NOT NULL
            AND Source.Field1 IS NULL
    )

    -- OR ... Repeat for other columns
)

Second attempt:

WHEN MATCHED AND
(
    -- Neither is null, values are not equal
    NOT (Target.Field1 IS NULL OR Source.Field1 IS NULL)
        AND Target.Field1 <> Source.Field1

    -- Source xor target is null
    OR (Target.Field1 IS NULL OR Source.Field1 IS NULL)
        AND NOT (Target.Field1 IS NULL AND Source.Field1 IS NULL)

    -- OR ... Repeat for other columns
)

Third attempt (inspired by @THEn's answer):

WHEN MATCHED AND
(

    ISNULL(
        NULLIF(Target.Field1, Source.Field1),
        NULLIF(Source.Field1, Target.Field1)
    ) IS NOT NULL

    -- OR ... Repeat for other columns
)

The same ISNULL/NULLIF logic can be used to test equality and inequality:

  • Equality: ISNULL(NULLIF(A, B), NULLIF(B, A)) IS NULL
  • Inequaltiy: ISNULL(NULLIF(A, B), NULLIF(B, A)) IS NOT NULL

Here is an SQL-Fiddle demonstrating how it works http://sqlfiddle.com/#!3/471d60/1

Angular ng-repeat add bootstrap row every 3 or 4 cols

After combining many answers and suggestion here, this is my final answer, which works well with flex, which allows us to make columns with equal height, it also checks the last index, and you don't need to repeat the inner HTML. It doesn't use clearfix:

<div ng-repeat="prod in productsFiltered=(products | filter:myInputFilter)" ng-if="$index % 3 == 0" class="row row-eq-height">
    <div ng-repeat="i in [0, 1, 2]" ng-init="product = productsFiltered[$parent.$parent.$index + i]"  ng-if="$parent.$index + i < productsFiltered.length" class="col-xs-4">
        <div class="col-xs-12">{{ product.name }}</div>
    </div>
</div>

It will output something like this:

<div class="row row-eq-height">
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
</div>
<div class="row row-eq-height">
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
    <div class="col-xs-4">
        <div class="col-xs-12">
            Product Name
        </div>
    </div>
</div>

Stock ticker symbol lookup API

You can send an HTTP request to http://finance.yahoo.com requesting symbols, names, quotes, and all sorts of other data. Data is returned as a .CSV so you can request multiple symbols in one query.

So if you send:

http://finance.yahoo.com/d/quotes.csv?s=MSFT+F+ATT&f=sn

You'll get back something like:

"MSFT","Microsoft Corp"
"F","FORD MOTOR CO"
"ATT","AT&T"

Here is an article called Downloading Yahoo Data which includes the various tags used to request the data.

Warning: Failed propType: Invalid prop `component` supplied to `Route`

[email protected] also fixed this bug, just update it:

npm i --save react-router@latest

Getting data-* attribute for onclick event for an html element

Like this:

$(this).data('id');
$(this).data('option');

Working example: http://jsfiddle.net/zwHUc/

How do you post to an iframe?

This function creates a temporary form, then send data using jQuery :

function postToIframe(data,url,target){
    $('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
    $.each(data,function(n,v){
        $('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
    });
    $('#postToIframe').submit().remove();
}

target is the 'name' attr of the target iFrame, and data is a JS object :

data={last_name:'Smith',first_name:'John'}

Using OpenGl with C#?

Tao is supposed to be a nice framework.

From their site:

The Tao Framework for .NET is a collection of bindings to facilitate cross-platform media application development utilizing the .NET and Mono platforms.

How to scroll to top of long ScrollView layout?

I faced Same Problem When i am using Scrollview inside View Flipper or Dialog that case scrollViewObject.fullScroll(ScrollView.FOCUS_UP) returns false so that case scrollViewObject.smoothScrollTo(0, 0) is Worked for me

Scroll Focus Top

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

What worked for me was to place the jniLibs folder under the "main" folder, just besides the "java" and "res" folders, for example project -> app -> src -> main -> jniLibs

I had all the libraries with the correct names and each one placed on their respective architecture subfolder, but I still had the same exception; even tried a lot of other SO answers like the accepted answer here, compiling a JAR with the .so libs, other placing of the jniLibs folder, etc.

For this project, I had to use Gradle 2.2 and Android Plugin 1.1.0 on Android Studio 1.5.1

Read Session Id using Javascript

As far as I know, a browser session doesn't have an id.

If you mean the server session, that is usually stored in a cookie. The cookie that ASP.NET stores, for example, is named "ASP.NET_SessionId".

clientHeight/clientWidth returning different values on different browsers

It may be caused by IE's box model bug. To fix this, you can use the Box Model Hack.

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

Install gcc.

If you're on linux, use the package manager.

If you're on Windows, use MinGW.

How to permanently add a private key with ssh-add on Ubuntu?

This worked for me.

ssh-agent /bin/sh
ssh-add /path/to/your/key

How to draw a checkmark / tick using CSS?

You can now include web fonts and even shrink down the file size with just the glyphs you need. https://github.com/fontello/fontello http://fontello.com/

li:before {
  content:'[add icon symbol here]';
  font-family: [my cool web icon font here];
  display:inline-block;
  vertical-align: top;
  line-height: 1em;
  width: 1em;
  height:1em;
  margin-right: 0.3em;
  text-align: center;
  color: #999;
}

Eclipse DDMS error "Can't bind to local 8600 for debugger"

I had a similar problem on OSX. It just so happens I had opened two instances of Eclipse so I could refer to some code in another workspace. Eventually I realized the two instances might be interfering with each other so I closed one. After that, I'm no longer seeing the "Can't bind..." error.

IIS 7, HttpHandler and HTTP Error 500.21

I had the same problem and just solved it. I had posted my own question on stackoverflow:

Can't PUT to my IHttpHandler, GET works fine

The solution was to set runManagedModulesForWebDavRequests to true in the modules element. My guess is that once you install WebDAV then all PUT requests are associated with it. If you need the PUT to go to your handler, you need to remove the WebDAV module and set this attribute to true.

<modules runManagedModulesForWebDavRequests="true">
...
</modules>

So if you're running into the problem when you use the PUT verb and you have installed WebDAV then hopefully this solution will fix your problem.

Loop through a Map with JSTL

Like this:

<c:forEach var="entry" items="${myMap}">
  Key: <c:out value="${entry.key}"/>
  Value: <c:out value="${entry.value}"/>
</c:forEach>

Python conversion between coordinates

Using numpy, you can define the following:

import numpy as np

def cart2pol(x, y):
    rho = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)
    return(rho, phi)

def pol2cart(rho, phi):
    x = rho * np.cos(phi)
    y = rho * np.sin(phi)
    return(x, y)

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

SSL peer shut down incorrectly in Java

I had mutual SSL enabled on my Spring Boot app and my Jenkins pipeline was re-building the dockers, bringing the compose up and then running integration tests which failed every time with this error. I was able to test the running dockers without this SSL error every time in a standalone test on the same Jenkins machine. It turned out that server was not completely up when the tests started executing. Putting a sleep of few seconds in my bash script to allow Spring boot application to be up and running completely resolved the issue.

is there a require for json in node.js

As of node v0.5.x yes you can require your JSON just as you would require a js file.

var someObject = require('./somefile.json')

In ES6:

import someObject from ('./somefile.json')

How do you run a .bat file from PHP?

When you use the exec() function, it is as though you have a cmd terminal open and are typing commands straight to it.

Use single quotes like this $str = exec('start /B Path\to\batch.bat');
The /B means the bat will be executed in the background so the rest of the php will continue after running that line, as opposed to $str = exec('start /B /C command', $result); where command is executed and then result is stored for later use.

PS: It works for both Windows and Linux.
More details are here http://www.php.net/manual/en/function.exec.php :)

Why does the C++ STL not provide any "tree" containers?

Probably for the same reason that there is no tree container in boost. There are many ways to implement such a container, and there is no good way to satisfy everyone who would use it.

Some issues to consider:

  • Are the number of children for a node fixed or variable?
  • How much overhead per node? - ie, do you need parent pointers, sibling pointers, etc.
  • What algorithms to provide? - different iterators, search algorithms, etc.

In the end, the problem ends up being that a tree container that would be useful enough to everyone, would be too heavyweight to satisfy most of the people using it. If you are looking for something powerful, Boost Graph Library is essentially a superset of what a tree library could be used for.

Here are some other generic tree implementations:

How to input a string from user into environment variable from batch file

You can use set with the /p argument:

SET /P variable=[promptString]

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

So, simply use something like

set /p Input=Enter some text: 

Later you can use that variable as argument to a command:

myCommand %Input%

Be careful though, that if your input might contain spaces it's probably a good idea to quote it:

myCommand "%Input%"

Have a div cling to top of screen if scrolled down past it

Use position:fixed; and set the top:0;left:0;right:0;height:100px; and you should be able to have it "stick" to the top of the page.

<div style="position:fixed;top:0;left:0;right:0;height:100px;">Some buttons</div>

How to set tbody height with overflow scroll

If you want tbody to show a scrollbar, set its display: block;.

Set display: table; for the tr so that it keeps the behavior of a table.

To evenly spread the cells, use table-layout: fixed;.

DEMO tbody scroll


CSS:

table, tr td {
    border: 1px solid red
}
tbody {
    display: block;
    height: 50px;
    overflow: auto;
}
thead, tbody tr {
    display: table;
    width: 100%;
    table-layout: fixed;/* even columns width , fix width of table too*/
}
thead {
    width: calc( 100% - 1em )/* scrollbar is average 1em/16px width, remove it from thead width */
}
table {
    width: 400px;
}

If tbody doesn't show a scroll, because content is less than height or max-height, set the scroll any time with: overflow-y: scroll;. DEMO 2

Important note: this approach to making a table scrollable has drawbacks in some cases. (See comments below.)

How to get the concrete class name as a string?

you can also create a dict with the classes themselves as keys, not necessarily the classnames

typefunc={
    int:lambda x: x*2,
    str:lambda s:'(*(%s)*)'%s
}

def transform (param):
    print typefunc[type(param)](param)

transform (1)
>>> 2
transform ("hi")
>>> (*(hi)*)

here typefunc is a dict that maps a function for each type. transform gets that function and applies it to the parameter.

of course, it would be much better to use 'real' OOP

Not class selector in jQuery

You need the :not() selector:

$('div[class^="first-"]:not(.first-bar)')

or, alternatively, the .not() method:

$('div[class^="first-"]').not('.first-bar');

How to use default Android drawables

Better to use android.R.drawable because it is public and documented.

How do I put text on ProgressBar?

AVOID FLICKERING TEXT

The solution provided by Barry above is excellent, but there's is the "flicker-problem".

As soon as the Value is above zero the OnPaint will be envoked repeatedly and the text will flicker.

There is a solution to this. We do not need VisualStyles for the object since we will be drawing it with our own code.

Add the following code to the custom object Barry wrote and you will avoid the flicker:

    [DllImportAttribute("uxtheme.dll")]
    private static extern int SetWindowTheme(IntPtr hWnd, string appname, string idlist);

    protected override void OnHandleCreated(EventArgs e)
    {
        SetWindowTheme(this.Handle, "", "");
        base.OnHandleCreated(e);
    }

I did not write this myself. It found it here: https://stackoverflow.com/a/299983/1163954

I've testet it and it works.

Centering the pagination in bootstrap

bootstrap 4 :

<!-- Default (left-aligned) -->
<ul class="pagination" style="margin:20px 0">
  <li class="page-item">...</li>
</ul>

<!-- Center-aligned -->
<ul class="pagination justify-content-center" style="margin:20px 0">
  <li class="page-item">...</li>
</ul>

<!-- Right-aligned -->
<ul class="pagination justify-content-end" style="margin:20px 0">
  <li class="page-item">...</li>
</ul> 

Create parameterized VIEW in SQL Server 2008

As astander has mentioned, you can do that with a UDF. However, for large sets using a scalar function (as oppoosed to a inline-table function) the performance will stink as the function is evaluated row-by-row. As an alternative, you could expose the same results via a stored procedure executing a fixed query with placeholders which substitutes in your parameter values.

(Here's a somewhat dated but still relevant article on row-by-row processing for scalar UDFs.)

Edit: comments re. degrading performance adjusted to make it clear this applies to scalar UDFs.

Strip spaces/tabs/newlines - python

This will only remove the tab, newlines, spaces and nothing else.

import re
myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"
output   = re.sub(r"[\n\t\s]*", "", myString)

OUTPUT:

IwantoRemoveallwhiespaces,newlinesandtabs

Good day!

Executing a stored procedure within a stored procedure

Here is an example of one of our stored procedures that executes multiple stored procedures within it:

ALTER PROCEDURE [dbo].[AssetLibrary_AssetDelete]
(
    @AssetID AS uniqueidentifier
)
AS

SET NOCOUNT ON

SET TRANSACTION ISOLATION LEVEL READ COMMITTED

EXEC AssetLibrary_AssetDeleteAttributes @AssetID
EXEC AssetLibrary_AssetDeleteComponents @AssetID
EXEC AssetLibrary_AssetDeleteAgreements @AssetID
EXEC AssetLibrary_AssetDeleteMaintenance @AssetID

DELETE FROM
    AssetLibrary_Asset
WHERE
    AssetLibrary_Asset.AssetID = @AssetID

RETURN (@@ERROR)

calling parent class method from child class object in java

Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though. The example below will help.

public class Parent {
    public int add(int m, int n){
        return m+n;
    }
}


public class Child extends Parent{
    public int add(int m,int n,int o){
        return super.add(super.add(m, n),0);
    }

}


public class SimpleInheritanceTest {
    public static void main(String[] a){
        Child child = new Child();
        child.add(10, 11);
    }
}

The add method in the Child class calls super.add to reuse the addition logic.

curl: (6) Could not resolve host: application

In my case, putting space after colon was wrong.

# Not work
curl -H Content-Type: application/json ~
# OK
curl -H Content-Type:application/json ~

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

I'm not sure about HQL, but in JPA you just call the query's setParameter with the parameter and collection.

Query q = entityManager.createQuery("SELECT p FROM Peron p WHERE name IN (:names)");
q.setParameter("names", names);

where names is the collection of names you're searching for

Collection<String> names = new ArrayList<String();
names.add("Joe");
names.add("Jane");
names.add("Bob");

How to compare the contents of two string objects in PowerShell

You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title

-match is for regex matching ( the second argument is a regex )

<DIV> inside link (<a href="">) tag

No, the link assigned to the containing <a> will be assigned to every elements inside it.

And, this is not the proper way. You can make a <a> behave like a <div>.

An Example [Demo]

CSS

a.divlink { 
     display:block;
     width:500px;
     height:500px; 
     float:left;
}

HTML

<div>
    <a class="divlink" href="yourlink.html">
         The text or elements inside the elements
    </a>
    <a class="divlink" href="yourlink2.html">
         Another text or element
    </a>
</div>

Make virtualenv inherit specific packages from your global site-packages

Install virtual env with

virtualenv --system-site-packages

and use pip install -U to install matplotlib

How to get POST data in WebAPI?

I found for my use case this was much more useful, hopefully it helps someone else that spent time on this answer applying it

public IDictionary<string, object> GetBodyPropsList()
        {
            var contentType = Request.Content.Headers.ContentType.MediaType;
            var requestParams = Request.Content.ReadAsStringAsync().Result;

            if (contentType == "application/json")
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, object>>(requestParams);
            }
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

Clear Cache in Android Application programmatically

Kotlin has an one-liner

context.cacheDir.deleteRecursively()

Multiple conditions in WHILE loop

If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.

How to read/write files in .Net Core?

    public static void Copy(String SourceFile, String TargetFile)
    {

        FileStream fis = null;
        FileStream fos = null;

            try
            {
                Console.Write("## Try No. " + a + " : (Write from " + SourceFile + " to " + TargetFile + ")\n");

                fis = new FileStream(SourceFile, FileMode.Open, FileAccess.ReadWrite);
                fos = new FileStream(TargetFile, FileMode.Create, FileAccess.ReadWrite);

                int intbuffer = 5242880;
                byte[] b = new byte[intbuffer];

                int i;
                while ((i = fis.Read(b, 0, intbuffer)) > 0)
                {
                    fos.Write(b, 0, i);
                }

                Console.Write("Writing file : " + TargetFile + " is successful.\n");

                break;
            }
            catch (Exception e)
            {
                Console.Write("Writing file : " + TargetFile + " is unsuccessful.\n");
                Console.Write(e);
            }
            finally
            {
                if (fis != null)
                {
                    fis.Close();
                }
                if (fos != null)
                {
                    fos.Close();
                }
            }
    }

The code above will read a big file and write to a new big file. The "intbuffer" value can be set in multiple of 1024. While both source and target file are open, it reads the big file by bytes and write to the new target file by bytes. It will not go out of memory.

Simple JavaScript problem: onClick confirm not preventing default action

First of all, delete is a reserved word in javascript, I'm surprised this even executes for you (When I test it in Firefox, I get a syntax error)

Secondly, your HTML looks weird - is there a reason you're closing the opening anchor tags with /> instead of just > ?

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

I was facing similar issue with openCV on the python:3.7-slim docker box. Following did the trick for me :

apt-get install build-essential libglib2.0-0 libsm6 libxext6 libxrender-dev

Please see if this helps !

How to get the ASCII value of a character

Note that ord() doesn't give you the ASCII value per se; it gives you the numeric value of the character in whatever encoding it's in. Therefore the result of ord('ä') can be 228 if you're using Latin-1, or it can raise a TypeError if you're using UTF-8. It can even return the Unicode codepoint instead if you pass it a unicode:

>>> ord(u'?')
12354

Getting Database connection in pure JPA setup

I'm using a old version of Hibernate (3.3.0) with a newest version of OpenEJB (4.6.0). My solution was:

EntityManagerImpl entityManager = (EntityManagerImpl)em.getDelegate();
Session session = entityManager.getSession();
Connection connection = session.connection();
Statement statement = null;
try {
    statement = connection.createStatement();
    statement.execute(sql);
    connection.commit();
} catch (SQLException e) {
    throw new RuntimeException(e);
}

I had an error after that:

Commit can not be set while enrolled in a transaction

Because this code above was inside a EJB Controller (you can't commit inside a transaction). I annotated the method with @TransactionAttribute(value = TransactionAttributeType.NOT_SUPPORTED) and the problem was gone.

How to replace a string in an existing file in Perl?

It can be done using a single line:

perl -pi.back -e 's/oldString/newString/g;' inputFileName

Pay attention that oldString is processed as a Regular Expression.
In case the string contains any of {}[]()^$.|*+? (The special characters for Regular Expression syntax) make sure to escape them unless you want it to be processed as a regular expression.
Escaping it is done by \, so \[.

Checking images for similarity with OpenCV

Sam's solution should be sufficient. I've used combination of both histogram difference and template matching because not one method was working for me 100% of the times. I've given less importance to histogram method though. Here's how I've implemented in simple python script.

import cv2

class CompareImage(object):

    def __init__(self, image_1_path, image_2_path):
        self.minimum_commutative_image_diff = 1
        self.image_1_path = image_1_path
        self.image_2_path = image_2_path

    def compare_image(self):
        image_1 = cv2.imread(self.image_1_path, 0)
        image_2 = cv2.imread(self.image_2_path, 0)
        commutative_image_diff = self.get_image_difference(image_1, image_2)

        if commutative_image_diff < self.minimum_commutative_image_diff:
            print "Matched"
            return commutative_image_diff
        return 10000 //random failure value

    @staticmethod
    def get_image_difference(image_1, image_2):
        first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256])
        second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256])

        img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA)
        img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0]
        img_template_diff = 1 - img_template_probability_match

        # taking only 10% of histogram diff, since it's less accurate than template method
        commutative_image_diff = (img_hist_diff / 10) + img_template_diff
        return commutative_image_diff


    if __name__ == '__main__':
        compare_image = CompareImage('image1/path', 'image2/path')
        image_difference = compare_image.compare_image()
        print image_difference

How to create a generic array in Java?

Maybe unrelated to this question but while I was getting the "generic array creation" error for using

Tuple<Long,String>[] tupleArray = new Tuple<Long,String>[10];

I find out the following works (and worked for me) with @SuppressWarnings({"unchecked"}):

 Tuple<Long, String>[] tupleArray = new Tuple[10];

How to convert a number to string and vice versa in C++

In C++17, new functions std::to_chars and std::from_chars are introduced in header charconv.

std::to_chars is locale-independent, non-allocating, and non-throwing.

Only a small subset of formatting policies used by other libraries (such as std::sprintf) is provided.

From std::to_chars, same for std::from_chars.

The guarantee that std::from_chars can recover every floating-point value formatted by to_chars exactly is only provided if both functions are from the same implementation

 // See en.cppreference.com for more information, including format control.
#include <cstdio>
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <charconv>

using Type =  /* Any fundamental type */ ;
std::size_t buffer_size = /* ... */ ;

[[noreturn]] void report_and_exit(int ret, const char *output) noexcept 
{
    std::printf("%s\n", output);
    std::exit(ret);
}
void check(const std::errc &ec) noexcept
{
    if (ec ==  std::errc::value_too_large)
        report_and_exit(1, "Failed");
}
int main() {
    char buffer[buffer_size];        
    Type val_to_be_converted, result_of_converted_back;

    auto result1 = std::to_chars(buffer, buffer + buffer_size,  val_to_be_converted);
    check(result1.ec);
    *result1.ptr = '\0';

    auto result2 = std::from_chars(buffer, result1.ptr, result_of_converted_back);
    check(result2.ec);

    assert(val_to_be_converted == result_of_converted_back);
    report_and_exit(0, buffer);
}

Although it's not fully implemented by compilers, it definitely will be implemented.

jinja2.exceptions.TemplateNotFound error

You put your template in the wrong place. From the Flask docs:

Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates

OWIN Startup Class Missing

On Visual Studio 2013 RC2, there is a template for this. Just add it to App_Start folder.

enter image description here

The template produces such a class:

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(WebApiOsp.App_Start.Startup))]

namespace WebApiOsp.App_Start
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
        }
    }
}

How can I schedule a daily backup with SQL Server Express?

Eduardo Molteni had a great answer:

Using Windows Scheduled Tasks:

In the batch file

"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" -S 
(local)\SQLExpress -i D:\dbbackups\SQLExpressBackups.sql

In SQLExpressBackups.sql

BACKUP DATABASE MyDataBase1 TO  DISK = N'D:\DBbackups\MyDataBase1.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase1 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

BACKUP DATABASE MyDataBase2 TO  DISK = N'D:\DBbackups\MyDataBase2.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase2 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

GO

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:

http://[server]/[site]/[ListName]/[Folder]/[SubFolder]

To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

How can I generate UUID in C#

I don't know about methods; however, the type to GUID can be done via:

Guid iid = System.Runtime.InteropServices.Marshal.GenerateGuidForType(typeof(IFoo));

http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.generateguidfortype.aspx

How to access property of anonymous type in C#?

You could iterate over the anonymous type's properties using Reflection; see if there is a "Checked" property and if there is then get its value.

See this blog post: http://blogs.msdn.com/wriju/archive/2007/10/26/c-3-0-anonymous-type-and-net-reflection-hand-in-hand.aspx

So something like:

foreach(object o in nodes)
{
    Type t = o.GetType();

    PropertyInfo[] pi = t.GetProperties(); 

    foreach (PropertyInfo p in pi)
    {
        if (p.Name=="Checked" && !(bool)p.GetValue(o))
            Console.WriteLine("awesome!");
    }
}

How to display a range input slider vertically

You can do this with css transforms, though be careful with container height/width. Also you may need to position it lower:

_x000D_
_x000D_
input[type="range"] {_x000D_
   position: absolute;_x000D_
   top: 40%;_x000D_
   transform: rotate(270deg);_x000D_
}
_x000D_
<input type="range"/>
_x000D_
_x000D_
_x000D_


or the 3d transform equivalent:

input[type="range"] {
   transform: rotateZ(270deg);
}

You can also use this to switch the direction of the slide by setting it to 180deg or 90deg for horizontal or vertical respectively.

How to disable a particular checkstyle rule for a particular line of code?

I had difficulty with the answers above, potentially because I set the checkStyle warnings to be errors. What did work was SuppressionFilter: http://checkstyle.sourceforge.net/config_filters.html#SuppressionFilter

The drawback of this is that the line range is stored in a separate suppresssions.xml file, so an unfamiliar developer may not immediately make the connection.

How do I get this javascript to run every second?

Use setInterval(func, delay) to run the func every delay milliseconds.

setTimeout() runs your function once after delay milliseconds -- it does not run it repeatedly. A common strategy is to run your code with setTimeout and call setTimeout again at the end of your code.

SQL Server 2008 can't login with newly created user

You'll likely need to check the SQL Server error logs to determine the actual state (it's not reported to the client for security reasons.) See here for details.

Sql script to find invalid email addresses

SELECT * FROM people WHERE email NOT LIKE '%_@__%.__%'

Anything more complex will likely return false negatives and run slower.

Validating e-mail addresses in code is virtually impossible.

EDIT: Related questions

Displaying the Indian currency symbol on a website

Image approach is not bad either. It hardly takes 400Bytes.
Download from here http://i.stack.imgur.com/vJZ9m.png

<span class="rupee"></span>

Well i found it better than webrupee.

For colors edit the image as below

    .rupee{
    background-position:left;
    width: 10px; 
    height: 14px;
    background-image: url('rupee.png');
    display:block; 
    background-repeat: no-repeat;
}

Git: How to check if a local repo is up to date?

You must run git fetch before you can compare your local repository against the files on your remote server.

This command only updates your remote tracking branches and will not affect your worktree until you call git merge or git pull.

To see the difference between your local branch and your remote tracking branch once you've fetched you can use git diff or git cherry as explained here.

What is the correct syntax of ng-include?

Maybe this will help for beginners

<!doctype html>
<html lang="en" ng-app>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="icon" href="favicon.ico">
    <link rel="stylesheet" href="custom.css">
  </head>
  <body>
    <div ng-include src="'view/01.html'"></div>
    <div ng-include src="'view/02.html'"></div>
    <script src="angular.min.js"></script>
  </body>
</html>

Return row of Data Frame based on value in a column - R

Based on the syntax provided

 Select * Where Amount = min(Amount)

You could do using:

 library(sqldf)

Using @Kara Woo's example df

  sqldf("select * from df where Amount in (select min(Amount) from df)")
  #Name Amount
 #1    B    120
 #2    E    120

How can I make a Python script standalone executable to run without ANY dependency?

pyinstaller yourfile.py -F --onefile

This creates a standalone EXE file on Windows.

Important note 1: The EXE file will be generated in a folder named 'dist'.

Important note 2: Do not forget --onefile flag

You can install PyInstaller using pip install PyInstaller

Enter image description here

Enter image description here

NOTE: In rare cases there are hidden dependencies...so if you run the EXE file and get missing library error (win32timezone in the example below) then use something like this:

pyinstaller --hiddenimport win32timezone -F "Backup Program.py"

Extract data from XML Clob using SQL from Oracle Database

This should work

SELECT EXTRACTVALUE(column_name, '/DCResponse/ContextData/Decision') FROM traptabclob;

I have assumed the ** were just for highlighting?

C# Return Different Types?

May be you need "dynamic" type?

public dynamic GetAnything()
{
     Hello hello = new Hello();
     Computer computer = new Computer();
     Radio radio = new Radio();

     return /*what boject you needed*/ ;`enter code here`   
}

Create stacked barplot where each stack is scaled to sum to 100%

You just need to divide each element by the sum of the values in its column.

Doing this should suffice:

data.perc <- apply(data, 2, function(x){x/sum(x)})

Note that the second parameter tells apply to apply the provided function to columns (using 1 you would apply it to rows). The anonymous function, then, gets passed each data column, one at a time.

equivalent to push() or pop() for arrays?

In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.

int[] i = new int[10];

The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:

int[] i = new int[11];

In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

Overview

As reported by Tim Anderson

Cross-platform development is a big deal, and will continue to be so until a day comes when everyone uses the same platform. Android? HTML? WebKit? iOS? Windows? Xamarin? Titanum? PhoneGap? Corona? ecc.

Sometimes I hear it said that there are essentially two approaches to cross-platform mobile apps. You can either use an embedded browser control and write a web app wrapped as a native app, as in Adobe PhoneGap/Cordova or the similar approach taken by Sencha, or you can use a cross-platform tool that creates native apps, such as Xamarin Studio, Appcelerator Titanium, or Embarcardero FireMonkey.

Within the second category though, there is diversity. In particular, they vary concerning the extent to which they abstract the user interface.

Here is the trade-off. If you design your cross-platform framework you can have your application work almost the same way on every platform. If you are sharing the UI design across all platforms, it is hard to make your design feel equally right in all cases. It might be better to take the approach adopted by most games, using a design that is distinctive to your app and make a virtue of its consistency across platforms, even though it does not have the native look and feel on any platform.

edit Xamarin v3 in 2014 started offering choice of Xamarin.Forms as well as pure native that still follows the philosophy mentioned here (took liberty of inline edit because such a great answer)

Xamarin Studio on the other hand makes no attempt to provide a shared GUI framework:

We don’t try to provide a user interface abstraction layer that works across all the platforms. We think that’s a bad approach that leads to lowest common denominator user interfaces. (Nat Friedman to Tim Anderson)

This is right; but the downside is the effort involved in maintaining two or more user interface designs for your app.

Comparison about PhoneGap and Titanium it's well reported in Kevin Whinnery blog.

PhoneGap

The purpose of PhoneGap is to allow HTML-based web applications to be deployed and installed as native applications. PhoneGap web applications are wrapped in a native application shell, and can be installed via the native app stores for multiple platforms. Additionally, PhoneGap strives to provide a common native API set which is typically unavailable to web applications, such as basic camera access, device contacts, and sensors not already exposed in the browser.

To develop PhoneGap applications, developers will create HTML, CSS, and JavaScript files in a local directory, much like developing a static website. Approaching native-quality UI performance in the browser is a non-trivial task - Sencha employs a large team of web programming experts dedicated full-time to solving this problem. Even so, on most platforms, in most browsers today, reaching native-quality UI performance and responsiveness is simply not possible, even with a framework as advanced as Sencha Touch. Is the browser already “good enough” though? It depends on your requirements and sensibilities, but it is unquestionably less good than native UI. Sometimes much worse, depending on the browser.

PhoneGap is not as truly cross-platform as one might believe, not all features are equally supported on all platforms.

  • Javascript is not an application scale programming language, too many global scope interactions, different libraries don't often co-exist nicely. We spent many hours trying to get knockout.js and jQuery.mobile play well together, and we still have problems.

  • Fragmented landscape for frameworks and libraries. Too many choices, and too many are not mature enough.

  • Strangely enough, for the needs of our app, decent performance could be achieved (not with jQuery.Mobile, though). We tried jqMobi (not very mature, but fast).

  • Very limited capability for interaction with other apps or cdevice capabilities, and this would not be cross-platform anyway, as there aren't any standards in HTML5 except for a few, like geolocation, camera and local databases.

by Karl Waclawek

Appcelerator Titanium

The goal of Titanium Mobile is to provide a high level, cross-platform JavaScript runtime and API for mobile development (today we support iOS, Android and Windows Phone. Titanium actually has more in common with MacRuby/Hot Cocoa, PHP, or node.js than it does with PhoneGap, Adobe AIR, Corona, or Rhomobile. Titanium is built on two assertions about mobile development: - There is a core of mobile development APIs which can be normalized across platforms. These areas should be targeted for code reuse. - There are platform-specific APIs, UI conventions, and features which developers should incorporate when developing for that platform. Platform-specific code should exist for these use cases to provide the best possible experience.

So for those reasons, Titanium is not an attempt at “write once, run everywhere”. Same as Xamarin.

Titanium are going to do a further step in the direction similar to that of Xamarin. In practice, they will do two layers of different depths: the layer Titanium (in JS), which gives you a bee JS-of-Titanium. If you want to go more low-level, have created an additional layer (called Hyperloop), where (always with JS) to call you back directly to native APIs of SO

Xamarin (+ MVVMCross)

AZDevelop.net

Xamarin (originally a division of Novell) in the last 18 months has brought to market its own IDE and snap-in for Visual Studio. The underlining premise of Mono is to create disparate mobile applications using C# while maintaining native UI development strategies.

In addition to creating a visual design platform to develop native applications, they have integrated testing suites, incorporated native library support and a Nuget style component store. Recently they provided iOS visual design through their IDE freeing the developer from opening XCode. In Visual Studio all three platforms are now supported and a cloud testing suite is on the horizon.

From the get go, Xamarin has provided a rich Android visual design experience. I have yet to download or open Eclipse or any other IDE besides Xamarin. What is truly amazing is that I am able to use LINQ to work with collections as well as create custom delegates and events that free me from objective-C and Java limitations. Many of the libraries I have been spoiled with, like Newtonsoft JSON.Net, work perfectly in all three environments.

In my opinion there are several HUGE advantages including

  • native performance
  • easier to read code (IMO)
  • testability
  • shared code between client and server
  • support (although Xam could do better on bugzilla)

Upgrade for me is use Xamarin and MVVMCross combined. It's still quite a new framework, but it's born from experience of several other frameworks (such as MvvmLight and monocross) and it's now been used in at several released cross platform projects.

Conclusion

My choice after knowing all these framwework, was to select development tool based on product needs. In general, however if you start to use a tool with which you feel comfortable (even if it requires a higher initial overhead) after you'll use it forever.

I chose Xamarin + MVVMCross and I must say to be happy with this choice. I'm not afraid of approach Native SDK for software updates or seeing limited functionality of a system or the most trivial thing a feature graphics. Write code fairly structured (DDD + SOA) is very useful to have a core project shared with native C# views implementation.

References and links

Transparent background on winforms?

I tried almost all of this. but still couldn't work. Finally I found it was because of 24bitmap problems. If you tried some bitmap which less than 24bit. Most of those above methods should work.

Where should I put <script> tags in HTML markup?

Depending on the script and its usage the best possible (in terms of page load and rendering time) may be to not use a conventional <script>-tag per se, but to dynamically trigger the loading of the script asynchronously.

There are some different techniques, but the most straight forward is to use document.createElement("script") when the window.onload event is triggered. Then the script is loaded first when the page itself has rendered, thus not impacting the time the user has to wait for the page to appear.

This naturally requires that the script itself is not needed for the rendering of the page.

For more information, see the post Coupling async scripts by Steve Souders (creator of YSlow but now at Google).

how to show only even or odd rows in sql server 2008?

For even values record :

select * from www where mod(salary,2)=0;

For odd values record:

select * from www where mod(salary,2)!=0;

Android View shadow

CardView gives you true shadow in android 5+ and it has a support library. Just wrap your view with it and you're done.

<android.support.v7.widget.CardView>
     <MyLayout>
</android.support.v7.widget.CardView>

It require the next dependency.

dependencies {
    ...
    compile 'com.android.support:cardview-v7:21.0.+'
}

Remove duplicates in the list using linq

You have three option here for removing duplicate item in your List:

  1. Use a a custom equality comparer and then use Distinct(new DistinctItemComparer()) as @Christian Hayter mentioned.
  2. Use GroupBy, but please note in GroupBy you should Group by all of the columns because if you just group by Id it doesn't remove duplicate items always. For example consider the following example:

    List<Item> a = new List<Item>
    {
        new Item {Id = 1, Name = "Item1", Code = "IT00001", Price = 100},
        new Item {Id = 2, Name = "Item2", Code = "IT00002", Price = 200},
        new Item {Id = 3, Name = "Item3", Code = "IT00003", Price = 150},
        new Item {Id = 1, Name = "Item1", Code = "IT00001", Price = 100},
        new Item {Id = 3, Name = "Item3", Code = "IT00003", Price = 150},
        new Item {Id = 3, Name = "Item3", Code = "IT00004", Price = 250}
    };
    var distinctItems = a.GroupBy(x => x.Id).Select(y => y.First());
    

    The result for this grouping will be:

    {Id = 1, Name = "Item1", Code = "IT00001", Price = 100}
    {Id = 2, Name = "Item2", Code = "IT00002", Price = 200}
    {Id = 3, Name = "Item3", Code = "IT00003", Price = 150}
    

    Which is incorrect because it considers {Id = 3, Name = "Item3", Code = "IT00004", Price = 250} as duplicate. So the correct query would be:

    var distinctItems = a.GroupBy(c => new { c.Id , c.Name , c.Code , c.Price})
                         .Select(c => c.First()).ToList();
    

    3.Override Equal and GetHashCode in item class:

    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Code { get; set; }
        public int Price { get; set; }
    
        public override bool Equals(object obj)
        {
            if (!(obj is Item))
                return false;
            Item p = (Item)obj;
            return (p.Id == Id && p.Name == Name && p.Code == Code && p.Price == Price);
        }
        public override int GetHashCode()
        {
            return String.Format("{0}|{1}|{2}|{3}", Id, Name, Code, Price).GetHashCode();
        }
    }
    

    Then you can use it like this:

    var distinctItems = a.Distinct();
    

Best way to strip punctuation from a string

From an efficiency perspective, you're not going to beat

s.translate(None, string.punctuation)

For higher versions of Python use the following code:

s.translate(str.maketrans('', '', string.punctuation))

It's performing raw string operations in C with a lookup table - there's not much that will beat that but writing your own C code.

If speed isn't a worry, another option though is:

exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)

This is faster than s.replace with each char, but won't perform as well as non-pure python approaches such as regexes or string.translate, as you can see from the below timings. For this type of problem, doing it at as low a level as possible pays off.

Timing code:

import re, string, timeit

s = "string. With. Punctuation"
exclude = set(string.punctuation)
table = string.maketrans("","")
regex = re.compile('[%s]' % re.escape(string.punctuation))

def test_set(s):
    return ''.join(ch for ch in s if ch not in exclude)

def test_re(s):  # From Vinko's solution, with fix.
    return regex.sub('', s)

def test_trans(s):
    return s.translate(table, string.punctuation)

def test_repl(s):  # From S.Lott's solution
    for c in string.punctuation:
        s=s.replace(c,"")
    return s

print "sets      :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)
print "regex     :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)
print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)
print "replace   :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)

This gives the following results:

sets      : 19.8566138744
regex     : 6.86155414581
translate : 2.12455511093
replace   : 28.4436721802

Can you blur the content beneath/behind a div?

you can do this with css3, this blurs the whole element

div (or whatever element) {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

Fiddle: http://jsfiddle.net/H4DU4/

How to get RegistrationID using GCM in android

In response to your first question: Yes, you have to run a server app to send the messages, as well as a client app to receive them.

In response to your second question: Yes, every application needs its own API key. This key is for your server app, not the client.

Html code as IFRAME source rather than a URL

I have a page it loads an HTML body from MYSQL I want to present that code in a frame so it renders it self independent of the rest of the page and in the confines of that specific bordering.

An object with a unencoded dataUri might have also fit your need if it was only to load a portion of data text:

The HTML <object> element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin.

_x000D_
_x000D_
body {display:flex;min-height:25em;}
p {margin:auto;}
object {margin:0 auto;background:lightgray;}
_x000D_
<p>here My uploaded content: </p>
<object data='data:text/html,
  <style>

.table {
  display: table;
  text-align:center;
  width:100%;
  height:100%;
}

.table > * {
  display: table-row;
}

.table > main {
  display: table-cell;
  height: 100%;
  vertical-align: middle;
}
</style>


<div class="table">
  <header>
    <h1>Title</h1>
    <p>subTitle</p>
  </header>

  <main>
    <p>Collection</p>
    <p>Version</p>
    <p>Id</p>
  </main>

  <footer>
    <p>Edition</p>
  </footer>'>

</object>
_x000D_
_x000D_
_x000D_

But keeping your Iframe idea, You could also load your HTML inside your iframe tag and set it as the srcdoc value.You should not have to mind about quotes nor turning it into a dataUri but only mind to fire onload once.

The HTML Inline Frame element (<iframe>) represents a nested browsing context, embedding another HTML page into the current one.

Both iframe below will render the same, one require extra javascript.

example loading a full document :

_x000D_
_x000D_
body {
  display: flex;
  min-height: 25em;
}

p {
  margin: auto;
}

iframe {
  margin: 0 auto;
  min-height: 100%;
  background:lightgray;
}
_x000D_
<p>here my uploaded contents =>:</p>
  <iframe srcdoc='<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <style>
html, body {
  height: 100%;
  margin:0;
}

body.table {
  display: table;
  text-align:center;
  width:100%;
}

.table > * {
  display: table-row;
}

.table > main {
  display: table-cell;
  height: 100%;
  vertical-align: middle;
}
</style>
</head>

<body class="table">
  <header>
    <h1>title</h1>
    <p>injected via <code>srcdoc</code></p>
  </header>

  <main>
    <p>Collection</p>
    <p>Version</p>
    <p>Id</p>
  </main>

  <footer>
    <p>Edition</p>
  </footer>
</body>
</html>'>

</iframe>

  <iframe onload="this.setAttribute('srcdoc', this.innerHTML);this.setAttribute('onload','')">
    <!-- below html loaded -->
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>
      <title>Test</title>
      <style>
        html,
        body {
          height: 100%;
          margin: 0;
          overflow:auto;
        }
        
        body.table {
          display: table;
          text-align: center;
          width: 100%;
        }
        
        .table>* {
          display: table-row;
        }
        
        .table>main {
          display: table-cell;
          height: 100%;
          vertical-align: middle;
        }
      </style>
    </head>

    <body class="table">
      <header>
        <h1>Title</h1>
        <p>Injected from <code>innerHTML</code></p>
      </header>

      <main>
        <p>Collection</p>
        <p>Version</p>
        <p>Id</p>
      </main>

      <footer>
        <p>Edition</p>
      </footer>
    </body>

    </html>
    </iframe>
_x000D_
_x000D_
_x000D_

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

You'll also get this error if you forget a new:

String s = String();

versus

String s = new String();

because the call without the new keyword will try and look for a (local) method called String without arguments - and that method signature is likely not defined.

Add new column with foreign key constraint in one command

In Oracle :

ALTER TABLE one ADD two_id INTEGER CONSTRAINT Fk_two_id REFERENCES two(id);

Move column by name to front of table in pandas

You can use the df.reindex() function in pandas. df is

                      Net  Upper   Lower  Mid  Zsore
Answer option                                      
More than once a day  0%  0.22%  -0.12%    2     65
Once a day            0%  0.32%  -0.19%    3     45
Several times a week  2%  2.45%   1.10%    4     78
Once a week           1%  1.63%  -0.40%    6     65

define an list of column names

cols = df.columns.tolist()
cols
Out[13]: ['Net', 'Upper', 'Lower', 'Mid', 'Zsore']

move the column name to wherever you want

cols.insert(0, cols.pop(cols.index('Mid')))
cols
Out[16]: ['Mid', 'Net', 'Upper', 'Lower', 'Zsore']

then use df.reindex() function to reorder

df = df.reindex(columns= cols)

out put is: df

                      Mid  Upper   Lower Net  Zsore
Answer option                                      
More than once a day    2  0.22%  -0.12%  0%     65
Once a day              3  0.32%  -0.19%  0%     45
Several times a week    4  2.45%   1.10%  2%     78
Once a week             6  1.63%  -0.40%  1%     65

Is there a date format to display the day of the week in java?

tl;dr

LocalDate.of( 2018 , Month.JANUARY , 23 )
         .format( DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US )  )

java.time

The modern approach uses the java.time classes.

LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;

Note how we specify a Locale such as Locale.CANADA_FRENCH to determine the human language used to translate the name of the day.

DateTimeFormatter f = DateTimeFormatter.ofPattern( “uuuu-MM-EEE” , Locale.US ) ;
String output = ld.format( f ) ;

ISO 8601

By the way, you may be interested in the standard ISO 8601 week numbering scheme: yyyy-Www-d.

2018-W01-2

Week # 1 has the first Thursday of the calendar-year. Week starts on a Monday. A year has either 52 or 53 weeks. The last/first few days of a calendar-year may land in the next/previous week-based-year.

The single digit on the end is day-of-week, 1-7 for Monday-Sunday.

Add the ThreeTen-Extra library class to your project for the YearWeek class.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Python function pointer

Why not store the function itself? myvar = mypackage.mymodule.myfunction is much cleaner.

Substitute multiple whitespace with single whitespace in Python

A regular expression can be used to offer more control over the whitespace characters that are combined.

To match unicode whitespace:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"\s+")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()

To match ASCII whitespace only:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)

Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.

Reference:

About \s:

For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.

About re.ASCII:

Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).

strip() will remote any leading and trailing whitespaces.

Scatter plot and Color mapping in Python

Here is an example

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)

plt.scatter(x, y, c=t)
plt.show()

Here you are setting the color based on the index, t, which is just an array of [1, 2, ..., 100]. enter image description here

Perhaps an easier-to-understand example is the slightly simpler

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
plt.scatter(x, y, c=t)
plt.show()

enter image description here

Note that the array you pass as c doesn't need to have any particular order or type, i.e. it doesn't need to be sorted or integers as in these examples. The plotting routine will scale the colormap such that the minimum/maximum values in c correspond to the bottom/top of the colormap.

Colormaps

You can change the colormap by adding

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.cmap_name)

Importing matplotlib.cm is optional as you can call colormaps as cmap="cmap_name" just as well. There is a reference page of colormaps showing what each looks like. Also know that you can reverse a colormap by simply calling it as cmap_name_r. So either

plt.scatter(x, y, c=t, cmap=cm.cmap_name_r)
# or
plt.scatter(x, y, c=t, cmap="cmap_name_r")

will work. Examples are "jet_r" or cm.plasma_r. Here's an example with the new 1.5 colormap viridis:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')
plt.show()

enter image description here

Colorbars

You can add a colorbar by using

plt.scatter(x, y, c=t, cmap='viridis')
plt.colorbar()
plt.show()

enter image description here

Note that if you are using figures and subplots explicitly (e.g. fig, ax = plt.subplots() or ax = fig.add_subplot(111)), adding a colorbar can be a bit more involved. Good examples can be found here for a single subplot colorbar and here for 2 subplots 1 colorbar.

How to Handle Button Click Events in jQuery?

<script type="text/javascript">

    $(document).ready(function() {

    $("#Button1").click(function() {

        alert("hello");

    });

    }
    );

</script>

String.contains in Java

no real explanation is given by Java (in either JavaDoc or much coveted code comments), but looking at the code, it seems that this is magic:

calling stack:

String.indexOf(char[], int, int, char[], int, int, int) line: 1591  
String.indexOf(String, int) line: 1564  
String.indexOf(String) line: 1546   
String.contains(CharSequence) line: 1934    

code:

/**
 * Code shared by String and StringBuffer to do searches. The
 * source is the character array being searched, and the target
 * is the string being searched for.
 *
 * @param   source       the characters being searched.
 * @param   sourceOffset offset of the source string.
 * @param   sourceCount  count of the source string.
 * @param   target       the characters being searched for.
 * @param   targetOffset offset of the target string.
 * @param   targetCount  count of the target string.
 * @param   fromIndex    the index to begin searching from.
 */
static int indexOf(char[] source, int sourceOffset, int sourceCount,
                   char[] target, int targetOffset, int targetCount,
                   int fromIndex) {
  if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
  }
      if (fromIndex < 0) {
        fromIndex = 0;
      }
  if (targetCount == 0) {//my comment: this is where it returns, the size of the 
    return fromIndex;    // incoming string is 0,  which is passed in as targetCount
  }                      // fromIndex is 0 as well, as the search starts from the 
                         // start of the source string
    ...//the rest of the method 

git pull keeping local changes

We can also try git pull with rebase

git pull --rebase origin dev

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

You could try Conditional Formatting available in the tool menu "Format -> Conditional Formatting".

TypeError: '<=' not supported between instances of 'str' and 'int'

When you use the input function it automatically turns it into a string. You need to go:

vote = int(input('Enter the name of the player you wish to vote for'))

which turns the input into a int type value

Get Windows version in a batch file

Have you tried using the wmic commands?

Try wmic os get version

This will give you the version number in a command line, then you just need to integrate into the batch file.

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

How can I make the cursor turn to the wait cursor?

Use this with WPF:

Cursor = Cursors.Wait;

// Your Heavy work here

Cursor = Cursors.Arrow;

Javascript variable access in HTML

Here you go: http://codepen.io/anon/pen/cKflA

Although, I must say that what you are asking to do is not a good way to do it. A good way is this: http://codepen.io/anon/pen/jlkvJ

Why call super() in a constructor?

We can Access SuperClass members using super keyword

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

// Here is a subclass, called Subclass, that overrides printMethod():

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    
    }
}

Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:

Printed in Superclass.
Printed in Subclass

How to check if current thread is not main thread

A simple Toast message works also as a quick check.

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

I don't want to sound too negative, but there are occasions when what you want is almost impossible without a lot of "artificial" tuning of page breaks.

If the callout falls naturally near the bottom of a page, and the figure falls on the following page, moving the figure back one page will probably displace the callout forward.

I would recommend (as far as possible, and depending on the exact size of the figures):

  • Place the figures with [t] (or [h] if you must)
  • Place the figures as near as possible to the "right" place (differs for [t] and [h])
  • Include the figures from separate files with \input, which will make them much easier to move around when you're doing the final tuning

In my experience, this is a big eater-up of non-available time (:-)


In reply to Jon's comment, I think this is an inherently difficult problem, because the LaTeX guys are no slouches. You may like to read Frank Mittelbach's paper.

psql: could not connect to server: No such file or directory (Mac OS X)

I've had to look up this post several times to solve this issue. There's another fix, which will also applies to similar issues with other running programs.

I just discovered you can use the following two commands.

$top

This will show all the currently running actions with their pid numbers. When you find postgres and the associated pid

$kill pid_number

C# code to validate email address

A simple one without using Regex (which I don't like for its poor readability):

bool IsValidEmail(string email)
{
    string emailTrimed = email.Trim();

    if (!string.IsNullOrEmpty(emailTrimed))
    {
        bool hasWhitespace = emailTrimed.Contains(" ");

        int indexOfAtSign = emailTrimed.LastIndexOf('@');

        if (indexOfAtSign > 0 && !hasWhitespace)
        {
            string afterAtSign = emailTrimed.Substring(indexOfAtSign + 1);

            int indexOfDotAfterAtSign = afterAtSign.LastIndexOf('.');

            if (indexOfDotAfterAtSign > 0 && afterAtSign.Substring(indexOfDotAfterAtSign).Length > 1)
                return true;
        }
    }

    return false;
}

Examples:

It is meant to be simple and therefore it doesn't deal with rare cases like emails with bracketed domains that contain spaces (typically allowed), emails with IPv6 addresses, etc.

Rendering HTML inside textarea

I have the same problem but in reverse, and the following solution. I want to put html from a div in a textarea (so I can edit some reactions on my website; I want to have the textarea in the same location.)

To put the content of this div in a textarea I use:

_x000D_
_x000D_
var content = $('#msg500').text();_x000D_
$('#msg500').wrapInner('<textarea>' + content + '</textarea>');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="msg500">here some <strong>html</strong> <i>tags</i>.</div>
_x000D_
_x000D_
_x000D_

What is the difference between Release and Debug modes in Visual Studio?

Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager... (it's on the Build menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.

Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.

The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #defines and a few other things. For a C++ project, you get a much bigger variety of things to tweak.

In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.

Making href (anchor tag) request POST instead of GET?

To do POST you'll need to have a form.

<form action="employee.action" method="post">
    <input type="submit" value="Employee1" />
</form>

There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.

Some tricks: Make a link use POST instead of GET and How do you post data with a link

Edit: to load response on a frame you can target your form to your frame:

<form action="employee.action" method="post" target="myFrame">

How to combine two lists in R

I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:

combineListsAsOne <-function(list1, list2){
  n <- c()
  for(x in list1){
    n<-c(n, x)
  }
  for(y in list2){
    n<-c(n, y)
  }
  return(n)
}

It just creates a new list and adds items from two supplied lists to create one.

Disable Scrolling on Body

To accomplish this, add 2 CSS properties on the <body> element.

body {
   height: 100%;
   overflow-y: hidden;
}

These days there are many news websites which require users to create an account. Typically they will give full access to the page for about a second, and then they show a pop-up, and stop users from scrolling down.

The Telegraph

How to enable local network users to access my WAMP sites?

I have some experiences in Wamp 3.0 and Apache 2.4 .

After all works do this steps:

1- Disable nod32.

2- Add this line to <VirtualHost *:80> block in httpd-vhosts.conf file:

Require ip 192.168.100 #client ip, allow 192.168.100.### ip's access

Setting Windows PowerShell environment variables

If, some time during a PowerShell session, you need to append to the PATH environment variable temporarily, you can do it this way:

$env:Path += ";C:\Program Files\GnuWin32\bin"

How to append a char to a std::string?

int main()
{
  char d = 'd';
  std::string y("Hello worl");

  y += d;
  y.push_back(d);
  y.append(1, d); //appending the character 1 time
  y.insert(y.end(), 1, d); //appending the character 1 time
  y.resize(y.size()+1, d); //appending the character 1 time
  y += std::string(1, d); //appending the character 1 time
}

Note that in all of these examples you could have used a character literal directly: y += 'd';.

Your second example almost would have worked, for unrelated reasons. char d[1] = { 'd'}; didn't work, but char d[2] = { 'd'}; (note the array is size two) would have been worked roughly the same as const char* d = "d";, and a string literal can be appended: y.append(d);.

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

How do you check in python whether a string contains only numbers?

Use string isdigit function:

>>> s = '12345'
>>> s.isdigit()
True
>>> s = '1abc'
>>> s.isdigit()
False

Making a <button> that's a link in HTML

You have three options:

  • Style links to look like buttons using CSS.

    Just look at the light blue "tags" under your question.

    It is possible, even to give them a depressed appearance when clicked (using pseudo-classes like :active), without any scripting. Lots of major sites, such as Google, are starting to make buttons out of CSS styles these days anyway, scripting or not.

  • Put a separate <form> element around each one.

    As you mentioned in the question. Easy and will definitely work without Javascript (or even CSS). But it adds a little extra code which may look untidy.

  • Rely on Javascript.

    Which is what you said you didn't want to do.

How to add months to a date in JavaScript?

Corrected as of 25.06.2019:

var newDate = new Date(date.setMonth(date.getMonth()+8));

Old From here:

var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8);

Git fetch remote branch

The title and the question are confused:

  • Git fetch remote branch
  • how can my colleague pull that branch specifically.

If the question is, how can I get a remote branch to work with, or how can I Git checkout a remote branch?, a simpler solution is:

With Git (>= 1.6.6) you are able to use:

git checkout <branch_name>

If local <branch_name> is not found, but there does exist a tracking branch in exactly one remote with a matching name, treat it as equivalent to:

git checkout -b <branch_name> --track <remote>/<branch_name>

See documentation for Git checkout

For your friend:

$ git checkout discover
Branch discover set up to track remote branch discover
Switched to a new branch 'discover'

What is a good Hash Function?

For doing "normal" hash table lookups on basically any kind of data - this one by Paul Hsieh is the best I've ever used.

http://www.azillionmonkeys.com/qed/hash.html

If you care about cryptographically secure or anything else more advanced, then YMMV. If you just want a kick ass general purpose hash function for a hash table lookup, then this is what you're looking for.

How to find the php.ini file used by the command line?

On OSX Mavericks, running:

$ php -i | grep 'Configuration File'

Returned:

Configuration File (php.ini) Path => /etc
Loaded Configuration File:         (none)

In the /etc/ directory was:

php.ini.default

(as well as php-fpm.conf.default)

I was able to copy php.ini.default to php.ini, add date.timezone = "US/Central" to the top (right below [php]), and the problem is solved.

(At least the error message is gone.)

How do I print the key-value pairs of a dictionary in python

In addition to ways already mentioned.. can use 'viewitems', 'viewkeys', 'viewvalues'

>>> d = {320: 1, 321: 0, 322: 3}
>>> list(d.viewitems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.viewkeys())
[320, 321, 322]
>>> list(d.viewvalues())
[1, 0, 3]

Or

>>> list(d.iteritems())
[(320, 1), (321, 0), (322, 3)]
>>> list(d.iterkeys())
[320, 321, 322]
>>> list(d.itervalues())
[1, 0, 3]

or using itemgetter

>>> from operator import itemgetter
>>> map(itemgetter(0), dd.items())     ####  for keys
['323', '332']
>>> map(itemgetter(1), dd.items())     ####  for values
['3323', 232]

Perform .join on value in array of objects

If object and dynamical keys: "applications\":{\"1\":\"Element1\",\"2\":\"Element2\"}

Object.keys(myObject).map(function (key, index) {
    return myObject[key]
}).join(', ')

*ngIf and *ngFor on same element causing error

Table below only lists items that have a "beginner" value set. Requires both the *ngFor and the *ngIf to prevent unwanted rows in html.

Originally had *ngIf and *ngFor on the same <tr> tag, but doesn't work. Added a <div> for the *ngFor loop and placed *ngIf in the <tr> tag, works as expected.

<table class="table lessons-list card card-strong ">
  <tbody>
  <div *ngFor="let lesson of lessons" >
   <tr *ngIf="lesson.isBeginner">
    <!-- next line doesn't work -->
    <!-- <tr *ngFor="let lesson of lessons" *ngIf="lesson.isBeginner"> -->
    <td class="lesson-title">{{lesson.description}}</td>
    <td class="duration">
      <i class="fa fa-clock-o"></i>
      <span>{{lesson.duration}}</span>
    </td>
   </tr>
  </div>
  </tbody>

</table>

Merge PDF files

A slight variation using a dictionary for greater flexibility (e.g. sort, dedup):

import os
from PyPDF2 import PdfFileMerger
# use dict to sort by filepath or filename
file_dict = {}
for subdir, dirs, files in os.walk("<dir>"):
    for file in files:
        filepath = subdir + os.sep + file
        # you can have multiple endswith
        if filepath.endswith((".pdf", ".PDF")):
            file_dict[file] = filepath
# use strict = False to ignore PdfReadError: Illegal character error
merger = PdfFileMerger(strict=False)

for k, v in file_dict.items():
    print(k, v)
    merger.append(v)

merger.write("combined_result.pdf")

#1292 - Incorrect date value: '0000-00-00'

The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.

For more information read this.

Hope it helps.

Basic communication between two fragments

There is a simple way to implement communication between fragments of an activity using architectural components. Data can be passed between fragments of an activity using ViewModel and LiveData.

Fragments involved in communication need to use the same view model objects which is tied to activity life cycle. The view model object contains livedata object to which data is passed by one fragment and the second fragment listens for changes on LiveData and receives the data sent from fragment one.

For complete example see http://www.zoftino.com/passing-data-between-android-fragments-using-viewmodel

List of Timezone IDs for use with FindTimeZoneById() in C#?

And if you'd like a HTML select with the Windows time zones in:

<select>
<option value="Morocco Standard Time">(GMT) Casablanca</option>
<option value="GMT Standard Time">(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London</option>
<option value="Greenwich Standard Time">(GMT) Monrovia, Reykjavik</option>
<option value="W. Europe Standard Time">(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna</option>
<option value="Central Europe Standard Time">(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague</option>
<option value="Romance Standard Time">(GMT+01:00) Brussels, Copenhagen, Madrid, Paris</option>
<option value="Central European Standard Time">(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb</option>
<option value="W. Central Africa Standard Time">(GMT+01:00) West Central Africa</option>
<option value="Jordan Standard Time">(GMT+02:00) Amman</option>
<option value="GTB Standard Time">(GMT+02:00) Athens, Bucharest, Istanbul</option>
<option value="Middle East Standard Time">(GMT+02:00) Beirut</option>
<option value="Egypt Standard Time">(GMT+02:00) Cairo</option>
<option value="South Africa Standard Time">(GMT+02:00) Harare, Pretoria</option>
<option value="FLE Standard Time">(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius</option>
<option value="Israel Standard Time">(GMT+02:00) Jerusalem</option>
<option value="E. Europe Standard Time">(GMT+02:00) Minsk</option>
<option value="Namibia Standard Time">(GMT+02:00) Windhoek</option>
<option value="Arabic Standard Time">(GMT+03:00) Baghdad</option>
<option value="Arab Standard Time">(GMT+03:00) Kuwait, Riyadh</option>
<option value="Russian Standard Time">(GMT+03:00) Moscow, St. Petersburg, Volgograd</option>
<option value="E. Africa Standard Time">(GMT+03:00) Nairobi</option>
<option value="Georgian Standard Time">(GMT+03:00) Tbilisi</option>
<option value="Iran Standard Time">(GMT+03:30) Tehran</option>
<option value="Arabian Standard Time">(GMT+04:00) Abu Dhabi, Muscat</option>
<option value="Azerbaijan Standard Time">(GMT+04:00) Baku</option>
<option value="Mauritius Standard Time">(GMT+04:00) Port Louis</option>
<option value="Caucasus Standard Time">(GMT+04:00) Yerevan</option>
<option value="Afghanistan Standard Time">(GMT+04:30) Kabul</option>
<option value="Ekaterinburg Standard Time">(GMT+05:00) Ekaterinburg</option>
<option value="Pakistan Standard Time">(GMT+05:00) Islamabad, Karachi</option>
<option value="West Asia Standard Time">(GMT+05:00) Tashkent</option>
<option value="India Standard Time">(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi</option>
<option value="Sri Lanka Standard Time">(GMT+05:30) Sri Jayawardenepura</option>
<option value="Nepal Standard Time">(GMT+05:45) Kathmandu</option>
<option value="N. Central Asia Standard Time">(GMT+06:00) Almaty, Novosibirsk</option>
<option value="Central Asia Standard Time">(GMT+06:00) Astana, Dhaka</option>
<option value="Myanmar Standard Time">(GMT+06:30) Yangon (Rangoon)</option>
<option value="SE Asia Standard Time">(GMT+07:00) Bangkok, Hanoi, Jakarta</option>
<option value="North Asia Standard Time">(GMT+07:00) Krasnoyarsk</option>
<option value="China Standard Time">(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi</option>
<option value="North Asia East Standard Time">(GMT+08:00) Irkutsk, Ulaan Bataar</option>
<option value="Singapore Standard Time">(GMT+08:00) Kuala Lumpur, Singapore</option>
<option value="W. Australia Standard Time">(GMT+08:00) Perth</option>
<option value="Taipei Standard Time">(GMT+08:00) Taipei</option>
<option value="Tokyo Standard Time">(GMT+09:00) Osaka, Sapporo, Tokyo</option>
<option value="Korea Standard Time">(GMT+09:00) Seoul</option>
<option value="Yakutsk Standard Time">(GMT+09:00) Yakutsk</option>
<option value="Cen. Australia Standard Time">(GMT+09:30) Adelaide</option>
<option value="AUS Central Standard Time">(GMT+09:30) Darwin</option>
<option value="E. Australia Standard Time">(GMT+10:00) Brisbane</option>
<option value="AUS Eastern Standard Time">(GMT+10:00) Canberra, Melbourne, Sydney</option>
<option value="West Pacific Standard Time">(GMT+10:00) Guam, Port Moresby</option>
<option value="Tasmania Standard Time">(GMT+10:00) Hobart</option>
<option value="Vladivostok Standard Time">(GMT+10:00) Vladivostok</option>
<option value="Central Pacific Standard Time">(GMT+11:00) Magadan, Solomon Is., New Caledonia</option>
<option value="New Zealand Standard Time">(GMT+12:00) Auckland, Wellington</option>
<option value="Fiji Standard Time">(GMT+12:00) Fiji, Kamchatka, Marshall Is.</option>
<option value="Tonga Standard Time">(GMT+13:00) Nuku'alofa</option>
<option value="Azores Standard Time">(GMT-01:00) Azores</option>
<option value="Cape Verde Standard Time">(GMT-01:00) Cape Verde Is.</option>
<option value="Mid-Atlantic Standard Time">(GMT-02:00) Mid-Atlantic</option>
<option value="E. South America Standard Time">(GMT-03:00) Brasilia</option>
<option value="Argentina Standard Time">(GMT-03:00) Buenos Aires</option>
<option value="SA Eastern Standard Time">(GMT-03:00) Georgetown</option>
<option value="Greenland Standard Time">(GMT-03:00) Greenland</option>
<option value="Montevideo Standard Time">(GMT-03:00) Montevideo</option>
<option value="Newfoundland Standard Time">(GMT-03:30) Newfoundland</option>
<option value="Atlantic Standard Time">(GMT-04:00) Atlantic Time (Canada)</option>
<option value="SA Western Standard Time">(GMT-04:00) La Paz</option>
<option value="Central Brazilian Standard Time">(GMT-04:00) Manaus</option>
<option value="Pacific SA Standard Time">(GMT-04:00) Santiago</option>
<option value="Venezuela Standard Time">(GMT-04:30) Caracas</option>
<option value="SA Pacific Standard Time">(GMT-05:00) Bogota, Lima, Quito, Rio Branco</option>
<option value="Eastern Standard Time">(GMT-05:00) Eastern Time (US & Canada)</option>
<option value="US Eastern Standard Time">(GMT-05:00) Indiana (East)</option>
<option value="Central America Standard Time">(GMT-06:00) Central America</option>
<option value="Central Standard Time">(GMT-06:00) Central Time (US & Canada)</option>
<option value="Central Standard Time (Mexico)">(GMT-06:00) Guadalajara, Mexico City, Monterrey</option>
<option value="Canada Central Standard Time">(GMT-06:00) Saskatchewan</option>
<option value="US Mountain Standard Time">(GMT-07:00) Arizona</option>
<option value="Mountain Standard Time (Mexico)">(GMT-07:00) Chihuahua, La Paz, Mazatlan</option>
<option value="Mountain Standard Time">(GMT-07:00) Mountain Time (US & Canada)</option>
<option value="Pacific Standard Time">(GMT-08:00) Pacific Time (US & Canada)</option>
<option value="Pacific Standard Time (Mexico)">(GMT-08:00) Tijuana, Baja California</option>
<option value="Alaskan Standard Time">(GMT-09:00) Alaska</option>
<option value="Hawaiian Standard Time">(GMT-10:00) Hawaii</option>
<option value="Samoa Standard Time">(GMT-11:00) Midway Island, Samoa</option>
<option value="Dateline Standard Time">(GMT-12:00) International Date Line West</option>
</select>

And if you'd like to use it in C#.NET MVC in a Razor view:

var timezones = new List<SelectListItem> { 
new SelectListItem() { Value="", Text="Select timezone...", Selected = false },
new SelectListItem() { Value="Morocco Standard Time", Text="(GMT) Casablanca", Selected = false },
new SelectListItem() { Value="GMT Standard Time", Text="(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London", Selected = false },
new SelectListItem() { Value="Greenwich Standard Time", Text="(GMT) Monrovia, Reykjavik", Selected = false },
new SelectListItem() { Value="W. Europe Standard Time", Text="(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna", Selected = false },
new SelectListItem() { Value="Central Europe Standard Time", Text="(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague", Selected = false },
new SelectListItem() { Value="Romance Standard Time", Text="(GMT+01:00) Brussels, Copenhagen, Madrid, Paris", Selected = false },
new SelectListItem() { Value="Central European Standard Time", Text="(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb", Selected = false },
new SelectListItem() { Value="W. Central Africa Standard Time", Text="(GMT+01:00) West Central Africa", Selected = false },
new SelectListItem() { Value="Jordan Standard Time", Text="(GMT+02:00) Amman", Selected = false },
new SelectListItem() { Value="GTB Standard Time", Text="(GMT+02:00) Athens, Bucharest, Istanbul", Selected = false },
new SelectListItem() { Value="Middle East Standard Time", Text="(GMT+02:00) Beirut", Selected = false },
new SelectListItem() { Value="Egypt Standard Time", Text="(GMT+02:00) Cairo", Selected = false },
new SelectListItem() { Value="South Africa Standard Time", Text="(GMT+02:00) Harare, Pretoria", Selected = false },
new SelectListItem() { Value="FLE Standard Time", Text="(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius", Selected = false },
new SelectListItem() { Value="Israel Standard Time", Text="(GMT+02:00) Jerusalem", Selected = false },
new SelectListItem() { Value="E. Europe Standard Time", Text="(GMT+02:00) Minsk", Selected = false },
new SelectListItem() { Value="Namibia Standard Time", Text="(GMT+02:00) Windhoek", Selected = false },
new SelectListItem() { Value="Arabic Standard Time", Text="(GMT+03:00) Baghdad", Selected = false },
new SelectListItem() { Value="Arab Standard Time", Text="(GMT+03:00) Kuwait, Riyadh", Selected = false },
new SelectListItem() { Value="Russian Standard Time", Text="(GMT+03:00) Moscow, St. Petersburg, Volgograd", Selected = false },
new SelectListItem() { Value="E. Africa Standard Time", Text="(GMT+03:00) Nairobi", Selected = false },
new SelectListItem() { Value="Georgian Standard Time", Text="(GMT+03:00) Tbilisi", Selected = false },
new SelectListItem() { Value="Iran Standard Time", Text="(GMT+03:30) Tehran", Selected = false },
new SelectListItem() { Value="Arabian Standard Time", Text="(GMT+04:00) Abu Dhabi, Muscat", Selected = false },
new SelectListItem() { Value="Azerbaijan Standard Time", Text="(GMT+04:00) Baku", Selected = false },
new SelectListItem() { Value="Mauritius Standard Time", Text="(GMT+04:00) Port Louis", Selected = false },
new SelectListItem() { Value="Caucasus Standard Time", Text="(GMT+04:00) Yerevan", Selected = false },
new SelectListItem() { Value="Afghanistan Standard Time", Text="(GMT+04:30) Kabul", Selected = false },
new SelectListItem() { Value="Ekaterinburg Standard Time", Text="(GMT+05:00) Ekaterinburg", Selected = false },
new SelectListItem() { Value="Pakistan Standard Time", Text="(GMT+05:00) Islamabad, Karachi", Selected = false },
new SelectListItem() { Value="West Asia Standard Time", Text="(GMT+05:00) Tashkent", Selected = false },
new SelectListItem() { Value="India Standard Time", Text="(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi", Selected = false },
new SelectListItem() { Value="Sri Lanka Standard Time", Text="(GMT+05:30) Sri Jayawardenepura", Selected = false },
new SelectListItem() { Value="Nepal Standard Time", Text="(GMT+05:45) Kathmandu", Selected = false },
new SelectListItem() { Value="N. Central Asia Standard Time", Text="(GMT+06:00) Almaty, Novosibirsk", Selected = false },
new SelectListItem() { Value="Central Asia Standard Time", Text="(GMT+06:00) Astana, Dhaka", Selected = false },
new SelectListItem() { Value="Myanmar Standard Time", Text="(GMT+06:30) Yangon (Rangoon)", Selected = false },
new SelectListItem() { Value="SE Asia Standard Time", Text="(GMT+07:00) Bangkok, Hanoi, Jakarta", Selected = false },
new SelectListItem() { Value="North Asia Standard Time", Text="(GMT+07:00) Krasnoyarsk", Selected = false },
new SelectListItem() { Value="China Standard Time", Text="(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi", Selected = false },
new SelectListItem() { Value="North Asia East Standard Time", Text="(GMT+08:00) Irkutsk, Ulaan Bataar", Selected = false },
new SelectListItem() { Value="Singapore Standard Time", Text="(GMT+08:00) Kuala Lumpur, Singapore", Selected = false },
new SelectListItem() { Value="W. Australia Standard Time", Text="(GMT+08:00) Perth", Selected = false },
new SelectListItem() { Value="Taipei Standard Time", Text="(GMT+08:00) Taipei", Selected = false },
new SelectListItem() { Value="Tokyo Standard Time", Text="(GMT+09:00) Osaka, Sapporo, Tokyo", Selected = false },
new SelectListItem() { Value="Korea Standard Time", Text="(GMT+09:00) Seoul", Selected = false },
new SelectListItem() { Value="Yakutsk Standard Time", Text="(GMT+09:00) Yakutsk", Selected = false },
new SelectListItem() { Value="Cen. Australia Standard Time", Text="(GMT+09:30) Adelaide", Selected = false },
new SelectListItem() { Value="AUS Central Standard Time", Text="(GMT+09:30) Darwin", Selected = false },
new SelectListItem() { Value="E. Australia Standard Time", Text="(GMT+10:00) Brisbane", Selected = false },
new SelectListItem() { Value="AUS Eastern Standard Time", Text="(GMT+10:00) Canberra, Melbourne, Sydney", Selected = false },
new SelectListItem() { Value="West Pacific Standard Time", Text="(GMT+10:00) Guam, Port Moresby", Selected = false },
new SelectListItem() { Value="Tasmania Standard Time", Text="(GMT+10:00) Hobart", Selected = false },
new SelectListItem() { Value="Vladivostok Standard Time", Text="(GMT+10:00) Vladivostok", Selected = false },
new SelectListItem() { Value="Central Pacific Standard Time", Text="(GMT+11:00) Magadan, Solomon Is., New Caledonia", Selected = false },
new SelectListItem() { Value="New Zealand Standard Time", Text="(GMT+12:00) Auckland, Wellington", Selected = false },
new SelectListItem() { Value="Fiji Standard Time", Text="(GMT+12:00) Fiji, Kamchatka, Marshall Is.", Selected = false },
new SelectListItem() { Value="Tonga Standard Time", Text="(GMT+13:00) Nuku'alofa", Selected = false },
new SelectListItem() { Value="Azores Standard Time", Text="(GMT-01:00) Azores", Selected = false },
new SelectListItem() { Value="Cape Verde Standard Time", Text="(GMT-01:00) Cape Verde Is.", Selected = false },
new SelectListItem() { Value="Mid-Atlantic Standard Time", Text="(GMT-02:00) Mid-Atlantic", Selected = false },
new SelectListItem() { Value="E. South America Standard Time", Text="(GMT-03:00) Brasilia", Selected = false },
new SelectListItem() { Value="Argentina Standard Time", Text="(GMT-03:00) Buenos Aires", Selected = false },
new SelectListItem() { Value="SA Eastern Standard Time", Text="(GMT-03:00) Georgetown", Selected = false },
new SelectListItem() { Value="Greenland Standard Time", Text="(GMT-03:00) Greenland", Selected = false },
new SelectListItem() { Value="Montevideo Standard Time", Text="(GMT-03:00) Montevideo", Selected = false },
new SelectListItem() { Value="Newfoundland Standard Time", Text="(GMT-03:30) Newfoundland", Selected = false },
new SelectListItem() { Value="Atlantic Standard Time", Text="(GMT-04:00) Atlantic Time (Canada)", Selected = false },
new SelectListItem() { Value="SA Western Standard Time", Text="(GMT-04:00) La Paz", Selected = false },
new SelectListItem() { Value="Central Brazilian Standard Time", Text="(GMT-04:00) Manaus", Selected = false },
new SelectListItem() { Value="Pacific SA Standard Time", Text="(GMT-04:00) Santiago", Selected = false },
new SelectListItem() { Value="Venezuela Standard Time", Text="(GMT-04:30) Caracas", Selected = false },
new SelectListItem() { Value="SA Pacific Standard Time", Text="(GMT-05:00) Bogota, Lima, Quito, Rio Branco", Selected = false },
new SelectListItem() { Value="Eastern Standard Time", Text="(GMT-05:00) Eastern Time (US & Canada)", Selected = false },
new SelectListItem() { Value="US Eastern Standard Time", Text="(GMT-05:00) Indiana (East)", Selected = false },
new SelectListItem() { Value="Central America Standard Time", Text="(GMT-06:00) Central America", Selected = false },
new SelectListItem() { Value="Central Standard Time", Text="(GMT-06:00) Central Time (US & Canada)", Selected = false },
new SelectListItem() { Value="Central Standard Time (Mexico)", Text="(GMT-06:00) Guadalajara, Mexico City, Monterrey", Selected = false },
new SelectListItem() { Value="Canada Central Standard Time", Text="(GMT-06:00) Saskatchewan", Selected = false },
new SelectListItem() { Value="US Mountain Standard Time", Text="(GMT-07:00) Arizona", Selected = false },
new SelectListItem() { Value="Mountain Standard Time (Mexico)", Text="(GMT-07:00) Chihuahua, La Paz, Mazatlan", Selected = false },
new SelectListItem() { Value="Mountain Standard Time", Text="(GMT-07:00) Mountain Time (US & Canada)", Selected = false },
new SelectListItem() { Value="Pacific Standard Time", Text="(GMT-08:00) Pacific Time (US & Canada)", Selected = false },
new SelectListItem() { Value="Pacific Standard Time (Mexico)", Text="(GMT-08:00) Tijuana, Baja California", Selected = false },
new SelectListItem() { Value="Alaskan Standard Time", Text="(GMT-09:00) Alaska", Selected = false },
new SelectListItem() { Value="Hawaiian Standard Time", Text="(GMT-10:00) Hawaii", Selected = false },
new SelectListItem() { Value="Samoa Standard Time", Text="(GMT-11:00) Midway Island, Samoa", Selected = false },
new SelectListItem() { Value="Dateline Standard Time", Text="(GMT-12:00) International Date Line West", Selected = false }
}

Although for Razor you can of course just generate the options by looping through TimeZoneInfo.GetSystemTimeZones()

LIKE vs CONTAINS on SQL Server

Also try changing from this:

    SELECT * FROM table WHERE Contains(Column, "test") > 0;

To this:

    SELECT * FROM table WHERE Contains(Column, '"*test*"') > 0;

The former will find records with values like "this is a test" and "a test-case is the plan".

The latter will also find records with values like "i am testing this" and "this is the greatest".

How to implement a simple scenario the OO way

You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.

ORA-00054: resource busy and acquire with NOWAIT specified

Depending on your situation, the table being locked may just be part of a normal operation & you don't want to just kill the blocking transaction. What you want to do is have your statement wait for the other resource. Oracle 11g has DDL timeouts which can be set to deal with this.

If you're dealing with 10g then you have to get more creative and write some PL/SQL to handle the re-try. Look at Getting around ORA-00054 in Oracle 10g This re-runs your statement when a resource_busy exception occurs.

Generate full SQL script from EF 5 Code First Migrations

For anyone using entity framework core ending up here. This is how you do it.

# Powershell / Package manager console
Script-Migration

# Cli 
dotnet ef migrations script

You can use the -From and -To parameter to generate an update script to update a database to a specific version.

Script-Migration -From 20190101011200_Initial-Migration -To 20190101021200_Migration-2

https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#generate-sql-scripts

There are several options to this command.

The from migration should be the last migration applied to the database before running the script. If no migrations have been applied, specify 0 (this is the default).

The to migration is the last migration that will be applied to the database after running the script. This defaults to the last migration in your project.

An idempotent script can optionally be generated. This script only applies migrations if they haven't already been applied to the database. This is useful if you don't exactly know what the last migration applied to the database was or if you are deploying to multiple databases that may each be at a different migration.

Where do I find old versions of Android NDK?

A way to find out old download links is to use internet archive tools like "Way back machine", https://archive.org/web/. You can browse older web pages versions and get the links you want.

For example, I needed to download the NDK rev 9, so I used this tool to access the NDK download page (https://developer.android.com/tools/sdk/ndk/) from March and the download link in March pointed to NDK rev 9.

What does a just-in-time (JIT) compiler do?

In the beginning, a compiler was responsible for turning a high-level language (defined as higher level than assembler) into object code (machine instructions), which would then be linked (by a linker) into an executable.

At one point in the evolution of languages, compilers would compile a high-level language into pseudo-code, which would then be interpreted (by an interpreter) to run your program. This eliminated the object code and executables, and allowed these languages to be portable to multiple operating systems and hardware platforms. Pascal (which compiled to P-Code) was one of the first; Java and C# are more recent examples. Eventually the term P-Code was replaced with bytecode, since most of the pseudo-operations are a byte long.

A Just-In-Time (JIT) compiler is a feature of the run-time interpreter, that instead of interpreting bytecode every time a method is invoked, will compile the bytecode into the machine code instructions of the running machine, and then invoke this object code instead. Ideally the efficiency of running object code will overcome the inefficiency of recompiling the program every time it runs.

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

I've found an issue happen to be with the Firewall. So, make sure your IP is whitelisted and the firewall does not block your connection. You can check connectivity with:

tsql -H somehost.com -p 1433

In my case, the output was:

Error 20009 (severity 9):
  Unable to connect: Adaptive Server is unavailable or does not exist
  OS error 111, "Connection refused"
There was a problem connecting to the server

Recommended way to embed PDF in HTML?

Our problem is that for legal reasons we are not allowed to temporarily store a PDF on the hard disk. In addition, the entire page should not be reloaded when displaying a PDF as Preview in the Browser.

First we tried PDF.jS. It worked with Base64 in the viewer for Firefox and Chrome. However, it was unacceptably slow for our PDF. IE/Edge didn't work at all.

We therefore tried it with a Base64 string in an HTML object tag. This again didn't work for IE/Edge (maybe the same problem as with PDF.js). In Chrome/Firefox/Safari again no problem. That's why we chose a hybrid solution. IE/Edge we use an IFrame and for all other browsers the object-tag.

The IFrame solution would of course also work for Chrome and co. The reason why we didn't use this solution for Chrome is that although the PDF is displayed correctly, Chrome makes a new request to the server as soon as you click on "download" in the preview. The required hidden-field pdfHelperTransferData (for sending our form data needed for PDF generation) is no longer set because the PDF is displayed in an IFrame. For this feature/bug see Chrome sends two requests when downloading a PDF (and cancels one of them).

Now the problem children IE9 and IE10 remain. For these we gave up a preview solution and simply send the document by clicking the preview button as a download to the user (instead of the preview). We have tried a lot but even if we had found a solution the extra effort for this tiny part of users would not have been worth the effort. You can find our solution for the download here: Download PDF without refresh with IFrame.

Our Javascript:

var transferData = getFormAsJson()
if (isMicrosoftBrowser()) {
        // Case IE / Edge (because doesn't recoginzie Pdf-Base64 use Iframe)
        var form = document.getElementById('pdf-helper-form');
        $("#pdfHelperTransferData").val(transferData);
        form.target = "iframe-pdf-shower";
        form.action = "serverSideFunctonWhichWritesPdfinResponse";
        form.submit();
 } else {
        // Case non IE use Object tag instead of iframe
        $.ajax({
            url: "serverSideFunctonWhichRetrivesPdfAsBase64",
            type: "post",
            data: { downloadHelperTransferData: transferData },
            success: function (result) {
                $("#object-pdf-shower").attr("data", result);
            }
        })
 }

Our HTML:

<div id="pdf-helper-hidden-container" style="display:none">
   <form id="pdf-helper-form" method="post">
        <input type="hidden" name="pdfHelperTransferData" id="pdfHelperTransferData" />
   </form>
</div>

<div id="pdf-wrapper" class="modal-content">
    <iframe id="iframe-pdf-shower" name="iframe-pdf-shower"></iframe>
    <object id="object-pdf-shower" type="application/pdf"></object>
</div>

To check the browser type for IE/Edge see here: How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript? I hope these findings will save someone else the time.

Ignoring directories in Git repositories on Windows

Create a file named .gitignore in your project's directory. Ignore directories by entering the directory name into the file (with a slash appended):

dir_to_ignore/

More information is here.

How can I convert a stack trace to a string?

Here is a version that is copy-pastable directly into code:

import java.io.StringWriter; 
import java.io.PrintWriter;

//Two lines of code to get the exception into a StringWriter
StringWriter sw = new StringWriter();
new Throwable().printStackTrace(new PrintWriter(sw));

//And to actually print it
logger.info("Current stack trace is:\n" + sw.toString());

Or, in a catch block

} catch (Throwable t) {
    StringWriter sw = new StringWriter();
    t.printStackTrace(new PrintWriter(sw));
    logger.info("Current stack trace is:\n" + sw.toString());
}

How to add more than one machine to the trusted hosts list using winrm

I prefer to work with the PSDrive WSMan:\.

Get TrustedHosts

Get-Item WSMan:\localhost\Client\TrustedHosts

Set TrustedHosts

provide a single, comma-separated, string of computer names

Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineA,machineB'

or (dangerous) a wild-card

Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*'

to append to the list, the -Concatenate parameter can be used

Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineC' -Concatenate

How to SFTP with PHP?

The ssh2 functions aren't very good. Hard to use and harder yet to install, using them will guarantee that your code has zero portability. My recommendation would be to use phpseclib, a pure PHP SFTP implementation.

How can I add 1 day to current date?

In my humble opinion the best way is to just add a full day in milliseconds, depending on how you factor your code it can mess up if your on the last day of the month.

for example Feb 28 or march 31.

Here is an example of how i would do it:

var current = new Date(); //'Mar 11 2015' current.getTime() = 1426060964567
var followingDay = new Date(current.getTime() + 86400000); // + 1 day in ms
followingDay.toLocaleDateString();

imo this insures accuracy

here is another example i Do not like that can work for you but not as clean that dose the above

var today = new Date('12/31/2015');
var tomorrow = new Date(today);
tomorrow.setDate(today.getDate()+1);
tomorrow.toLocaleDateString();

imho this === 'POOP'

So some of you have had gripes about my millisecond approach because of day light savings time. So Im going to bash this out. First, Some countries and states do not have Day light savings time. Second Adding exactly 24 hours is a full day. If the date number dose not change once a year but then gets fixed 6 months later i don't see a problem there. But for the purpose of being definite and having to deal with allot the evil Date() i have thought this through and now thoroughly hate Date. So this is my new Approach

var dd = new Date(); // or any date and time you care about 
var dateArray =  dd.toISOString().split('T')[0].split('-').concat( dd.toISOString().split('T')[1].split(':') );
// ["2016", "07", "04", "00", "17", "58.849Z"] at Z 

Now for the fun part!

var date = { 
    day: dateArray[2],
    month: dateArray[1],
    year: dateArray[0],
    hour: dateArray[3],
    minutes: dateArray[4],
    seconds:dateArray[5].split('.')[0],
    milliseconds: dateArray[5].split('.')[1].replace('Z','')
}

now we have our Official Valid international Date Object clearly written out at Zulu meridian. Now to change the date

  dd.setDate(dd.getDate()+1); // this gives you one full calendar date forward
  tomorrow.setDate(dd.getTime() + 86400000);// this gives your 24 hours into the future. do what you want with it.

How to configure log4j to only keep log files for the last seven days?

My script based on @dogbane's answer

/etc/cron.daily/hbase

#!/bin/sh
find /var/log/hbase -type f -name "phoenix-hbase-server.log.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]" -exec bzip2 {} ";"
find /var/log/hbase -type f -regex ".*.out.[0-9][0-9]?" -exec bzip2 {} ";"
find /var/log/hbase -type f -mtime +7 -name "*.bz2" -exec rm -f {} ";"

/etc/cron.daily/tomcat

#!/bin/sh
find /opt/tomcat/log/ -type f -mtime +1 -name "*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].*log" -exec bzip2 {} ";"
find /opt/tomcat/log/ -type f -mtime +1 -name "*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].txt" -exec bzip2 {} ";"
find /opt/tomcat/log/ -type f -mtime +7 -name "*.bz2" -exec rm -f {} ";"

because Tomcat rotate needs one day delay.

Core Data: Quickest way to delete all instances of an entity

The above answers give a good insight on how to delete the "Cars"

However, I want this answer to challenge the approach itself:

1- SQLite CoreData is a relational database. In this case, where there isn't any releation, I would advise against using CoreData and maybe using the file system instead, or keep things in memory.

2- In other examples, where "Car" entity have other relations, and therefore CoreData, I would advise against having 2000 cars as root entity. Instead I would give them a parent, let's say "CarsRepository" entity. Then you can give a one-to-many relationship to the "Car" entity, and just replace the relationship to point to the new cars when they are downloaded. Adding the right deletion rule to the relationships ensures the integrity of the model.

document.all vs. document.getElementById

document.all is a proprietary Microsoft extension to the W3C standard.

getElementById() is standard - use that.

However, consider if using a js library like jQuery would come in handy. For example, $("#id") is the jQuery equivalent for getElementById(). Plus, you can use more than just CSS3 selectors.

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

Using IQueryable with Linq

Marc Gravell's answer is very complete, but I thought I'd add something about this from the user's point of view, as well...


The main difference, from a user's perspective, is that, when you use IQueryable<T> (with a provider that supports things correctly), you can save a lot of resources.

For example, if you're working against a remote database, with many ORM systems, you have the option of fetching data from a table in two ways, one which returns IEnumerable<T>, and one which returns an IQueryable<T>. Say, for example, you have a Products table, and you want to get all of the products whose cost is >$25.

If you do:

 IEnumerable<Product> products = myORM.GetProducts();
 var productsOver25 = products.Where(p => p.Cost >= 25.00);

What happens here, is the database loads all of the products, and passes them across the wire to your program. Your program then filters the data. In essence, the database does a SELECT * FROM Products, and returns EVERY product to you.

With the right IQueryable<T> provider, on the other hand, you can do:

 IQueryable<Product> products = myORM.GetQueryableProducts();
 var productsOver25 = products.Where(p => p.Cost >= 25.00);

The code looks the same, but the difference here is that the SQL executed will be SELECT * FROM Products WHERE Cost >= 25.

From your POV as a developer, this looks the same. However, from a performance standpoint, you may only return 2 records across the network instead of 20,000....

Setting unique Constraint with fluent API?

Here is an extension method for setting unique indexes more fluently:

public static class MappingExtensions
{
    public static PrimitivePropertyConfiguration IsUnique(this PrimitivePropertyConfiguration configuration)
    {
        return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute { IsUnique = true }));
    }
}

Usage:

modelBuilder 
    .Entity<Person>() 
    .Property(t => t.Name)
    .IsUnique();

Will generate migration such as:

public partial class Add_unique_index : DbMigration
{
    public override void Up()
    {
        CreateIndex("dbo.Person", "Name", unique: true);
    }

    public override void Down()
    {
        DropIndex("dbo.Person", new[] { "Name" });
    }
}

Src: Creating Unique Index with Entity Framework 6.1 fluent API

Send email using the GMail SMTP server from a PHP page

Send Mail using phpMailer library through Gmail Please donwload library files from Github

<?php
/**
 * This example shows settings to use when sending via Google's Gmail servers.
 */
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');
require '../PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "[email protected]";
//Password to use for SMTP authentication
$mail->Password = "yourpassword";
//Set who the message is to be sent from
$mail->setFrom('[email protected]', 'First Last');
//Set an alternative reply-to address
$mail->addReplyTo('[email protected]', 'First Last');
//Set who the message is to be sent to
$mail->addAddress('[email protected]', 'John Doe');
//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__));
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');
//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

Get current scroll position of ScrollView in React Native

Try.

<ScrollView onScroll={this.handleScroll} />

And then:

handleScroll: function(event: Object) {
 console.log(event.nativeEvent.contentOffset.y);
},

Not able to start Genymotion device

I had this same issue and here are the specific configuration that I needed to get this to work.

First, go to the VirtualBox preferences -> Network.

enter image description here

enter image description here

enter image description here

For the "Host-only Networks" tab, focus on the vboxnet0.

enter image description here

Click the icon on the left that looks like a screwdriver. For the Adapter tab, fill in the IPv4 Network Address as 192.168.56.1 Fill in the IPv4 Network Mask as 255.255.255.0

enter image description here

For the DHCP Server tab, select the check box for Enable Server to enable the server Fill in the Server Address as 192.168.56.100 Fill in the Server Mask as 255.255.255.0 Fill in the Lower Address Bound as 192.168.56.101 Fill in the Upper Address Bound as 192.168.56.254

enter image description here

The DHCP server part is what was not correct for me and it fixed my problem.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Reset textbox value in javascript

I know this is an old post, but this may help clarify:

$('#searchField')
    .val('')// [property value] e.g. what is visible / will be submitted
    .attr('value', '');// [attribute value] e.g. <input value="preset" ...

Changing [attribute value] has no effect if there is a [property value]. (user || js altered input)

Checking for empty queryset in Django

The most efficient way (before django 1.2) is this:

if orgs.count() == 0:
    # no results
else:
    # alrigh! let's continue...

How to access my localhost from another PC in LAN?

Actualy you don't need an internet connection to use ip address. Each computer in LAN has an internal IP address you can discover by runing

ipconfig /all

in cmd.

You can use the ip address of the server (probabily something like 192.168.0.x or 10.0.0.x) to access the website remotely.

If you found the ip and still cannot access the website, it means WAMP is not configured to respond to that name ( what did you call me? 192.168.0.3? That's not my name. I'm Localhost ) and you have to modify ....../apache/config/httpd.conf

Listen *:80

Get value of multiselect box using jQuery or pure JS

You could do like this too.

<form action="ResultsDulith.php" id="intermediate" name="inputMachine[]" multiple="multiple" method="post">
    <select id="selectDuration" name="selectDuration[]" multiple="multiple"> 
        <option value="1 WEEK" >Last 1 Week</option>
        <option value="2 WEEK" >Last 2 Week </option>
        <option value="3 WEEK" >Last 3 Week</option>
         <option value="4 WEEK" >Last 4 Week</option>
          <option value="5 WEEK" >Last 5 Week</option>
           <option value="6 WEEK" >Last 6 Week</option>
    </select>
     <input type="submit"/> 
</form>

Then take the multiple selection from following PHP code below. It print the selected multiple values accordingly.

$shift=$_POST['selectDuration'];

print_r($shift);

How to install lxml on Ubuntu

For Ubuntu 14.04

sudo apt-get install python-lxml

worked for me.

Check if a number is odd or even in python

One of the simplest ways is to use de modulus operator %. If n % 2 == 0, then your number is even.

Hope it helps,