Programs & Examples On #Asa

Cisco ASA (Adaptive Security Appliance) is a family of security products from Cisco Systems. For Sybase ASA, use [tag:sybase-asa]

Why my regexp for hyphenated words doesn't work?

A couple of things:

  1. Your regexes need to be anchored by separators* or you'll match partial words, as is the case now
  2. You're not using the proper syntax for a non-capturing group. It's (?: not (:?

If you address the first problem, you won't need groups at all.

*That is, a blank or beginning/end of string.

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

I hope it will help someone else.

This error seems to occur also when you UNintentionally send an object to React child components.

Example of it is passing to child component new Date('....') as follows:

 const data = {name: 'ABC', startDate: new Date('2011-11-11')}
 ...
 <GenInfo params={data}/>

If you send it as value of a child component parameter you would be sending a complex Object and you may get the same error as stated above.

Check if you are passing something similar (that generates Object under the hood).

error: resource android:attr/fontVariationSettings not found

If you are updating to v28

change the compileSdkVersion to compileSdkVersion 28

How to solve npm install throwing fsevents warning on non-MAC OS?

npm i -f

I'd like to repost some comments from this thread, where you can read up on the issue and the issue was solved.

This is exactly Angular's issue. Current package.json requires fsevent as not optionalDependencies but devDependencies. This may be a problem for non-OSX users.

Sometimes

Even if you remove it from package.json npm i still fails because another module has it as a peer dep.

So

if npm-shrinkwrap.json is still there, please remove it or try npm i -f

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

Download latest version of postman from https://www.postman.com/downloads/ then after tar.gz file gets downloaded follow below commands

$ tar -xvzf Postman-linux-x64-7.27.1.tar.gz
$ cd Postman
$ ./Postman

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

Make sure you switch the SHELL first:

SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]

RUN [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 
RUN Invoke-WebRequest -UseBasicParsing -Uri  'https://github.com/git-for-windows/git/releases/download/v2.25.1.windows.1/Git-2.25.1-64-bit.exe' -OutFile 'outfile.exe'

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

Get all validation errors from Angular 2 FormGroup

For a large FormGroup tree, you can use lodash to clean up the tree and get a tree of just the controls with errors. This is done by recurring through child controls (e.g. using allErrors(formGroup)), and pruning any fully-valid sub groups of controls:

private isFormGroup(control: AbstractControl): control is FormGroup {
  return !!(<FormGroup>control).controls;
}

// Returns a tree of any errors in control and children of control
allErrors(control: AbstractControl): any {
  if (this.isFormGroup(control)) {
    const childErrors = _.mapValues(control.controls, (childControl) => {
      return this.allErrors(childControl);
    });

    const pruned = _.omitBy(childErrors, _.isEmpty);
    return _.isEmpty(pruned) ? null : pruned;
  } else {
    return control.errors;
  }
}

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

C++ programs are translated to assembly programs during the generation of machine code from the source code. It would be virtually wrong to say assembly is slower than C++. Moreover, the binary code generated differs from compiler to compiler. So a smart C++ compiler may produce binary code more optimal and efficient than a dumb assembler's code.

However I believe your profiling methodology has certain flaws. The following are general guidelines for profiling:

  1. Make sure your system is in its normal/idle state. Stop all running processes (applications) that you started or that use CPU intensively (or poll over the network).
  2. Your datasize must be greater in size.
  3. Your test must run for something more than 5-10 seconds.
  4. Do not rely on just one sample. Perform your test N times. Collect results and calculate the mean or median of the result.

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

By converting the matrix to array by using

n12 = np.squeeze(np.asarray(n2))

X12 = np.squeeze(np.asarray(x1))

solved the issue.

How to unpack an .asar file?

It is possible to upack without node installed using the following 7-Zip plugin:
http://www.tc4shell.com/en/7zip/asar/

Thanks @MayaPosch for mentioning that in this comment.

Normalizing images in OpenCV

The other answers normalize an image based on the entire image. But if your image has a predominant color (such as black), it will mask out the features that you're trying to enhance since it will not be as pronounced. To get around this limitation, we can normalize the image based on a subsection region of interest (ROI). Essentially we will normalize based on the section of the image that we want to enhance instead of equally treating each pixel with the same weight. Take for instance this earth image:

Input image -> Normalization based on entire image

If we want to enhance the clouds by normalizing based on the entire image, the result will not be very sharp and will be over saturated due to the black background. The features to enhance are lost. So to obtain a better result we can crop a ROI, normalize based on the ROI, and then apply the normalization back onto the original image. Say we crop the ROI highlighted in green:

This gives us this ROI

The idea is to calculate the mean and standard deviation of the ROI and then clip the frame based on the lower and upper range. In addition, we could use an offset to dynamically adjust the clip intensity. From here we normalize the original image to this new range. Here's the result:

Before -> After

Code

import cv2
import numpy as np

# Load image as grayscale and crop ROI
image = cv2.imread('1.png', 0)
x, y, w, h = 364, 633, 791, 273
ROI = image[y:y+h, x:x+w]

# Calculate mean and STD
mean, STD  = cv2.meanStdDev(ROI)

# Clip frame to lower and upper STD
offset = 0.2
clipped = np.clip(image, mean - offset*STD, mean + offset*STD).astype(np.uint8)

# Normalize to range
result = cv2.normalize(clipped, clipped, 0, 255, norm_type=cv2.NORM_MINMAX)

cv2.imshow('image', image)
cv2.imshow('ROI', ROI)
cv2.imshow('result', result)
cv2.waitKey()

The difference between normalizing based on the entire image vs a specific section of the ROI can be visualized by applying a heatmap to the result. Notice the difference on how the clouds are defined.

Input image -> heatmap

Normalized on entire image -> heatmap

Normalized on ROI -> heatmap

Heatmap code

import matplotlib.pyplot as plt
import numpy as np
import cv2

image = cv2.imread('result.png', 0)
colormap = plt.get_cmap('inferno')
heatmap = (colormap(image) * 2**16).astype(np.uint16)[:,:,:3]
heatmap = cv2.cvtColor(heatmap, cv2.COLOR_RGB2BGR)

cv2.imshow('image', image)
cv2.imshow('heatmap', heatmap)
cv2.waitKey()

Note: The ROI bounding box coordinates were obtained using how to get ROI Bounding Box Coordinates without Guess & Check and heatmap code was from how to convert a grayscale image to heatmap image with Python OpenCV

Iterating over Typescript Map

You could use Map.prototype.forEach((value, key, map) => void, thisArg?) : void instead

Use it like this:

myMap.forEach((value: boolean, key: string) => {
    console.log(key, value);
});

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

After reviewing MySQL 5.7 changes, MySql stopped supporting zero values in date / datetime.

It's incorrect to use zeros in date or in datetime, just put null instead of zeros.

docker unauthorized: authentication required - upon push with successful login

Make sure your docker repositry name matches your local docker repo name. e.g lets say if you local repo name "kavashgar/nodjsapp"

then your should also have a repo names "kavashgar" in docker hub

Install pip in docker

Try this:

  1. Uncomment the following line in /etc/default/docker DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"
  2. Restart the Docker service sudo service docker restart
  3. Delete any images which have cached the invalid DNS settings.
  4. Build again and the problem should be solved.

From this question.

How to convert an Image to base64 string in java?

I think you might want:

String encodedFile = Base64.getEncoder().encodeToString(bytes);

How to extend / inherit components?

Let us understand some key limitations & features on Angular’s component inheritance system.

The component only inherits the class logic:

  • All meta-data in the @Component decorator is not inherited.
  • Component @Input properties and @Output properties are inherited.
  • Component lifecycle is not inherited.

These features are very important to have in mind so let us examine each one independently.

The Component only inherits the class logic

When you inherit a Component, all logic inside is equally inherited. It is worth noting that only public members are inherited as private members are only accessible in the class that implements them.

All meta-data in the @Component decorator is not inherited

The fact that no meta-data is inherited might seem counter-intuitive at first but, if you think about this it actually makes perfect sense. If you inherit from a Component say (componentA), you would not want the selector of ComponentA, which you are inheriting from to replace the selector of ComponentB which is the class that is inheriting. The same can be said for the template/templateUrl as well as the style/styleUrls.

Component @Input and @Output properties are inherited

This is another feature that I really love about component Inheritance in Angular. In a simple sentence, whenever you have a custom @Input and @Output property, these properties get inherited.

Component lifecycle is not inherited

This part is the one that is not so obvious especially to people who have not extensively worked with OOP principles. For example, say you have ComponentA which implements one of Angular’s many lifecycle hooks like OnInit. If you create ComponentB and inherit ComponentA, the OnInit lifecycle from ComponentA won't fire until you explicitly call it even if you do have this OnInit lifecycle for ComponentB.

Calling Super/Base Component Methods

In order to have the ngOnInit() method from ComponentA fire, we need to use the super keyword and then call the method we need which in this case is ngOnInit. The super keyword refers to the instance of the component that is being inherited from which in this case will be ComponentA.

TypeScript for ... of with index / key?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries

for (var [key, item] of someArray.entries()) { ... }

In TS this requires targeting ES2015 since it requires the runtime to support iterators, which ES5 runtimes don't. You can of course use something like Babel to make the output work on ES5 runtimes.

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

The following worked for me

import java.time.*;
import java.time.format.*;

public class Times {

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

and gave me output as

2012-02-22T02:06:58.147

How to set menu to Toolbar in Android

Here is a fuller answer as a reference to future visitors. I usually use a support toolbar but it works just as well either way.

enter image description here

1. Make a menu xml

This is going to be in res/menu/main_menu.

  • Right click the res folder and choose New > Android Resource File.
  • Type main_menu for the File name.
  • Choose Menu for the Resource type.

Paste in the following content as a starter.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_add"
        android:icon="@drawable/ic_add"
        app:showAsAction="ifRoom"
        android:title="Add">
    </item>
    <item
        android:id="@+id/action_settings"
        app:showAsAction="never"
        android:title="Settings">
    </item>
</menu>

You can right click res and choose New image asset to create the ic_add icon.

2. Inflate the menu

In your activity add the following method.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;
}

3. Handle menu clicks

Also in your Activity, add the following method:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.action_add:
            addSomething();
            return true;
        case R.id.action_settings:
            startSettings();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Further reading

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:

[A] JObject isn't the elementary base type of everything in JSON.net, but JToken is. So even though you could say,

object i = new int[0];

in C#, you can't say,

JObject i = JObject.Parse("[0, 0, 0]");

in JSON.net.

What you want is JArray.Parse, which will accept the array you're passing it (denoted by the opening [ in your API response). This is what the "StartArray" in the error message is telling you.

As for what happened when you used JArray, you're using arr instead of obj:

var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);

Swap that, and I believe it should work.

Although I'd be tempted to deserialize arr directly as an IEnumerable<LocationData>, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.

Angular 2 router no base href set

Check your index.html. If you have accidentally removed the following part, include it and it will be fine

<base href="/">

<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

npm install -g less does not work: EACCES: permission denied

I have tried all the suggested solutions but nothing worked.

I am using macOS Catalina 10.15.3

Go to /usr/local/

Select bin folder > Get Info

Add your user to Sharing & Permissions. Read & Write Permissions. enter image description here

And go to terminal and run npm install -g @ionic/cli

It has helped me.

Convert list or numpy array of single element to float in python

np.asscalar(a) is deprecated since NumPy v1.16, use a.item() instead.

For example:

a = np.array([[0.6813]])
print(a.item())

gives:

0.6813

How to convert a DataFrame back to normal RDD in pyspark?

@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.

Try this:

rdd = df.rdd.map(tuple)

or

rdd = df.rdd.map(list)

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

In my case I had inherited from the IdentityDbContext correctly (with my own custom types and key defined) but had inadvertantly removed the call to the base class's OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder); // I had removed this
    /// Rest of on model creating here.
}

Which then fixed up my missing indexes from the identity classes and I could then generate migrations and enable migrations appropriately.

How to set up a Web API controller for multipart/form-data

You're getting HTTP 415 "The request entity's media type 'multipart/form-data' is not supported for this resource." because you haven't mention the correct content type in your request.

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

I was getting this same warning everytime I was doing 'maven clean'. I found the solution :

Step - 1 Right click on your project in Eclipse

Step - 2 Click Properties

Step - 3 Select Maven in the left hand side list.

Step - 4 You will notice "pom.xml" in the Active Maven Profiles text box on the right hand side. Clear it and click Apply.

Below is the screen shot :

Properties dialog box

Hope this helps. :)

Check if an element has event listener on it. No jQuery

Nowadays (2016) in Chrome Dev Tools console, you can quickly execute this function below to show all event listeners that have been attached to an element.

getEventListeners(document.querySelector('your-element-selector'));

Creating a SearchView that looks like the material design guidelines

The following will create a SearchView identical to the one in Gmail and add it to the given Toolbar. You'll just have to implement your own "ViewUtil.convertDpToPixel" method.

private SearchView createMaterialSearchView(Toolbar toolbar, String hintText) {

    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayShowTitleEnabled(false);

    SearchView searchView = new SearchView(this);
    searchView.setIconifiedByDefault(false);
    searchView.setMaxWidth(Integer.MAX_VALUE);
    searchView.setMinimumHeight(Integer.MAX_VALUE);
    searchView.setQueryHint(hintText);

    int rightMarginFrame = 0;
    View frame = searchView.findViewById(getResources().getIdentifier("android:id/search_edit_frame", null, null));
    if (frame != null) {
        LinearLayout.LayoutParams frameParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        rightMarginFrame = ((LinearLayout.LayoutParams) frame.getLayoutParams()).rightMargin;
        frameParams.setMargins(0, 0, 0, 0);
        frame.setLayoutParams(frameParams);
    }

    View plate = searchView.findViewById(getResources().getIdentifier("android:id/search_plate", null, null));
    if (plate != null) {
        plate.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        plate.setPadding(0, 0, rightMarginFrame, 0);
        plate.setBackgroundColor(Color.TRANSPARENT);
    }

    int autoCompleteId = getResources().getIdentifier("android:id/search_src_text", null, null);
    if (searchView.findViewById(autoCompleteId) != null) {
        EditText autoComplete = (EditText) searchView.findViewById(autoCompleteId);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, (int) ViewUtil.convertDpToPixel(36));
        params.weight = 1;
        params.gravity = Gravity.CENTER_VERTICAL;
        params.leftMargin = rightMarginFrame;
        autoComplete.setLayoutParams(params);
        autoComplete.setTextSize(16f);
    }

    int searchMagId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
    if (searchView.findViewById(searchMagId) != null) {
        ImageView v = (ImageView) searchView.findViewById(searchMagId);
        v.setImageDrawable(null);
        v.setPadding(0, 0, 0, 0);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, 0, 0);
        v.setLayoutParams(params);
    }

    toolbar.setTitle(null);
    toolbar.setContentInsetsAbsolute(0, 0);
    toolbar.addView(searchView);

    return searchView;
}

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

How to add buttons like refresh and search in ToolBar in Android?

To control the location of the title you may want to set a custom font as explained here (by twaddington): Link

Then to relocate the position of the text, in updateMeasureState() you would add p.baselineShift += (int) (p.ascent() * R); Similarly in updateDrawState() add tp.baselineShift += (int) (tp.ascent() * R); Where R is double between -1 and 1.

How to auto adjust the div size for all mobile / tablet display formats?

This is called Responsive Web Development(RWD). To make page responsive to all device we need to use some basic fundamental such as:-

1. Set the viewport meta tag in head:

<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0"/>

2.Use media queries.

Example:-

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

3. Or we can directly use RWD framework:-

Some of good Article

Media Queries for Standard Devices - BY CHRIS COYIER

CSS Media Dimensions

4. Larger Device, Medium Devices & Small Devices media queries. (Work in my Scenarios.)

Below media queries for generic Device type: - Larger Device, Medium Devices & Small Devices. This is just basic media types which work for all of scenario & easy to handle code instead of using various media queries just need to care of three media type.

/*###Desktops, big landscape tablets and laptops(Large, Extra large)####*/
@media screen and (min-width: 1024px){
/*Style*/
}

/*###Tablet(medium)###*/
@media screen and (min-width : 768px) and (max-width : 1023px){
/*Style*/
}

/*### Smartphones (portrait and landscape)(small)### */
@media screen and (min-width : 0px) and (max-width : 767px){
/*Style*/
}

Why is it that "No HTTP resource was found that matches the request URI" here?

Just make sure that the controller name is the same as yours DeliveryController if you renamed it (it will not change automatically!). if you rename the project name too you should delete the reference to this project from the Bin folder. Don't forget to specify the method get or post.

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

The return type depends on the server, sometimes the response is indeed a JSON array but sent as text/plain

Setting the accept headers in the request should get the correct type:

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

which can then be serialized to a JSON list or array. Thanks for the comment from @svick which made me curious that it should work.

The Exception I got without configuring the accept headers was System.Net.Http.UnsupportedMediaTypeException.

Following code is cleaner and should work (untested, but works in my case):

    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var response = await client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs");
    var model = await response.Content.ReadAsAsync<List<Job>>();

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

It may occur due to the clean solution.The dlls in the bin will be removed. 1.Clean Solution 2.Rebuild the solution 3.If the build process have failed,not all the necessary dlls will be stored in the bin. This is another scenario where the error occurs

How to disable SSL certificate checking with Spring RestTemplate?

Please see below for a modest improvement on @Sled's code shown above, that turn-back-on method was missing one line, now it passes my tests. This disables HTTPS certificate and hostname spoofing when using RestTemplate in a Spring-Boot version 2 application that uses the default HTTP configuration, NOT configured to use Apache HTTP Client.

package org.my.little.spring-boot-v2.app;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Disables and enables certificate and host-name checking in
 * HttpsURLConnection, the default JVM implementation of the HTTPS/TLS protocol.
 * Has no effect on implementations such as Apache Http Client, Ok Http.
*/
public final class SSLUtils {

    private static final HostnameVerifier jvmHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();

    private static final HostnameVerifier trivialHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession sslSession) {
            return true;
        }
    };

    private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    public static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
        HttpsURLConnection.setDefaultHostnameVerifier(trivialHostnameVerifier);
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, UNQUESTIONING_TRUST_MANAGER, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    public static void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException {
        HttpsURLConnection.setDefaultHostnameVerifier(jvmHostnameVerifier);
        // Return it to the initial state (discovered by reflection, now hardcoded)
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, null, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    private SSLUtils() {
        throw new UnsupportedOperationException("Do not instantiate libraries.");
    }
}

Start redis-server with config file

Okay, redis is pretty user friendly but there are some gotchas.

Here are just some easy commands for working with redis on Ubuntu:

install:

sudo apt-get install redis-server

start with conf:

sudo redis-server <path to conf>
sudo redis-server config/redis.conf

stop with conf:

redis-ctl shutdown

(not sure how this shuts down the pid specified in the conf. Redis must save the path to the pid somewhere on boot)

log:

tail -f /var/log/redis/redis-server.log

Also, various example confs floating around online and on this site were beyond useless. The best, sure fire way to get a compatible conf is to copy-paste the one your installation is already using. You should be able to find it here:

/etc/redis/redis.conf

Then paste it at <path to conf>, tweak as needed and you're good to go.

Bootstrap 3 truncate long text inside rows of a table in a responsive way

I did it this way (you need to add a class text to <td> and put the text between a <span>:

HTML

<td class="text"><span>looooooong teeeeeeeeext</span></td>

SASS

.table td.text {
    max-width: 177px;
    span {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        display: inline-block;
        max-width: 100%;
    }
}

CSS equivalent

.table td.text {
    max-width: 177px;
}
.table td.text span {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
    max-width: 100%;
}

And it will still be mobile responsive (forget it with layout=fixed) and will keep the original behaviour.

PS: Of course 177px is a custom size (put whatever you need).

Error sending json in POST to web API service

Please check if you are were passing method as POST instead as GET. if so you will get same error as a you posted above.

$http({               
 method: 'GET',

The request entity's media type 'text/plain' is not supported for this resource.

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

Implementing SearchView in action bar

SearchDialog or SearchWidget ?

When it comes to implement a search functionality there are two suggested approach by official Android Developer Documentation.
You can either use a SearchDialog or a SearchWidget.
I am going to explain the implementation of Search functionality using SearchWidget.

How to do it with Search widget ?

I will explain search functionality in a RecyclerView using SearchWidget. It's pretty straightforward.

Just follow these 5 Simple steps

1) Add searchView item in the menu

You can add SearchView can be added as actionView in menu using

app:useActionClass = "android.support.v7.widget.SearchView" .

<menu xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   tools:context="rohksin.com.searchviewdemo.MainActivity">
   <item
       android:id="@+id/searchBar"
       app:showAsAction="always"
       app:actionViewClass="android.support.v7.widget.SearchView"
   />
</menu>

2) Set up SerchView Hint text, listener etc

You should initialize SearchView in the onCreateOptionsMenu(Menu menu) method.

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
     // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        MenuItem searchItem = menu.findItem(R.id.searchBar);

        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setQueryHint("Search People");
        searchView.setOnQueryTextListener(this);
        searchView.setIconified(false);

        return true;
   }

3) Implement SearchView.OnQueryTextListener in your Activity

OnQueryTextListener has two abstract methods

  1. onQueryTextSubmit(String query)
  2. onQueryTextChange(String newText

So your Activity skeleton would look like this

YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{

     public boolean onQueryTextSubmit(String query)

     public boolean onQueryTextChange(String newText) 

}

4) Implement SearchView.OnQueryTextListener

You can provide the implementation for the abstract methods like this

public boolean onQueryTextSubmit(String query) {

    // This method can be used when a query is submitted eg. creating search history using SQLite DB

    Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {

    adapter.filter(newText);
    return true;
}

5) Write a filter method in your RecyclerView Adapter.

Most important part. You can write your own logic to perform search.
Here is mine. This snippet shows the list of Name which contains the text typed in the SearchView

public void filter(String queryText)
{
    list.clear();

    if(queryText.isEmpty())
    {
       list.addAll(copyList);
    }
    else
    {

       for(String name: copyList)
       {
           if(name.toLowerCase().contains(queryText.toLowerCase()))
           {
              list.add(name);
           }
       }

    }

   notifyDataSetChanged();
}

Relevant link:

Full working code on SearchView with an SQLite database in this Music App

data.table vs dplyr: can one do something well the other can't or does poorly?

Here's my attempt at a comprehensive answer from the dplyr perspective, following the broad outline of Arun's answer (but somewhat rearranged based on differing priorities).

Syntax

There is some subjectivity to syntax, but I stand by my statement that the concision of data.table makes it harder to learn and harder to read. This is partly because dplyr is solving a much easier problem!

One really important thing that dplyr does for you is that it constrains your options. I claim that most single table problems can be solved with just five key verbs filter, select, mutate, arrange and summarise, along with a "by group" adverb. That constraint is a big help when you're learning data manipulation, because it helps order your thinking about the problem. In dplyr, each of these verbs is mapped to a single function. Each function does one job, and is easy to understand in isolation.

You create complexity by piping these simple operations together with %>%. Here's an example from one of the posts Arun linked to:

diamonds %>%
  filter(cut != "Fair") %>%
  group_by(cut) %>%
  summarize(
    AvgPrice = mean(price),
    MedianPrice = as.numeric(median(price)),
    Count = n()
  ) %>%
  arrange(desc(Count))

Even if you've never seen dplyr before (or even R!), you can still get the gist of what's happening because the functions are all English verbs. The disadvantage of English verbs is that they require more typing than [, but I think that can be largely mitigated by better autocomplete.

Here's the equivalent data.table code:

diamondsDT <- data.table(diamonds)
diamondsDT[
  cut != "Fair", 
  .(AvgPrice = mean(price),
    MedianPrice = as.numeric(median(price)),
    Count = .N
  ), 
  by = cut
][ 
  order(-Count) 
]

It's harder to follow this code unless you're already familiar with data.table. (I also couldn't figure out how to indent the repeated [ in a way that looks good to my eye). Personally, when I look at code I wrote 6 months ago, it's like looking at a code written by a stranger, so I've come to prefer straightforward, if verbose, code.

Two other minor factors that I think slightly decrease readability:

  • Since almost every data table operation uses [ you need additional context to figure out what's happening. For example, is x[y] joining two data tables or extracting columns from a data frame? This is only a small issue, because in well-written code the variable names should suggest what's happening.

  • I like that group_by() is a separate operation in dplyr. It fundamentally changes the computation so I think should be obvious when skimming the code, and it's easier to spot group_by() than the by argument to [.data.table.

I also like that the the pipe isn't just limited to just one package. You can start by tidying your data with tidyr, and finish up with a plot in ggvis. And you're not limited to the packages that I write - anyone can write a function that forms a seamless part of a data manipulation pipe. In fact, I rather prefer the previous data.table code rewritten with %>%:

diamonds %>% 
  data.table() %>% 
  .[cut != "Fair", 
    .(AvgPrice = mean(price),
      MedianPrice = as.numeric(median(price)),
      Count = .N
    ), 
    by = cut
  ] %>% 
  .[order(-Count)]

And the idea of piping with %>% is not limited to just data frames and is easily generalised to other contexts: interactive web graphics, web scraping, gists, run-time contracts, ...)

Memory and performance

I've lumped these together, because, to me, they're not that important. Most R users work with well under 1 million rows of data, and dplyr is sufficiently fast enough for that size of data that you're not aware of processing time. We optimise dplyr for expressiveness on medium data; feel free to use data.table for raw speed on bigger data.

The flexibility of dplyr also means that you can easily tweak performance characteristics using the same syntax. If the performance of dplyr with the data frame backend is not good enough for you, you can use the data.table backend (albeit with a somewhat restricted set of functionality). If the data you're working with doesn't fit in memory, then you can use a database backend.

All that said, dplyr performance will get better in the long-term. We'll definitely implement some of the great ideas of data.table like radix ordering and using the same index for joins & filters. We're also working on parallelisation so we can take advantage of multiple cores.

Features

A few things that we're planning to work on in 2015:

  • the readr package, to make it easy to get files off disk and in to memory, analogous to fread().

  • More flexible joins, including support for non-equi-joins.

  • More flexible grouping like bootstrap samples, rollups and more

I'm also investing time into improving R's database connectors, the ability to talk to web apis, and making it easier to scrape html pages.

What is a 'NoneType' object?

For the sake of defensive programming, objects should be checked against nullity before using.

if obj is None:

or

if obj is not None:

Python+OpenCV: cv2.imwrite

wtluo, great ! May I propose a slight modification of your code 2. ? Here it is:

for i, detected_box in enumerate(detect_boxes):
    box = detected_box["box"]
    face_img = img[ box[1]:box[1] + box[3], box[0]:box[0] + box[2] ]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

GlobalConfiguration.Configure API is available in "Microsoft.AspNet.WebApi.WebHost" version="5.2.3"

and not in "Microsoft.AspNet.WebApi.WebHost" version="4.0.0"

EntityType has no key defined error

There are several reasons this can happen. Some of these I found here, others I discovered on my own.

  • If the property is named something other than Id, you need to add the [Key] attribute to it.
  • The key needs to be a property, not a field.
  • The key needs to be public
  • The key needs to be a CLS-compliant type, meaning unsigned types like uint, ulong etc. are not allowed.
  • This error can also be caused by configuration mistakes.

Display JSON Data in HTML Table

Try this:

CSS:

.hidden{display:none;}

HTML:

<table id="table" class="hidden">
    <tr>
        <th>City</th>
        <th>Status</th>
    </tr>
</table>

JS:

$('#search').click(function() {
    $.ajax({
        type: 'POST',
        url: 'cityResults.htm',
        data: $('#cityDetails').serialize(),
        dataType:"json", //to parse string into JSON object,
        success: function(data){ 
            if(data){
                var len = data.length;
                var txt = "";
                if(len > 0){
                    for(var i=0;i<len;i++){
                        if(data[i].city && data[i].cStatus){
                            txt += "<tr><td>"+data[i].city+"</td><td>"+data[i].cStatus+"</td></tr>";
                        }
                    }
                    if(txt != ""){
                        $("#table").append(txt).removeClass("hidden");
                    }
                }
            }
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('error: ' + textStatus + ': ' + errorThrown);
        }
    });
    return false;//suppress natural form submission
});

how to create a logfile in php?

Agree with the @jon answer. Just added modified the path to create the log directory inside the root

 function wh_log($log_msg) {
    $log_filename = $_SERVER['DOCUMENT_ROOT']."/log";
    if (!file_exists($log_filename))
    {
        // create directory/folder uploads.
        mkdir($log_filename, 0777, true);
    }
    $log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
    file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
}

just added $_SERVER['DOCUMENT_ROOT']

How to change MenuItem icon in ActionBar programmatically

Here is how i resolved this:

1 - create a Field Variable like: private Menu mMenuItem;

2 - override the method invalidateOptionsMenu():

@Override
public void invalidateOptionsMenu() {
    super.invalidateOptionsMenu();
}

3 - call the method invalidateOptionsMenu() in your onCreate()

4 - add mMenuItem = menu in your onCreateOptionsMenu(Menu menu) like this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.webview_menu, menu);
    mMenuItem = menu;
    return super.onCreateOptionsMenu(menu);
}

5 - in the method onOptionsItemSelected(MenuItem item) change the icon you want like this:

 @Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()){

        case R.id.R.id.action_settings:
            mMenuItem.getItem(0).setIcon(R.drawable.ic_launcher); // to change the fav icon
            //Toast.makeText(this, " " + mMenuItem.getItem(0).getTitle(), Toast.LENGTH_SHORT).show(); <<--- this to check if the item in the index 0 is the one you are looking for
            return true;
    }
    return super.onOptionsItemSelected(item);
}

Attempt to set a non-property-list object as an NSUserDefaults

It seems rather wasteful to me to run through the array and encode the objects into NSData yourself. Your error BC_Person is a non-property-list object is telling you that the framework doesn't know how to serialize your person object.

So all that is needed is to ensure that your person object conforms to NSCoding then you can simply convert your array of custom objects into NSData and store that to defaults. Heres a playground:

Edit: Writing to NSUserDefaults is broken on Xcode 7 so the playground will archive to data and back and print an output. The UserDefaults step is included in case its fixed at a later point

//: Playground - noun: a place where people can play

import Foundation

class Person: NSObject, NSCoding {
    let surname: String
    let firstname: String

    required init(firstname:String, surname:String) {
        self.firstname = firstname
        self.surname = surname
        super.init()
    }

    //MARK: - NSCoding -
    required init(coder aDecoder: NSCoder) {
        surname = aDecoder.decodeObjectForKey("surname") as! String
        firstname = aDecoder.decodeObjectForKey("firstname") as! String
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(firstname, forKey: "firstname")
        aCoder.encodeObject(surname, forKey: "surname")
    }
}

//: ### Now lets define a function to convert our array to NSData

func archivePeople(people:[Person]) -> NSData {
    let archivedObject = NSKeyedArchiver.archivedDataWithRootObject(people as NSArray)
    return archivedObject
}

//: ### Create some people

let people = [Person(firstname: "johnny", surname:"appleseed"),Person(firstname: "peter", surname: "mill")]

//: ### Archive our people to NSData

let peopleData = archivePeople(people)

if let unarchivedPeople = NSKeyedUnarchiver.unarchiveObjectWithData(peopleData) as? [Person] {
    for person in unarchivedPeople {
        print("\(person.firstname), you have been unarchived")
    }
} else {
    print("Failed to unarchive people")
}

//: ### Lets try use NSUserDefaults
let UserDefaultsPeopleKey = "peoplekey"
func savePeople(people:[Person]) {
    let archivedObject = archivePeople(people)
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(archivedObject, forKey: UserDefaultsPeopleKey)
    defaults.synchronize()
}

func retrievePeople() -> [Person]? {
    if let unarchivedObject = NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultsPeopleKey) as? NSData {
        return NSKeyedUnarchiver.unarchiveObjectWithData(unarchivedObject) as? [Person]
    }
    return nil
}

if let retrievedPeople = retrievePeople() {
    for person in retrievedPeople {
        print("\(person.firstname), you have been unarchived")
    }
} else {
    print("Writing to UserDefaults is still broken in playgrounds")
}

And Voila, you have stored an array of custom objects into NSUserDefaults

How to run python script with elevated privilege on windows

Thank you all for your reply. I have got my script working with the module/ script written by Preston Landers way back in 2010. After two days of browsing the internet I could find the script as it was was deeply hidden in pywin32 mailing list. With this script it is easier to check if the user is admin and if not then ask for UAC/ admin right. It does provide output in separate windows to find out what the code is doing. Example on how to use the code also included in the script. For the benefit of all who all are looking for UAC on windows have a look at this code. I hope it helps someone looking for same solution. It can be used something like this from your main script:-

import admin
if not admin.isUserAdmin():
        admin.runAsAdmin()

The actual code is:-

#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4

# (C) COPYRIGHT © Preston Landers 2010
# Released under the same license as Python 2.6.5


import sys, os, traceback, types

def isUserAdmin():

    if os.name == 'nt':
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            print "Admin check failed, assuming not an admin."
            return False
    elif os.name == 'posix':
        # Check for root on Posix
        return os.getuid() == 0
    else:
        raise RuntimeError, "Unsupported operating system for this module: %s" % (os.name,)

def runAsAdmin(cmdLine=None, wait=True):

    if os.name != 'nt':
        raise RuntimeError, "This function is only implemented on Windows."

    import win32api, win32con, win32event, win32process
    from win32com.shell.shell import ShellExecuteEx
    from win32com.shell import shellcon

    python_exe = sys.executable

    if cmdLine is None:
        cmdLine = [python_exe] + sys.argv
    elif type(cmdLine) not in (types.TupleType,types.ListType):
        raise ValueError, "cmdLine is not a sequence."
    cmd = '"%s"' % (cmdLine[0],)
    # XXX TODO: isn't there a function or something we can call to massage command line params?
    params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
    cmdDir = ''
    showCmd = win32con.SW_SHOWNORMAL
    #showCmd = win32con.SW_HIDE
    lpVerb = 'runas'  # causes UAC elevation prompt.

    # print "Running", cmd, params

    # ShellExecute() doesn't seem to allow us to fetch the PID or handle
    # of the process, so we can't get anything useful from it. Therefore
    # the more complex ShellExecuteEx() must be used.

    # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)

    procInfo = ShellExecuteEx(nShow=showCmd,
                              fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
                              lpVerb=lpVerb,
                              lpFile=cmd,
                              lpParameters=params)

    if wait:
        procHandle = procInfo['hProcess']    
        obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        rc = win32process.GetExitCodeProcess(procHandle)
        #print "Process handle %s returned code %s" % (procHandle, rc)
    else:
        rc = None

    return rc

def test():
    rc = 0
    if not isUserAdmin():
        print "You're not an admin.", os.getpid(), "params: ", sys.argv
        #rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
        rc = runAsAdmin()
    else:
        print "You are an admin!", os.getpid(), "params: ", sys.argv
        rc = 0
    x = raw_input('Press Enter to exit.')
    return rc


if __name__ == "__main__":
    sys.exit(test())

How to change the background color of Action Bar's Option Menu in Android 4.2?

You can apply styles and Themes in Overflow MenuItem as per below. OverFlow Menu is ListView so, we can apply theme as per listview.

Apply below code in styles.xml

<style name="AppTheme" parent="@android:style/Theme.Holo.Light">
<item name="android:dropDownListViewStyle">@style/PopupMenuListView</item>
        <item name="android:actionBarWidgetTheme">@style/PopupMenuTextView</item>
        <item name="android:popupMenuStyle">@style/PopupMenu</item>
        <item name="android:listPreferredItemHeightSmall">40dp</item>
</style>

<!-- Change Overflow Menu ListView Divider Property -->
    <style name="PopupMenuListView" parent="@android:style/Widget.Holo.ListView.DropDown">
        <item name="android:divider">@color/app_navigation_divider</item>
        <item name="android:dividerHeight">1sp</item>
        <item name="android:listSelector">@drawable/list_selector</item>
    </style>

    <!-- Change Overflow Menu ListView Text Size and Text Size -->
    <style name="PopupMenuTextView" parent="@android:style/Widget.Holo.Light.TextView">
        <item name="android:textColor">@color/app_white</item>
        <item name="android:textStyle">normal</item>
        <item name="android:textSize">18sp</item>
        <item name="android:drawablePadding">25dp</item>
        <item name="android:drawableRight">@drawable/navigation_arrow_selector</item>
    </style>

    <!-- Change Overflow Menu Background -->
    <style name="PopupMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
        <item name="android:popupBackground">@drawable/menu_overflow_bg</item>
    </style>

HTTP Error 503. The service is unavailable. App pool stops on accessing website

Changing "Managed Pipeline Mode" from "Classic" to "Integrated" worked for me. It can be changed at Application Pools -> Basic Settings

Unsuccessful append to an empty NumPy array

numpy.append is pretty different from list.append in python. I know that's thrown off a few programers new to numpy. numpy.append is more like concatenate, it makes a new array and fills it with the values from the old array and the new value(s) to be appended. For example:

import numpy

old = numpy.array([1, 2, 3, 4])
new = numpy.append(old, 5)
print old
# [1, 2, 3, 4]
print new
# [1, 2, 3, 4, 5]
new = numpy.append(new, [6, 7])
print new
# [1, 2, 3, 4, 5, 6, 7]

I think you might be able to achieve your goal by doing something like:

result = numpy.zeros((10,))
result[0:2] = [1, 2]

# Or
result = numpy.zeros((10, 2))
result[0, :] = [1, 2]

Update:

If you need to create a numpy array using loop, and you don't know ahead of time what the final size of the array will be, you can do something like:

import numpy as np

a = np.array([0., 1.])
b = np.array([2., 3.])

temp = []
while True:
    rnd = random.randint(0, 100)
    if rnd > 50:
        temp.append(a)
    else:
        temp.append(b)
    if rnd == 0:
         break

 result = np.array(temp)

In my example result will be an (N, 2) array, where N is the number of times the loop ran, but obviously you can adjust it to your needs.

new update

The error you're seeing has nothing to do with types, it has to do with the shape of the numpy arrays you're trying to concatenate. If you do np.append(a, b) the shapes of a and b need to match. If you append an (2, n) and (n,) you'll get a (3, n) array. Your code is trying to append a (1, 0) to a (2,). Those shapes don't match so you get an error.

python: changing row index of pandas data frame

followers_df.reset_index()
followers_df.reindex(index=range(0,20))

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

I got this issue when deploying to Azure using the Publish feature. Remember to clear files at destination.

Publish Settings -> File Publish Options drop down -> Check Remove additional files at destination

This solved my issue, in case people have to hunt around for this like I did. Everything was the same version in my project/solution, just not at the destination I was deploying to.

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

If you are using 64 bit machine

Go to Visual Studio > Tools Menu > Options

Options window with Projects and Solutions > Web Projects selected and option Use the 64 bit version of IIS Express selected

How to convert an array into an object using stdClass()

The quick and dirty way is using json_encode and json_decode which will turn the entire array (including sub elements) into an object.

$clasa = json_decode(json_encode($clasa)); //Turn it into an object

The same can be used to convert an object into an array. Simply add , true to json_decode to return an associated array:

$clasa = json_decode(json_encode($clasa), true); //Turn it into an array

An alternate way (without being dirty) is simply a recursive function:

function convertToObject($array) {
    $object = new stdClass();
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $value = convertToObject($value);
        }
        $object->$key = $value;
    }
    return $object;
}

or in full code:

<?php
    function convertToObject($array) {
        $object = new stdClass();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $value = convertToObject($value);
            }
            $object->$key = $value;
        }
        return $object;
    }

    $clasa = array(
            'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
            'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
            'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
            'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
            'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
    );

    $obj = convertToObject($clasa);
    print_r($obj);
?>

which outputs (note that there's no arrays - only stdClass's):

stdClass Object
(
    [e1] => stdClass Object
        (
            [nume] => Nitu
            [prenume] => Andrei
            [sex] => m
            [varsta] => 23
        )

    [e2] => stdClass Object
        (
            [nume] => Nae
            [prenume] => Ionel
            [sex] => m
            [varsta] => 27
        )

    [e3] => stdClass Object
        (
            [nume] => Noman
            [prenume] => Alice
            [sex] => f
            [varsta] => 22
        )

    [e4] => stdClass Object
        (
            [nume] => Geangos
            [prenume] => Bogdan
            [sex] => m
            [varsta] => 23
        )

    [e5] => stdClass Object
        (
            [nume] => Vasile
            [prenume] => Mihai
            [sex] => m
            [varsta] => 25
        )

)

So you'd refer to it by $obj->e5->nume.

DEMO

Web API Put Request generates an Http 405 Method Not Allowed error

In my case the error 405 was invoked by static handler due to route ("api/images") conflicting with the folder of the same name ("~/images").

Logging request/response messages when using HttpClient

See http://mikehadlow.blogspot.com/2012/07/tracing-systemnet-to-debug-http-clients.html

To configure a System.Net listener to output to both the console and a log file, add the following to your assembly configuration file:

<system.diagnostics>
  <trace autoflush="true" />
  <sources>
    <source name="System.Net">
      <listeners>
        <add name="MyTraceFile"/>
        <add name="MyConsole"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add
      name="MyTraceFile"
      type="System.Diagnostics.TextWriterTraceListener"
      initializeData="System.Net.trace.log" />
    <add name="MyConsole" type="System.Diagnostics.ConsoleTraceListener" />
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose" />
  </switches>
</system.diagnostics>

Making an iframe responsive

iFrames CAN be FULLY responsive while keeping their aspect ratio with a little CSS technique called the Intrinsic Ratio Technique. I wrote a blog post addressing this question specifically: https://benmarshall.me/responsive-iframes/

This gist is:

_x000D_
_x000D_
.intrinsic-container {_x000D_
  position: relative;_x000D_
  height: 0;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
_x000D_
/* 16x9 Aspect Ratio */_x000D_
_x000D_
.intrinsic-container-16x9 {_x000D_
  padding-bottom: 56.25%;_x000D_
}_x000D_
_x000D_
_x000D_
/* 4x3 Aspect Ratio */_x000D_
_x000D_
.intrinsic-container-4x3 {_x000D_
  padding-bottom: 75%;_x000D_
}_x000D_
_x000D_
.intrinsic-container iframe {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div class="intrinsic-container intrinsic-container-16x9">_x000D_
  <iframe src="//www.youtube.com/embed/KMYrIi_Mt8A" allowfullscreen></iframe>_x000D_
</div>
_x000D_
_x000D_
_x000D_

BOOM, fully responsive!

Are nested try/except blocks in Python a good programming practice?

A good and simple example for nested try/except could be the following:

import numpy as np

def divide(x, y):
    try:
        out = x/y
    except:
        try:
            out = np.inf * x / abs(x)
        except:
            out = np.nan
    finally:
        return out

Now try various combinations and you will get the correct result:

divide(15, 3)
# 5.0

divide(15, 0)
# inf

divide(-15, 0)
# -inf

divide(0, 0)
# nan

(Of course, we have NumPy, so we don't need to create this function.)

Deserialize a JSON array in C#

This code is working fine for me,

var a = serializer.Deserialize<List<Entity>>(json);

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

I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.

The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)

From: http://technet.microsoft.com/en-us/library/ee681792.aspx:

"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."

Edit: Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE returned.

If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll.

Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206

I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.

Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you print, or otherwise send Unicode strings to stdout, and it's attached to a console/tty, Python has to encode it.

The error message indirectly tells you what character set Python was trying to use:

  File "C:\Python32\lib\encodings\cp850.py", line 19, in encode

This means the charset is cp850.

You can test or yourself that this charset doesn't have the appropriate character just by doing '\u2013'.encode('cp850'). Or you can look up cp850 online (e.g., at Wikipedia).

It's possible that Python is guessing wrong, and your console is really set for, say UTF-8. (In that case, just manually set sys.stdout.encoding='utf-8'.) It's also possible that you intended your console to be set for UTF-8 but did something wrong. (In that case, you probably want to follow up at superuser.com.)

But if nothing is wrong, you just can't print that character. You will have to manually encode it with one of the non-strict error-handlers. For example:

>>> '\u2013'.encode('cp850')
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 0: character maps to <undefined>
>>> '\u2013'.encode('cp850', errors='replace')
b'?'

So, how do you print a string that won't print on your console?

You can replace every print function with something like this:

>>> print(r['body'].encode('cp850', errors='replace').decode('cp850'))
?

… but that's going to get pretty tedious pretty fast.

The simple thing to do is to just set the error handler on sys.stdout:

>>> sys.stdout.errors = 'replace'
>>> print(r['body'])
?

For printing to a file, things are pretty much the same, except that you don't have to set f.errors after the fact, you can set it at construction time. Instead of this:

with open('path', 'w', encoding='cp850') as f:

Do this:

with open('path', 'w', encoding='cp850', errors='replace') as f:

… Or, of course, if you can use UTF-8 files, just do that, as Mark Ransom's answer shows:

with open('path', 'w', encoding='utf-8') as f:

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

I have done this in a project a long time ago. The code given below write a whole rows bold with specific column names and all of these columns are written in bold format.

private void WriteColumnHeaders(DataColumnCollection columnCollection, int row, int column)
    {
        // row represent particular row you want to bold its content.
        for (i = 0; i < columnCollection.Count; i++)
        {
            DataColumn col = columnCollection[i];
            xlWorkSheet.Cells[row, column + i + 1] = col.Caption;
            // Some Font Styles
            xlWorkSheet.Cells[row, column + i + 1].Style.Font.Bold = true;
            xlWorkSheet.Cells[row, column + i + 1].Interior.Color = Color.FromArgb(192, 192, 192);
            //xlWorkSheet.Columns[i + 1].ColumnWidth = xlWorkSheet.Columns[i+1].ColumnWidth + 10;
        }
    }

You must pass value of row 0 so that first row of your excel sheets have column headers with bold font size. Just change DataColumnCollection to your columns name and change col.Caption to specific column name.

Alternate

You may do this to cell of excel sheet you want bold.

xlWorkSheet.Cells[row, column].Style.Font.Bold = true;

Java double.MAX_VALUE?

Resurrecting the dead here, but just in case someone stumbles against this like myself. I know where to get the maximum value of a double, the (more) interesting part was to how did they get to that number.

double has 64 bits. The first one is reserved for the sign.

Next 11 represent the exponent (that is 1023 biased). It's just another way to represent the positive/negative values. If there are 11 bits then the max value is 1023.

Then there are 52 bits that hold the mantissa.

This is easily computed like this for example:

public static void main(String[] args) {

    String test = Strings.repeat("1", 52);

    double first = 0.5;
    double result = 0.0;
    for (char c : test.toCharArray()) {
        result += first;
        first = first / 2;
    }

    System.out.println(result); // close approximation of 1
    System.out.println(Math.pow(2, 1023) * (1 + result));
    System.out.println(Double.MAX_VALUE);

} 

You can also prove this in reverse order :

    String max = "0" + Long.toBinaryString(Double.doubleToLongBits(Double.MAX_VALUE));

    String sign = max.substring(0, 1);
    String exponent = max.substring(1, 12); // 11111111110
    String mantissa = max.substring(12, 64);

    System.out.println(sign); // 0 - positive
    System.out.println(exponent); // 2046 - 1023 = 1023
    System.out.println(mantissa); // 0.99999...8

Maven is not working in Java 8 when Javadoc tags are incomplete

As of maven-javadoc-plugin 3.0.0 you should have been using additionalJOption to set an additional Javadoc option, so if you would like Javadoc to disable doclint, you should add the following property.

<properties>
    ...
    <additionalJOption>-Xdoclint:none</additionalJOption>
    ...
<properties>

You should also mention the version of maven-javadoc-plugin as 3.0.0 or higher.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>3.0.0</version>    
</plugin>

How to save a bitmap on internal storage

To save file into directory

  public static Uri saveImageToInternalStorage(Context mContext, Bitmap bitmap){

    String mTimeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());

    String mImageName = "snap_"+mTimeStamp+".jpg";

    ContextWrapper wrapper = new ContextWrapper(mContext);

    File file = wrapper.getDir("Images",MODE_PRIVATE);

    file = new File(file, "snap_"+ mImageName+".jpg");

    try{

        OutputStream stream = null;

        stream = new FileOutputStream(file);

        bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);

        stream.flush();

        stream.close();

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

    Uri mImageUri = Uri.parse(file.getAbsolutePath());

    return mImageUri;
}

required permission

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

asp.net Button OnClick event not firing

If you are using updatepanel on onclick event, this may happen.

Use 'EnableEventValidation="false"' in your page markup like this :

<%@ Page Language="C#" MasterPageFile="~/ars_home.master" AutoEventWireup="true" CodeFile="Transaction_Window.aspx.cs" Inherits="Transaction_Window" EnableEventValidation="false" %>

Hope this helps

All ASP.NET Web API controllers return 404

I have dozens of installations of my app with different clients which all worked fine and then this one just always returned 404 on all api calls. It turns out that when I created the application pool in IIS for this client it defaulted to .net framework 2.0 instead of 4.0 and I missed it. This caused the 404 error. Seems to me this should have been a 500 error. Very misleading Microsoft!

jQuery click events not working in iOS

There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.

While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

I've found this the easy fix, simply add this to the css:

cursor: pointer;

How to generate an MD5 file hash in JavaScript?

If you don't want to use libraries or other things, you can use this native javascript approach:

_x000D_
_x000D_
var MD5 = function(d){var r = M(V(Y(X(d),8*d.length)));return r.toLowerCase()};function M(d){for(var _,m="0123456789ABCDEF",f="",r=0;r<d.length;r++)_=d.charCodeAt(r),f+=m.charAt(_>>>4&15)+m.charAt(15&_);return f}function X(d){for(var _=Array(d.length>>2),m=0;m<_.length;m++)_[m]=0;for(m=0;m<8*d.length;m+=8)_[m>>5]|=(255&d.charCodeAt(m/8))<<m%32;return _}function V(d){for(var _="",m=0;m<32*d.length;m+=8)_+=String.fromCharCode(d[m>>5]>>>m%32&255);return _}function Y(d,_){d[_>>5]|=128<<_%32,d[14+(_+64>>>9<<4)]=_;for(var m=1732584193,f=-271733879,r=-1732584194,i=271733878,n=0;n<d.length;n+=16){var h=m,t=f,g=r,e=i;f=md5_ii(f=md5_ii(f=md5_ii(f=md5_ii(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_hh(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_gg(f=md5_ff(f=md5_ff(f=md5_ff(f=md5_ff(f,r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+0],7,-680876936),f,r,d[n+1],12,-389564586),m,f,d[n+2],17,606105819),i,m,d[n+3],22,-1044525330),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+4],7,-176418897),f,r,d[n+5],12,1200080426),m,f,d[n+6],17,-1473231341),i,m,d[n+7],22,-45705983),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+8],7,1770035416),f,r,d[n+9],12,-1958414417),m,f,d[n+10],17,-42063),i,m,d[n+11],22,-1990404162),r=md5_ff(r,i=md5_ff(i,m=md5_ff(m,f,r,i,d[n+12],7,1804603682),f,r,d[n+13],12,-40341101),m,f,d[n+14],17,-1502002290),i,m,d[n+15],22,1236535329),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+1],5,-165796510),f,r,d[n+6],9,-1069501632),m,f,d[n+11],14,643717713),i,m,d[n+0],20,-373897302),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+5],5,-701558691),f,r,d[n+10],9,38016083),m,f,d[n+15],14,-660478335),i,m,d[n+4],20,-405537848),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+9],5,568446438),f,r,d[n+14],9,-1019803690),m,f,d[n+3],14,-187363961),i,m,d[n+8],20,1163531501),r=md5_gg(r,i=md5_gg(i,m=md5_gg(m,f,r,i,d[n+13],5,-1444681467),f,r,d[n+2],9,-51403784),m,f,d[n+7],14,1735328473),i,m,d[n+12],20,-1926607734),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+5],4,-378558),f,r,d[n+8],11,-2022574463),m,f,d[n+11],16,1839030562),i,m,d[n+14],23,-35309556),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+1],4,-1530992060),f,r,d[n+4],11,1272893353),m,f,d[n+7],16,-155497632),i,m,d[n+10],23,-1094730640),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+13],4,681279174),f,r,d[n+0],11,-358537222),m,f,d[n+3],16,-722521979),i,m,d[n+6],23,76029189),r=md5_hh(r,i=md5_hh(i,m=md5_hh(m,f,r,i,d[n+9],4,-640364487),f,r,d[n+12],11,-421815835),m,f,d[n+15],16,530742520),i,m,d[n+2],23,-995338651),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+0],6,-198630844),f,r,d[n+7],10,1126891415),m,f,d[n+14],15,-1416354905),i,m,d[n+5],21,-57434055),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+12],6,1700485571),f,r,d[n+3],10,-1894986606),m,f,d[n+10],15,-1051523),i,m,d[n+1],21,-2054922799),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+8],6,1873313359),f,r,d[n+15],10,-30611744),m,f,d[n+6],15,-1560198380),i,m,d[n+13],21,1309151649),r=md5_ii(r,i=md5_ii(i,m=md5_ii(m,f,r,i,d[n+4],6,-145523070),f,r,d[n+11],10,-1120210379),m,f,d[n+2],15,718787259),i,m,d[n+9],21,-343485551),m=safe_add(m,h),f=safe_add(f,t),r=safe_add(r,g),i=safe_add(i,e)}return Array(m,f,r,i)}function md5_cmn(d,_,m,f,r,i){return safe_add(bit_rol(safe_add(safe_add(_,d),safe_add(f,i)),r),m)}function md5_ff(d,_,m,f,r,i,n){return md5_cmn(_&m|~_&f,d,_,r,i,n)}function md5_gg(d,_,m,f,r,i,n){return md5_cmn(_&f|m&~f,d,_,r,i,n)}function md5_hh(d,_,m,f,r,i,n){return md5_cmn(_^m^f,d,_,r,i,n)}function md5_ii(d,_,m,f,r,i,n){return md5_cmn(m^(_|~f),d,_,r,i,n)}function safe_add(d,_){var m=(65535&d)+(65535&_);return(d>>16)+(_>>16)+(m>>16)<<16|65535&m}function bit_rol(d,_){return d<<_|d>>>32-_}_x000D_
_x000D_
/** NORMAL words**/_x000D_
var value = 'test';_x000D_
_x000D_
var result = MD5(value);_x000D_
 _x000D_
document.body.innerHTML = 'hash -  normal words: ' + result;_x000D_
_x000D_
/** NON ENGLISH words**/_x000D_
value = '????'_x000D_
_x000D_
//unescape() can be deprecated for the new browser versions_x000D_
result = MD5(unescape(encodeURIComponent(value)));_x000D_
_x000D_
document.body.innerHTML += '<br><br>hash - non english words: ' + result;_x000D_
 
_x000D_
_x000D_
_x000D_

For non english words you may need to use unescape() and the encodeURIComponent() methods.

Query to select data between two dates with the format m/d/yyyy

DateTime dt1 = this.dateTimePicker1.Value.Date;
DateTime dt2 = this.dateTimePicker2.Value.Date.AddMinutes(1440);
String query = "SELECT * FROM student WHERE sdate BETWEEN '" + dt1 + "' AND '" + dt2 + "'";

Automapper missing type map configuration or unsupported mapping - Error

I was trying to map an IEnumerable to an object. This is way I got this error. Maybe it helps.

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

  • if you unable to find assembly reference from when (Right click on reference ->add required assembly)

try this Package manager console
Install-Package System.Net.Http.Formatting.Extension -Version 5.2.3 and then add by using add reference .

How can I save an image with PIL?

You should be able to simply let PIL get the filetype from extension, i.e. use:

j.save("C:/Users/User/Desktop/mesh_trans.bmp")

What is the difference between Numpy's array() and asarray() functions?

The difference can be demonstrated by this example:

  1. generate a matrix

    >>> A = numpy.matrix(numpy.ones((3,3)))
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  2. use numpy.array to modify A. Doesn't work because you are modifying a copy

    >>> numpy.array(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  3. use numpy.asarray to modify A. It worked because you are modifying A itself

    >>> numpy.asarray(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 2.,  2.,  2.]])
    

Hope this helps!

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

Go to Xcode's breakpoints tab. Use the button at the bottom to add an exception breakpoint. Now you'll see what code is invoking setValue:forKey: and the associated stack. With luck that'll point you straight at the problem's source.

Odd that your class is LoginScreen, yet the error is saying someone is using "LoginScreen" as a key. Check that LoginScreen.m is part of your target.

enter image description here


Footnote: with Swift a common problem arises if you change the name of a class (so, you rename it everywhere in your code). Storyboard struggles with this, and you usually have to re-drag any connections involving that class. And in particular, re-enter the name of the class anywhere used in IdentityInspector tab on the right. (In the picture example I deliberately misspelled the class name. But the same thing often happens when you rename a class; even though it's seemingly correct in IdentityInspector, you need to enter the name again; it will correctly autocomplete and you're good to go.)

How to pass ArrayList of Objects from one to another activity using Intent in android?

It works well,

public class Question implements Serializable {
    private int[] operands;
    private int[] choices;
    private int userAnswerIndex;

   public Question(int[] operands, int[] choices) {
       this.operands = operands;
       this.choices = choices;
       this.userAnswerIndex = -1;
   }

   public int[] getChoices() {
       return choices;
   }

   public void setChoices(int[] choices) {
       this.choices = choices;
   }

   public int[] getOperands() {
       return operands;
   }

   public void setOperands(int[] operands) {
       this.operands = operands;
   }

   public int getUserAnswerIndex() {
       return userAnswerIndex;
   }

   public void setUserAnswerIndex(int userAnswerIndex) {
       this.userAnswerIndex = userAnswerIndex;
   }

   public int getAnswer() {
       int answer = 0;
       for (int operand : operands) {
           answer += operand;
       }
       return answer;
   }

   public boolean isCorrect() {
       return getAnswer() == choices[this.userAnswerIndex];
   }

   public boolean hasAnswered() {
       return userAnswerIndex != -1;
   }

   @Override
   public String toString() {
       StringBuilder builder = new StringBuilder();

       // Question
       builder.append("Question: ");
       for(int operand : operands) {
           builder.append(String.format("%d ", operand));
       }
       builder.append(System.getProperty("line.separator"));

       // Choices
       int answer = getAnswer();
       for (int choice : choices) {
           if (choice == answer) {
               builder.append(String.format("%d (A) ", choice));
           } else {
               builder.append(String.format("%d ", choice));
           }
       }
       return builder.toString();
     }
  }

In your Source Activity, use this :

  List<Question> mQuestionList = new ArrayList<Question>;
  mQuestionsList = QuestionBank.getQuestions();
  mQuestionList.add(new Question(ops1, choices1));

  Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
  intent.putExtra("QuestionListExtra", ArrayList<Question>mQuestionList);

In your Target Activity, use this :

  List<Question> questions = new ArrayList<Question>();
  questions = (ArrayList<Question>)getIntent().getSerializableExtra("QuestionListExtra");

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The possible reason can also be that you have not inherited Controller from ApiController. Happened with me took a while to understand the same.

PIL image to array (numpy array to array) - Python

I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects

import Image
import numpy as np

im = Image.load('foo.jpg')
im = im.convert('L')

arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)

arr ^= 0xFF  # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()

Where can I find Android's default icons?

\path-to-your-android-sdk-folder\platforms\android-xx\data\res

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

I know this is an oldie, but thought I might add some value. For those of us running Server Core outside of a domain (domain members can just run Server Manager remotely to add/remove features/roles), you have to resort to command lines.

Powershell users can type "Install-WindowsFeature Web-Asp-Net45"

That should be equivalent to using server manager.

Count all values in a matrix greater than a value

This is very straightforward with boolean arrays:

p31 = numpy.asarray(o31)
za = (p31 < 200).sum() # p31<200 is a boolean array, so `sum` counts the number of True elements

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I found this answer when I was getting a similar error for nodeName after upgrading to Bootstrap 4. The issue was that the tabs didn't have the nav and nav-tab classes; adding those to the <ul> element fixed the issue.

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

Try using ReadAsStringAsync() instead.

 var foo = resp.Content.ReadAsStringAsync().Result;

The reason why it ReadAsAsync<string>() doesn't work is because ReadAsAsync<> will try to use one of the default MediaTypeFormatter (i.e. JsonMediaTypeFormatter, XmlMediaTypeFormatter, ...) to read the content with content-type of text/plain. However, none of the default formatter can read the text/plain (they can only read application/json, application/xml, etc).

By using ReadAsStringAsync(), the content will be read as string regardless of the content-type.

how to execute php code within javascript

May be this way:

    <?php 
     if($_SERVER['REQUEST_METHOD']=="POST") {
       echo 'asdasda';
     }
    ?>

    <form method="post">
    <button type="submit" id="okButton">Order now</button>
</form>

How to include Authorization header in cURL POST HTTP Request in PHP?

@jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:

$rest = curl_exec($crl);

if ($rest === false)
{
    // throw new Exception('Curl error: ' . curl_error($crl));
    print_r('Curl error: ' . curl_error($crl));
}

curl_close($crl);
print_r($rest);

EDIT 1

To debug you can set CURLOPT_HEADER to true to check HTTP response with firebug::net or similar.

curl_setopt($crl, CURLOPT_HEADER, true);

EDIT 2

About Curl error: SSL certificate problem, verify that the CA cert is OK try adding this headers (just to debug, in a production enviroment you should keep these options in true):

curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);

'negative' pattern matching in python

If this is a file, you can simply skip the first and last lines and read the rest with csv:

>>> s = """OK SYS 10 LEN 20 12 43
... 1233a.fdads.txt,23 /data/a11134/a.txt
... 3232b.ddsss.txt,32 /data/d13f11/b.txt
... 3452d.dsasa.txt,1234 /data/c13af4/f.txt
... ."""
>>> stream = StringIO.StringIO(s)
>>> rows = [row for row in csv.reader(stream,delimiter=',') if len(row) == 2]
>>> rows
[['1233a.fdads.txt', '23 /data/a11134/a.txt'], ['3232b.ddsss.txt', '32 /data/d13f11/b.txt'], ['3452d.dsasa.txt', '1234 /data/c13af4/f.txt']]

If its a file, then you can do this:

with open('myfile.txt','r') as f:
   rows = [row for row in csv.reader(f,delimiter=',') if len(row) == 2]

Adding Http Headers to HttpClient

Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.

var client = new HttpClient();
var request = new HttpRequestMessage() {
    RequestUri = new Uri("http://www.someURI.com"),
    Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

how to get the attribute value of an xml node using java

public static void main(String[] args) throws IOException {
    String filePath = "/Users/myXml/VH181.xml";
    File xmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();
        printElement(doc);
        System.out.println("XML file updated successfully");
    } catch (SAXException | ParserConfigurationException e1) {
        e1.printStackTrace();
    }
}
private static void printElement(Document someNode) {
    NodeList nodeList = someNode.getElementsByTagName("choiceInteraction");
    for(int z=0,size= nodeList.getLength();z<size; z++) {
            String Value = nodeList.item(z).getAttributes().getNamedItem("id").getNodeValue();
            System.out.println("Choice Interaction Id:"+Value);
        }
    }

we Can try this code using method

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

Add bean declaration in bean.xml file or in any other configuration file . It will resolve the error

<bean  class="com.demo.dao.RailwayDao"></bean>
<bean  class="com.demo.service.RailwayService"></bean>
<bean  class="com.demo.model.RailwayReservation"></bean>

rejected master -> master (non-fast-forward)

Try this, in my case it works

git rebase --abort

"Parser Error Message: Could not load type" in Global.asax

I also got the same error...check the name of the Application you developed properly ie. the namespace and the assembly name alloted and also try physically changing the name of the folder created for the application, all of this should be same as the name in the above namespace present in the file global.asax

Python: SyntaxError: keyword can't be an expression

I just got that problem when converting from % formatting to .format().

Previous code:

"SET !TIMEOUT_STEP %{USER_TIMEOUT_STEP}d" % {'USER_TIMEOUT_STEP' = 3}

Problematic syntax:

"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format('USER_TIMEOUT_STEP' = 3)

The problem is that format is a function that needs parameters. They cannot be strings. That is one of worst python error messages I've ever seen.

Corrected code:

"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format(USER_TIMEOUT_STEP = 3)

How to check whether dynamically attached event listener exists or not?

I usually attach a class to the element then check if the class exist like this:

let element = document.getElementsById("someElement");

if(!element.classList.contains('attached-listener'))
   element.addEventListener("click", this.itemClicked);

element.classList.add('attached-listener');

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

you can create a service and generate excel on server and then allow clients download excel. cos buying excel license for 1000 ppl, it is better to have one license for server.

hope that helps.

Multiple HttpPost method in Web API controller

You can use this approach :

public class VTRoutingController : ApiController
{
    [HttpPost("Route")]
    public MyResult Route(MyRequestTemplate routingRequestTemplate)
    {
        return null;
    }

    [HttpPost("TSPRoute")]
    public MyResult TSPRoute(MyRequestTemplate routingRequestTemplate)
    {
        return null;
    }
}

MIME types missing in IIS 7 for ASP.NET - 404.17

There are two reasons you might get this message:

  1. ASP.Net is not configured. For this run from Administrator command %FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.
  2. Another reason this may happen is because your App Pool is not configured correctly. For example, you created website for WordPress and you also want to throw in few aspx files in there, WordPress creates app pool that says don't run CLR stuff. To fix this just open up App Pool and enable CLR.

How to stretch the background image to fill a div

Try something like this:

div {
    background-image: url(../img/picture1.jpg);
    height: 30em;
    background-repeat: no-repeat;
    width: 100%;
    background-position: center;
}

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

open cmd as Administrator then try to register in both location

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

Where is HttpContent.ReadAsAsync?

I have the same problem, so I simply get JSON string and deserialize to my class:

HttpResponseMessage response = await client.GetAsync("Products");
//get data as Json string 
string data = await response.Content.ReadAsStringAsync();
//use JavaScriptSerializer from System.Web.Script.Serialization
JavaScriptSerializer JSserializer = new JavaScriptSerializer();
//deserialize to your class
products = JSserializer.Deserialize<List<Product>>(data);

Java - Convert image to Base64

The line

base64String = Base64.encode(byteArray);

converts the full array (102400 bytes) to Base64, not just the number of bytes you have read. You need to pass it the numbers of bytes.

What's the advantage of a Java enum versus a class with public static final fields?

enum Benefits:

  1. Enums are type-safe, static fields are not
  2. There is a finite number of values (it is not possible to pass non-existing enum value. If you have static class fields, you can make that mistake)
  3. Each enum can have multiple properties (fields/getters) assigned - encapsulation. Also some simple methods: YEAR.toSeconds() or similar. Compare: Colors.RED.getHex() with Colors.toHex(Colors.RED)

"such as the ability to easily assign an enum element a certain value"

enum EnumX{
  VAL_1(1),
  VAL_200(200);
  public final int certainValue;
  private X(int certainValue){this.certainValue = certainValue;}
}

"and consequently the ability to convert an integer to an enum without a decent amount of effort" Add a method converting int to enum which does that. Just add static HashMap<Integer, EnumX> containing the mapping java enum.

If you really want to convert ord=VAL_200.ordinal() back to val_200 just use: EnumX.values()[ord]

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

Try changing the second parameter in the SaveAs call to Excel.XlFileFormat.xlWorkbookDefault.

When I did that, I generated an xlsx file that I was able to successfully open. (Before making the change, I could produce an xlsx file, but I was unable to open it.)

Also, I'm not sure if it matters or not, but I'm using the Excel 12.0 object library.

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

ajax jquery simple get request

It seems to me, this is a cross-domain issue since you're not allowed to make a request to a different domain.

You have to find solutions to this problem: - Use a proxy script, running on your server that will forward your request and will handle the response sending it to the browser Or - The service you're making the request should have JSONP support. This is a cross-domain technique. You might want to read this http://en.wikipedia.org/wiki/JSONP

Convert RGBA PNG to RGB with PIL

By using Image.alpha_composite, the solution by Yuji 'Tomita' Tomita become simpler. This code can avoid a tuple index out of range error if png has no alpha channel.

from PIL import Image

png = Image.open(img_path).convert('RGBA')
background = Image.new('RGBA', png.size, (255,255,255))

alpha_composite = Image.alpha_composite(background, png)
alpha_composite.save('foo.jpg', 'JPEG', quality=80)

m2eclipse error

Just go to your user folder, inside it there's a ".m2" folder, open it and delete the folder "repository". Go to eclipse, clean your project, then right click->Maven->Update Project .. and you are ready to go.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Timeout expired because the sql query is taking more time than you set in sqlCommand.CommandTimeout property.

Obviously you can increase CommandTimeout to solve this issue but before doing that you must optimize your query by adding index. If you run your query in Sql server management studio including actual execution plan then Sql server management studio will suggest you proper index. Most of the case you will get rid of timeout issue if you can optimize your query.

how to convert an RGB image to numpy array?

You can also use matplotlib for this.

from matplotlib.image import imread

img = imread('abc.tiff')
print(type(img))

output: <class 'numpy.ndarray'>

Basic Python client socket example

Here is the simplest python socket example.

Server side:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # become a server socket, maximum 5 connections

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print buf
        break

Client Side:

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')
  • First run the SocketServer.py, and make sure the server is ready to listen/receive sth
  • Then the client send info to the server;
  • After the server received sth, it terminates

Converting an OpenCV Image to Black and White

Simply you can write the following code snippet to convert an OpenCV image into a grey scale image

import cv2
image = cv2.imread('image.jpg',0)
cv2.imshow('grey scale image',image)

Observe that the image.jpg and the code must be saved in same folder.

Note that:

  • ('image.jpg') gives a RGB image
  • ('image.jpg',0) gives Grey Scale Image.

Set environment variables on Mac OS X Lion

More detail, which may perhaps be helpful to someone:

Due to my own explorations, I now know how to set environment variables in 7 of 8 different ways. I was trying to get an envar through to an application I'm developing under Xcode. I set "tracer" envars using these different methods to tell me which ones get it into the scope of my application. From the below, you can see that editing the "scheme" in Xcode to add arguments works, as does "putenv". What didn't set it in that scope: ~/.MACOS/environment.plist, app-specific plist, .profile, and adding a build phase to run a custom script (I found another way in Xcode [at least] to set one but forgot what I called the tracer and can't find it now; maybe it's on another machine....)

GPU_DUMP_DEVICE_KERNEL is 3

GPU_DUMP_TRK_ENVPLIST is (null)

GPU_DUMP_TRK_APPPLIST is (null)

GPU_DUMP_TRK_DOTPROFILE is (null)

GPU_DUMP_TRK_RUNSCRIPT is (null)

GPU_DUMP_TRK_SCHARGS is 1

GPU_DUMP_TRK_PUTENV is 1

... on the other hand, if I go into Terminal and say "set", it seems the only one it gets is the one from .profile (I would have thought it would pick up environment.plist also, and I'm sure once I did see a second tracer envar in Terminal, so something's probably gone wonky since then. Long day....)

Can you control how an SVG's stroke-width is drawn?

Here's a function that will calculate how many pixels you need to add - using the given stroke - to the top, right, bottom and left, all based on the browser:

var getStrokeOffsets = function(stroke){

        var strokeFloor =       Math.floor(stroke / 2),                                                                 // max offset
            strokeCeil =        Math.ceil(stroke / 2);                                                                  // min offset

        if($.browser.mozilla){                                                                                          // Mozilla offsets

            return {
                bottom:     strokeFloor,
                left:       strokeFloor,
                top:        strokeCeil,
                right:      strokeCeil
            };

        }else if($.browser.webkit){                                                                                     // WebKit offsets

            return {
                bottom:     strokeCeil,
                left:       strokeFloor,
                top:        strokeFloor,
                right:      strokeCeil
            };

        }else{                                                                                                          // default offsets

            return {
                bottom:     strokeCeil,
                left:       strokeCeil,
                top:        strokeCeil,
                right:      strokeCeil
            };

        }

    };

How do I create sql query for searching partial matches?

First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).

If your data is not large, you can do

SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'

using OR if you have multiple keywords.

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

Get Base64 encode file-data from Input Form

Inspired by @Josef's answer:

const fileToBase64 = async (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (e) => reject(e)
  })

const file = event.srcElement.files[0];
const imageStr = await fileToBase64(file)

Objects inside objects in javascript

var pause_menu = {
    pause_button : { someProperty : "prop1", someOther : "prop2" },
    resume_button : { resumeProp : "prop", resumeProp2 : false },
    quit_button : false
};

then:

pause_menu.pause_button.someProperty //evaluates to "prop1"

etc etc.

How to mute an html5 video player using jQuery

Are you using the default controls boolean attribute on the video tag? If so, I believe all the supporting browsers have mute buttons. If you need to wire it up, set .muted to true on the element in javascript (use .prop for jquery because it's an IDL attribute.) The speaker icon on the volume control is the mute button on chrome,ff, safari, and opera for example

Why I cannot cout a string?

You need to reference the cout's namespace std somehow. For instance, insert

using std::cout;
using std::endl;

on top of your function definition, or the file.

Where is the Global.asax.cs file?

That's because you created a Web Site instead of a Web Application. The cs/vb files can only be seen in a Web Application, but in a website you can't have a separate cs/vb file.

Edit: In the website you can add a cs file behavior like..

<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>

~/Global.asax.cs:

namespace ApplicationName
{
    public partial class MyApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
        }
    }
}

Good way of getting the user's location in Android

In my experience, I've found it best to go with the GPS fix unless it's not available. I don't know much about other location providers, but I know that for GPS there are a few tricks that can be used to give a bit of a ghetto precision measure. The altitude is often a sign, so you could check for ridiculous values. There is the accuracy measure on Android location fixes. Also if you can see the number of satellites used, this can also indicate the precision.

An interesting way of getting a better idea of the accuracy could be to ask for a set of fixes very rapidly, like ~1/sec for 10 seconds and then sleep for a minute or two. One talk I've been to has led to believe that some android devices will do this anyway. You would then weed out the outliers (I've heard Kalman filter mentioned here) and use some kind of centering strategy to get a single fix.

Obviously the depth you get to here depends on how hard your requirements are. If you have particularly strict requirement to get THE BEST location possible, I think you'll find that GPS and network location are as similar as apples and oranges. Also GPS can be wildly different from device to device.

Simple way to count character occurrences in a string

Since you're scanning the whole string anyway you can build a full character count and do any number of lookups, all for the same big-Oh cost (n):

public static Map<Character,Integer> getCharFreq(String s) {
  Map<Character,Integer> charFreq = new HashMap<Character,Integer>();
  if (s != null) {
    for (Character c : s.toCharArray()) {
      Integer count = charFreq.get(c);
      int newCount = (count==null ? 1 : count+1);
      charFreq.put(c, newCount);
    }
  }
  return charFreq;
}

// ...
String s = "abdsd3$asda$asasdd$sadas";
Map counts = getCharFreq(s);
counts.get('$'); // => 3
counts.get('a'); // => 7
counts.get('s'); // => 6

How to style the menu items on an Android action bar

I did this way:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="android:actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="actionMenuTextColor">@color/colorAccent</item>
</style>

<style name="MenuTextAppearance" >
    <item name="android:textAppearance">@android:style/TextAppearance.Large</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
</style>

'Incomplete final line' warning when trying to read a .csv file into R

The message indicates that the last line of the file doesn't end with an End Of Line (EOL) character (linefeed (\n) or carriage return+linefeed (\r\n)). The original intention of this message was to warn you that the file may be incomplete; most datafiles have an EOL character as the very last character in the file.

The remedy is simple:

  1. Open the file
  2. Navigate to the very last line of the file
  3. Place the cursor the end of that line
  4. Press return
  5. Save the file

How to update a menu item shown in the ActionBar?

Option #1: Try invalidateOptionsMenu(). I don't know if this will force an immediate redraw of the action bar or not.

Option #2: See if getActionView() returns anything for the affected MenuItem. It is possible that showAsAction simply automatically creates action views for you. If so, you can presumably enable/disable that View.

I can't seem to find a way to get the currently set Menu to manipulate it except for in onPrepareOptionMenu.

You can hang onto the Menu object you were handed in onCreateOptionsMenu(). Quoting the docs:

You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.

Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

please paste below code on surfaceview extend class constructor.............

constructor coding

    SurfaceHolder holder = getHolder();
    holder.addCallback(this);

    SurfaceView sur = (SurfaceView)findViewById(R.id.surfaceview);
    sur.setZOrderOnTop(true);    // necessary
    holder = sur.getHolder();
    holder.setFormat(PixelFormat.TRANSPARENT);

xml coding

    <com.welcome.panelview.PanelViewWelcomeScreen
        android:id="@+id/one"
        android:layout_width="600px"
        android:layout_height="312px"
        android:layout_gravity="center"
        android:layout_marginTop="10px"
        android:background="@drawable/welcome" />

try above code...

How do I parse JSON with Objective-C?

JSON parsing using NSJSONSerialization

   NSString* path  = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
   
    //Here you can take JSON string from your URL ,I am using json file
    NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *jsonError;
    NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
  
    NSLog(@"jsonDataArray: %@",jsonDataArray);

    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];
if(jsonObject !=nil){
   // NSString *errorCode=[NSMutableString stringWithFormat:@"%@",[jsonObject objectForKey:@"response"]];
   
        
        if(![[jsonObject objectForKey:@"#data"] isEqual:@""]){
            
            NSMutableArray *array=[jsonObject objectForKey:@"#data"];
             // NSLog(@"array: %@",array);
            NSLog(@"array: %d",array.count);  
            
            int k = 0;
            for(int z = 0; z<array.count;z++){
                
                NSString *strfd = [NSString stringWithFormat:@"%d",k];
                NSDictionary *dicr = jsonObject[@"#data"][strfd];
                k=k+1;
                // NSLog(@"dicr: %@",dicr);
                 NSLog(@"Firstname - Lastname   : %@ - %@",
                     [NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"user_first_name"]],
                     [NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"user_last_name"]]);
            }
            
          }

     }

You can see the Console output as below :

Firstname - Lastname : Chandra Bhusan - Pandey

Firstname - Lastname : Kalaiyarasan - Balu

Firstname - Lastname : (null) - (null)

Firstname - Lastname : Girija - S

Firstname - Lastname : Girija - S

Firstname - Lastname : (null) - (null)

afxwin.h file is missing in VC++ Express Edition

Including the header afxwin.h signalizes use of MFC. The following instructions (based on those on CodeProject.com) could help to get MFC code compiling:

  1. Download and install the Windows Driver Kit.

  2. Select menu Tools > Options… > Projects and Solutions > VC++ Directories.

  3. In the drop-down menu Show directories for select Include files.

  4. Add the following paths (replace $(WDK_directory) with the directory where you installed Windows Driver Kit in the first step):

    $(WDK_directory)\inc\mfc42
    $(WDK_directory)\inc\atl30
    

  5. In the drop-down menu Show directories for select Library files and add (replace $(WDK_directory) like before):

    $(WDK_directory)\lib\mfc\i386
    $(WDK_directory)\lib\atl\i386
    

  6. In the $(WDK_directory)\inc\mfc42\afxwin.inl file, edit the following lines (starting from 1033):

    _AFXWIN_INLINE CMenu::operator==(const CMenu& menu) const
        { return ((HMENU) menu) == m_hMenu; }
    _AFXWIN_INLINE CMenu::operator!=(const CMenu& menu) const
        { return ((HMENU) menu) != m_hMenu; }
    

    to

    _AFXWIN_INLINE BOOL CMenu::operator==(const CMenu& menu) const
        { return ((HMENU) menu) == m_hMenu; }
    _AFXWIN_INLINE BOOL CMenu::operator!=(const CMenu& menu) const
        { return ((HMENU) menu) != m_hMenu; }
    

    In other words, add BOOL after _AFXWIN_INLINE.

"No resource identifier found for attribute 'showAsAction' in package 'android'"

all above fix may not work in android studio .if you are using ANDROID STUDIO...... use this fix

add

xmlns:compat="http://schemas.android.com/tools"

in menu tag instead of

xmlns:compat="http://schemas.android.com/apk/res-auto"

in menu tag.

Apache POI Excel - how to configure columns to be expanded?

You can use setColumnWidth() if you want to expand your cell more.

Better way to shuffle two numpy arrays in unison

Your can use NumPy's array indexing:

def unison_shuffled_copies(a, b):
    assert len(a) == len(b)
    p = numpy.random.permutation(len(a))
    return a[p], b[p]

This will result in creation of separate unison-shuffled arrays.

No grammar constraints (DTD or XML schema) detected for the document

I too had the same problem in eclipse using web.xml file
it showed me this " no grammar constraints referenced in the document "

but it can be resolved by adding tag
after the xml tag i.e. <?xml version = "1.0" encoding = "UTF-8"?>

System.Runtime.InteropServices.COMException (0x800A03EC)

For all of those, who still experiencing this problem, I just spent 2 days tracking down the bloody thing. I was getting the same error when there was no rows in dataset. Seems obvious, but error message is very obscure, hence 2 days.

How to Copy Contents of One Canvas to Another Canvas Locally

Actually you don't have to create an image at all. drawImage() will accept a Canvas as well as an Image object.

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);

Way faster than using an ImageData object or Image element.

Note that sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas.

Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element

Create a new TextView programmatically then display it below another TextView

public View recentView;

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Create a relative layout and add a button
        relativeLayout = new RelativeLayout(this);
        btn = new Button(this);
        btn.setId((int)System.currentTimeMillis());
        recentView = btn;
        btn.setText("Click me");
        relativeLayout.addView(btn);


        setContentView(relativeLayout);

        btn.setOnClickListener(new View.OnClickListener() {

            @Overr ide
            public void onClick(View view) {

                //Create a textView, set a random ID and position it below the most recently added view
                textView = new TextView(ActivityName.this);
                textView.setId((int)System.currentTimeMillis());
                layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
                layoutParams.addRule(RelativeLayout.BELOW, recentView.getId());
                textView.setText("Time: "+System.currentTimeMillis());
                relativeLayout.addView(textView, layoutParams);
                recentView = textView;
            }
        });
    }

This can be modified to display each element of a String array in different TextViews.

Strange Jackson exception being thrown when serializing Hibernate object

You can add a Jackson mixin on Object.class to always ignore hibernate-related properties. If you are using Spring Boot put this in your Application class:

@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
    Jackson2ObjectMapperBuilder b = new Jackson2ObjectMapperBuilder();
    b.mixIn(Object.class, IgnoreHibernatePropertiesInJackson.class);
    return b;
}


@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private abstract class IgnoreHibernatePropertiesInJackson{ }

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

If your key is a CHAR/VARCHAR or something of that type, another possible problem is different collation. Check if the charset is the same.

Address already in use: JVM_Bind

You can try to use TCPView utility.

Try to find in the localport column is there any process worked on "busy" port. Right click and end the process. Then try to start the Tomcat.

Its really works for me.

Log4net does not write the log in the log file

Also, Make sure the "Copy always" option is selected for [log4net].config

enter image description here

How to find most common elements of a list?

nltk is convenient for a lot of language processing stuff. It has methods for frequency distribution built in. Something like:

import nltk
fdist = nltk.FreqDist(your_list) # creates a frequency distribution from a list
most_common = fdist.max()    # returns a single element
top_three = fdist.keys()[:3] # returns a list

Python base64 data decode

Python 3 (and 2)

import base64
a = 'eW91ciB0ZXh0'
base64.b64decode(a)

Python 2

A quick way to decode it without importing anything:

'eW91ciB0ZXh0'.decode('base64')

or more descriptive

>>> a = 'eW91ciB0ZXh0'
>>> a.decode('base64')
'your text'

How to make correct date format when writing data to Excel

This worked for me:

hoja_trabajo.Cells[i + 2, j + 1] = fecha.ToString("dd-MMM-yyyy").Replace(".", "");

.NET Global exception handler in console application

What you are trying should work according to the MSDN doc's for .Net 2.0. You could also try a try/catch right in main around your entry point for the console app.

static void Main(string[] args)
{
    try
    {
        // Start Working
    }
    catch (Exception ex)
    {
        // Output/Log Exception
    }
    finally
    {
        // Clean Up If Needed
    }
}

And now your catch will handle anything not caught (in the main thread). It can be graceful and even restart where it was if you want, or you can just let the app die and log the exception. You woul add a finally if you wanted to do any clean up. Each thread will require its own high level exception handling similar to the main.

Edited to clarify the point about threads as pointed out by BlueMonkMN and shown in detail in his answer.

How do I auto size columns through the Excel interop objects?

This method opens already created excel file, Autofit all columns of all sheets based on 3rd Row. As you can see Range is selected From "A3 to K3" in excel.

 public static void AutoFitExcelSheets()
    {
        Microsoft.Office.Interop.Excel.Application _excel = null;
        Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
        try
        {
            string ExcelPath = ApplicationData.PATH_EXCEL_FILE;
            _excel = new Microsoft.Office.Interop.Excel.Application();
            _excel.Visible = false;
            object readOnly = false;
            object isVisible = true;
            object missing = System.Reflection.Missing.Value;

            excelWorkbook = _excel.Workbooks.Open(ExcelPath,
                   0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
                   true, false, 0, true, false, false);
            Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
            foreach (Microsoft.Office.Interop.Excel.Worksheet currentSheet in excelSheets)
            {
                string Name = currentSheet.Name;
                Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(Name);
                Microsoft.Office.Interop.Excel.Range excelCells =
(Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A3", "K3");
                excelCells.Columns.AutoFit();
            }
        }
        catch (Exception ex)
        {
            ProjectLog.AddError("EXCEL ERROR: Can not AutoFit: " + ex.Message);
        }
        finally
        {
            excelWorkbook.Close(true, Type.Missing, Type.Missing);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            releaseObject(excelWorkbook);
            releaseObject(_excel);
        }
    }

Get name of property as a string

You can use Reflection to obtain the actual names of the properties.

http://www.csharp-examples.net/reflection-property-names/

If you need a way to assign a "String Name" to a property, why don't you write an attribute that you can reflect over to get the string name?

[StringName("MyStringName")]
private string MyProperty
{
    get { ... }
}

Global variables in c#.net

/// <summary>
/// Contains global variables for project.
/// </summary>
public static class GlobalVar
{
/// <summary>
/// Global variable that is constant.
/// </summary>
public const string GlobalString = "Important Text";

/// <summary>
/// Static value protected by access routine.
/// </summary>
static int _globalValue;

/// <summary>
/// Access routine for global variable.
/// </summary>
public static int GlobalValue
{
get
{
    return _globalValue;
}
set
{
    _globalValue = value;
}
}

/// <summary>
/// Global static field.
/// </summary>
public static bool GlobalBoolean;
}

What is the purpose of global.asax in asp.net

Global.asax is the asp.net application file.

It is an optional file that handles events raised by ASP.NET or by HttpModules. Mostly used for application and session start/end events and for global error handling.

When used, it should be in the root of the website.

Resizing an image in an HTML5 canvas

I'd highly suggest you check out this link and make sure it is set to true.

Controlling image scaling behavior

Introduced in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0)

Gecko 1.9.2 introduced the mozImageSmoothingEnabled property to the canvas element; if this Boolean value is false, images won't be smoothed when scaled. This property is true by default. view plainprint?

  1. cx.mozImageSmoothingEnabled = false;

Flatten an irregular list of lists

My solution:

import collections


def flatten(x):
    if isinstance(x, collections.Iterable):
        return [a for i in x for a in flatten(i)]
    else:
        return [x]

A little more concise, but pretty much the same.

HTTPS connection Python

To check for ssl support in Python 2.6+:

try:
    import ssl
except ImportError:
    print "error: no ssl support"

To connect via https:

import urllib2

try:
    response = urllib2.urlopen('https://example.com') 
    print 'response headers: "%s"' % response.info()
except IOError, e:
    if hasattr(e, 'code'): # HTTPError
        print 'http error code: ', e.code
    elif hasattr(e, 'reason'): # URLError
        print "can't connect, reason: ", e.reason
    else:
        raise

How to set a Default Route (To an Area) in MVC

First, what version of MVC2 are you using? There have been significant changes from preview2 to RC.

Assuming you use the RC, I think you route-mapping should look differently. In the AreaRegistration.cs in your area, you can register some kind of default route, e.g.

        context.MapRoute(
            "ShopArea_default",
            "{controller}/{action}/{id}",
            new { action = "Index", id = "", controller="MyRoute" }
        );

The code above will send the user to the MyRouteController in our ShopArea per default.

Using an empty string as a second parameter should throw an exception, because a controller must be specified.

Of course you will have to change the default route in Global.asax so it doesn't interfere with this default route, e.g. by using a prefix for the main site.

Also see this thread and Haack's answer: MVC 2 AreaRegistration Routes Order

Hope this helps.

Does my application "contain encryption"?

Short answer: Yes, but you don't have to do anything

I was searching the web for this for some hours. Actually it is pretty easy and you can verify this in itunes connect:

1. All you have to do

If your app uses only HTTPS or uses encryption only for authentication, tokens, etc., there is nothing you have to do, just include

<key>ITSAppUsesNonExemptEncryption</key><false/>

in your Info.plist and you are done.

2. Verification

You can verify this in itunes connect.

  • select your app
  • chose features
  • chose encryption
  • click "+"
  • follow the dialog
  • for https or authentication the answer is yes and yes

In any case you should of course read yourself carefully through the dialog.


A very helpful article can be found here:

https://www.cocoanetics.com/2017/02/itunes-connect-encryption-info/

"Could not load type [Namespace].Global" causing me grief

I had a similar issues where I was receiving this error on a project.

“Could not load type [Namespace].Global
Error in Line 1   etc etc

After spending some time I suspect a function with possible errors in a Class ..later commenting that specific function my problem get resolved.

I dont know why Visual Studio did't give me that specific error at debugging time. But this error might occure due to some errors in class file..

In Python, how do I determine if an object is iterable?

I'd like to shed a little bit more light on the interplay of iter, __iter__ and __getitem__ and what happens behind the curtains. Armed with that knowledge, you will be able to understand why the best you can do is

try:
    iter(maybe_iterable)
    print('iteration will probably work')
except TypeError:
    print('not iterable')

I will list the facts first and then follow up with a quick reminder of what happens when you employ a for loop in python, followed by a discussion to illustrate the facts.

Facts

  1. You can get an iterator from any object o by calling iter(o) if at least one of the following conditions holds true:

    a) o has an __iter__ method which returns an iterator object. An iterator is any object with an __iter__ and a __next__ (Python 2: next) method.

    b) o has a __getitem__ method.

  2. Checking for an instance of Iterable or Sequence, or checking for the attribute __iter__ is not enough.

  3. If an object o implements only __getitem__, but not __iter__, iter(o) will construct an iterator that tries to fetch items from o by integer index, starting at index 0. The iterator will catch any IndexError (but no other errors) that is raised and then raises StopIteration itself.

  4. In the most general sense, there's no way to check whether the iterator returned by iter is sane other than to try it out.

  5. If an object o implements __iter__, the iter function will make sure that the object returned by __iter__ is an iterator. There is no sanity check if an object only implements __getitem__.

  6. __iter__ wins. If an object o implements both __iter__ and __getitem__, iter(o) will call __iter__.

  7. If you want to make your own objects iterable, always implement the __iter__ method.

for loops

In order to follow along, you need an understanding of what happens when you employ a for loop in Python. Feel free to skip right to the next section if you already know.

When you use for item in o for some iterable object o, Python calls iter(o) and expects an iterator object as the return value. An iterator is any object which implements a __next__ (or next in Python 2) method and an __iter__ method.

By convention, the __iter__ method of an iterator should return the object itself (i.e. return self). Python then calls next on the iterator until StopIteration is raised. All of this happens implicitly, but the following demonstration makes it visible:

import random

class DemoIterable(object):
    def __iter__(self):
        print('__iter__ called')
        return DemoIterator()

class DemoIterator(object):
    def __iter__(self):
        return self

    def __next__(self):
        print('__next__ called')
        r = random.randint(1, 10)
        if r == 5:
            print('raising StopIteration')
            raise StopIteration
        return r

Iteration over a DemoIterable:

>>> di = DemoIterable()
>>> for x in di:
...     print(x)
...
__iter__ called
__next__ called
9
__next__ called
8
__next__ called
10
__next__ called
3
__next__ called
10
__next__ called
raising StopIteration

Discussion and illustrations

On point 1 and 2: getting an iterator and unreliable checks

Consider the following class:

class BasicIterable(object):
    def __getitem__(self, item):
        if item == 3:
            raise IndexError
        return item

Calling iter with an instance of BasicIterable will return an iterator without any problems because BasicIterable implements __getitem__.

>>> b = BasicIterable()
>>> iter(b)
<iterator object at 0x7f1ab216e320>

However, it is important to note that b does not have the __iter__ attribute and is not considered an instance of Iterable or Sequence:

>>> from collections import Iterable, Sequence
>>> hasattr(b, '__iter__')
False
>>> isinstance(b, Iterable)
False
>>> isinstance(b, Sequence)
False

This is why Fluent Python by Luciano Ramalho recommends calling iter and handling the potential TypeError as the most accurate way to check whether an object is iterable. Quoting directly from the book:

As of Python 3.4, the most accurate way to check whether an object x is iterable is to call iter(x) and handle a TypeError exception if it isn’t. This is more accurate than using isinstance(x, abc.Iterable) , because iter(x) also considers the legacy __getitem__ method, while the Iterable ABC does not.

On point 3: Iterating over objects which only provide __getitem__, but not __iter__

Iterating over an instance of BasicIterable works as expected: Python constructs an iterator that tries to fetch items by index, starting at zero, until an IndexError is raised. The demo object's __getitem__ method simply returns the item which was supplied as the argument to __getitem__(self, item) by the iterator returned by iter.

>>> b = BasicIterable()
>>> it = iter(b)
>>> next(it)
0
>>> next(it)
1
>>> next(it)
2
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Note that the iterator raises StopIteration when it cannot return the next item and that the IndexError which is raised for item == 3 is handled internally. This is why looping over a BasicIterable with a for loop works as expected:

>>> for x in b:
...     print(x)
...
0
1
2

Here's another example in order to drive home the concept of how the iterator returned by iter tries to access items by index. WrappedDict does not inherit from dict, which means instances won't have an __iter__ method.

class WrappedDict(object): # note: no inheritance from dict!
    def __init__(self, dic):
        self._dict = dic

    def __getitem__(self, item):
        try:
            return self._dict[item] # delegate to dict.__getitem__
        except KeyError:
            raise IndexError

Note that calls to __getitem__ are delegated to dict.__getitem__ for which the square bracket notation is simply a shorthand.

>>> w = WrappedDict({-1: 'not printed',
...                   0: 'hi', 1: 'StackOverflow', 2: '!',
...                   4: 'not printed', 
...                   'x': 'not printed'})
>>> for x in w:
...     print(x)
... 
hi
StackOverflow
!

On point 4 and 5: iter checks for an iterator when it calls __iter__:

When iter(o) is called for an object o, iter will make sure that the return value of __iter__, if the method is present, is an iterator. This means that the returned object must implement __next__ (or next in Python 2) and __iter__. iter cannot perform any sanity checks for objects which only provide __getitem__, because it has no way to check whether the items of the object are accessible by integer index.

class FailIterIterable(object):
    def __iter__(self):
        return object() # not an iterator

class FailGetitemIterable(object):
    def __getitem__(self, item):
        raise Exception

Note that constructing an iterator from FailIterIterable instances fails immediately, while constructing an iterator from FailGetItemIterable succeeds, but will throw an Exception on the first call to __next__.

>>> fii = FailIterIterable()
>>> iter(fii)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: iter() returned non-iterator of type 'object'
>>>
>>> fgi = FailGetitemIterable()
>>> it = iter(fgi)
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/iterdemo.py", line 42, in __getitem__
    raise Exception
Exception

On point 6: __iter__ wins

This one is straightforward. If an object implements __iter__ and __getitem__, iter will call __iter__. Consider the following class

class IterWinsDemo(object):
    def __iter__(self):
        return iter(['__iter__', 'wins'])

    def __getitem__(self, item):
        return ['__getitem__', 'wins'][item]

and the output when looping over an instance:

>>> iwd = IterWinsDemo()
>>> for x in iwd:
...     print(x)
...
__iter__
wins

On point 7: your iterable classes should implement __iter__

You might ask yourself why most builtin sequences like list implement an __iter__ method when __getitem__ would be sufficient.

class WrappedList(object): # note: no inheritance from list!
    def __init__(self, lst):
        self._list = lst

    def __getitem__(self, item):
        return self._list[item]

After all, iteration over instances of the class above, which delegates calls to __getitem__ to list.__getitem__ (using the square bracket notation), will work fine:

>>> wl = WrappedList(['A', 'B', 'C'])
>>> for x in wl:
...     print(x)
... 
A
B
C

The reasons your custom iterables should implement __iter__ are as follows:

  1. If you implement __iter__, instances will be considered iterables, and isinstance(o, collections.abc.Iterable) will return True.
  2. If the object returned by __iter__ is not an iterator, iter will fail immediately and raise a TypeError.
  3. The special handling of __getitem__ exists for backwards compatibility reasons. Quoting again from Fluent Python:

That is why any Python sequence is iterable: they all implement __getitem__ . In fact, the standard sequences also implement __iter__, and yours should too, because the special handling of __getitem__ exists for backward compatibility reasons and may be gone in the future (although it is not deprecated as I write this).

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

This issue is complicated because it's easy to confuse the root cause with whatever the immediate cause happens to be.

In my case, the immediate cause was that the solution is configured to use NuGet Package Restore, but the server was not connected to the internet, so NuGet was unable to download the dependencies when building for the first time.

I believe the root cause is simply that the solution is unable to resolve dependencies correctly. It may be an incorrect path configuration, or the wrong version of an assembly, or conflicting assemblies, or a partial deployment. But in all cases, the error is simply saying that it can't find the type specified in global.asax because it can't build it.

jQuery hasAttr checking to see if there is an attribute on an element

I wrote a hasAttr() plugin for jquery that will do all of this very simply, exactly as the OP has requested. More information here

EDIT: My plugin was deleted in the great plugins.jquery.com database deletion disaster of 2010. You can look here for some info on adding it yourself, and why it hasn't been added.

Could not load file or assembly 'System.Data.SQLite'

I resolved this by installing System.Data.SQLite with Nuget extension. This extension can use for Visual Studio 2010 or higher. First, you have to install Nuget extension. You can follow here:

  • Go to Visual Studio 2010, Menu --> Tools
  • Select Extension Manager
  • Enter NuGet in the search box and click Online Gallery. Waiting it Retrieve information…
  • Select the retrieved NuGet Package Manager, click Download. Waiting it Download…
  • Click Install on the Visual Studio Extension Installer NuGet Package Manager. Wait for the installation to complete.
  • Click Close and 'Restart Now.

Second, now, you can install SQLite:

And now, you can use System.Data.SQLite.

In the case, you see two folder x64 and, x86, these folders contain SQLite.Interop.dll. Now go to the properties windows of those dlls and set build action is content and Copy to output directory is Copy always.

So, that is my way.

Thanks. Kim Tho Pham, HoChiMinh City, Vietnam. Email: [email protected]

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

Phil Haak has an example that I think is a bit more stable when dealing with paths with crazy "\" style directory separators. It also safely handles path concatenation. It comes for free in System.IO

var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);

However, you could also try "AppDomain.CurrentDomain.BaseDirector" instead of "Server.MapPath".

How to calculate an angle from three points?

If you mean the angle that P1 is the vertex of then using the Law of Cosines should work:

arccos((P122 + P132 - P232) / (2 * P12 * P13))

where P12 is the length of the segment from P1 to P2, calculated by

sqrt((P1x - P2x)2 + (P1y - P2y)2)

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

Brian, This approach works great for non-Ajax requests, but as Lion_cl stated, if you have an error during an Ajax call, your Share/Error.aspx view (or your custom error page view) will be returned to the Ajax caller--the user will NOT be redirected to the error page.

Verify object attribute value with mockito

And very nice and clean solution in koltin from com.nhaarman.mockito_kotlin

verify(mock).execute(argThat {
    this.param = expected
})

How can I create an array with key value pairs?

$data =array();
$data['user_code']  = 'JOY' ;
$data['user_name']  = 'JOY' ;
$data['user_email'] = '[email protected]';

Is embedding background image data into CSS as Base64 good or bad practice?

I tried to create an online concept of CSS/HTML analyzer tool:

http://www.motobit.com/util/base64/css-images-to-base64.asp

It can:

  • Download and parse HTML/CSS files, extract href/src/url elements
  • Detect compression (gzip) and size data on the URL
  • Compare original data size, base64 data size and gzipped base64 data size
  • Convert the URL (image, font, css, ...) to a base64 data URI scheme.
  • Count number of requests which can be spared by Data URIs

Comments/suggestions are welcome.

Antonin

Using the AND and NOT Operator in Python

It's called and and or in Python.

ASP.NET MVC - Set custom IIdentity or IPrincipal

Here is a solution if you need to hook up some methods to @User for use in your views. No solution for any serious membership customization, but if the original question was needed for views alone then this perhaps would be enough. The below was used for checking a variable returned from a authorizefilter, used to verify if some links wehere to be presented or not(not for any kind of authorization logic or access granting).

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Security.Principal;

    namespace SomeSite.Web.Helpers
    {
        public static class UserHelpers
        {
            public static bool IsEditor(this IPrincipal user)
            {
                return null; //Do some stuff
            }
        }
    }

Then just add a reference in the areas web.config, and call it like below in the view.

@User.IsEditor()

Is there a decorator to simply cache function return values?

I implemented something like this, using pickle for persistance and using sha1 for short almost-certainly-unique IDs. Basically the cache hashed the code of the function and the hist of arguments to get a sha1 then looked for a file with that sha1 in the name. If it existed, it opened it and returned the result; if not, it calls the function and saves the result (optionally only saving if it took a certain amount of time to process).

That said, I'd swear I found an existing module that did this and find myself here trying to find that module... The closest I can find is this, which looks about right: http://chase-seibert.github.io/blog/2011/11/23/pythondjango-disk-based-caching-decorator.html

The only problem I see with that is it wouldn't work well for large inputs since it hashes str(arg), which isn't unique for giant arrays.

It would be nice if there were a unique_hash() protocol that had a class return a secure hash of its contents. I basically manually implemented that for the types I cared about.

Application_Start not firing?

Make sure the namespaces in Global.asax and Global.asax.cs are same. If they are different it will not throw any error but will not hit the breakpoint also because it is not executing application_start at all.

Converting HTML files to PDF

If you look at the side bar of your question, you will see many related questions...

In your context, the simpler method might be to install a PDF print driver like PDFCreator and just print the page to this output.

Stack, Static, and Heap in C++

I'm sure one of the pedants will come up with a better answer shortly, but the main difference is speed and size.

Stack

Dramatically faster to allocate. It is done in O(1) since it is allocated when setting up the stack frame so it is essentially free. The drawback is that if you run out of stack space you are boned. You can adjust the stack size, but IIRC you have ~2MB to play with. Also, as soon as you exit the function everything on the stack is cleared. So it can be problematic to refer to it later. (Pointers to stack allocated objects leads to bugs.)

Heap

Dramatically slower to allocate. But you have GB to play with, and point to.

Garbage Collector

The garbage collector is some code that runs in the background and frees memory. When you allocate memory on the heap it is very easy to forget to free it, which is known as a memory leak. Over time, the memory your application consumes grows and grows until it crashes. Having a garbage collector periodically free the memory you no longer need helps eliminate this class of bugs. Of course this comes at a price, as the garbage collector slows things down.

ASP.NET custom error page - Server.GetLastError() is null

I think you have a couple of options here.

you could store the last Exception in the Session and retrieve it from your custom error page; or you could just redirect to your custom error page within the Application_error event. If you choose the latter, you want to make sure you use the Server.Transfer method.

SQL Server Management Studio – tips for improving the TSQL coding process

Use the Filter button in the Object Explorer to quickly find a particular object (table, stored procedure, etc.) from partial text in the name or find objects that belong to a particular schema.

Get index of selected option with jQuery

Good way to solve this in Jquery manner

$("#dropDownMenuKategorie option:selected").index()

Center HTML Input Text Field Placeholder

The HTML5 placeholder element can be styled for those browsers that accept the element, but in diferent ways, as you can see here: http://davidwalsh.name/html5-placeholder-css.

But I don't believe that text-align will be interpreted by the browsers. At least on Chrome, this attribute is ignored. But you can always change other things, like color, font-size, font-family etc. I suggest you rethinking your design whether possible to remove this center behavior.

EDIT

If you really want this text centered, you can always use some jQuery code or plugin to simulate the placeholder behavior. Here is a sample of it: http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html.

This way the style will work:

input.placeholder {
    text-align: center;
}

How to get multiple select box values using jQuery?

Using the .val() function on a multi-select list will return an array of the selected values:

var selectedValues = $('#multipleSelect').val();

and in your html:

<select id="multipleSelect" multiple="multiple">
    <option value="1">Text 1</option>
    <option value="2">Text 2</option>
    <option value="3">Text 3</option>
</select>

Cell spacing in UICollectionView

I have problem with the accepted answer, so I updated it, this is working for me:

.h

@interface MaxSpacingCollectionViewFlowLayout : UICollectionViewFlowLayout
@property (nonatomic,assign) CGFloat maxCellSpacing;
@end

.m

@implementation MaxSpacingCollectionViewFlowLayout

- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];

    if (attributes.count <= 0) return attributes;

    CGFloat firstCellOriginX = ((UICollectionViewLayoutAttributes *)attributes[0]).frame.origin.x;

    for(int i = 1; i < attributes.count; i++) {
        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
        if (currentLayoutAttributes.frame.origin.x == firstCellOriginX) { // The first cell of a new row
            continue;
        }

        UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
        CGFloat prevOriginMaxX = CGRectGetMaxX(prevLayoutAttributes.frame);
        if ((currentLayoutAttributes.frame.origin.x - prevOriginMaxX) > self.maxCellSpacing) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = prevOriginMaxX + self.maxCellSpacing;
            currentLayoutAttributes.frame = frame;
        }
    }
    return attributes;
}

@end

Elegant way to report missing values in a data.frame

summary(airquality)

already gives you this information

The VIM packages also offers some nice missing data plot for data.frame

library("VIM")
aggr(airquality)

enter image description here

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

In the examples below the client is the browser and the server is the webserver hosting the website.

Before you can understand these technologies, you have to understand classic HTTP web traffic first.

Regular HTTP:

  1. A client requests a webpage from a server.
  2. The server calculates the response
  3. The server sends the response to the client.

HTTP

Ajax Polling:

  1. A client requests a webpage from a server using regular HTTP (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server at regular intervals (e.g. 0.5 seconds).
  3. The server calculates each response and sends it back, just like normal HTTP traffic.

Ajax Polling

Ajax Long-Polling:

  1. A client requests a webpage from a server using regular HTTP (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server.
  3. The server does not immediately respond with the requested information but waits until there's new information available.
  4. When there's new information available, the server responds with the new information.
  5. The client receives the new information and immediately sends another request to the server, re-starting the process.

Ajax Long-Polling

HTML5 Server Sent Events (SSE) / EventSource:

  1. A client requests a webpage from a server using regular HTTP (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which opens a connection to the server.
  3. The server sends an event to the client when there's new information available.

HTML5 SSE

HTML5 Websockets:

  1. A client requests a webpage from a server using regular http (see HTTP above).
  2. The client receives the requested webpage and executes the JavaScript on the page which opens a connection with the server.
  3. The server and the client can now send each other messages when new data (on either side) is available.

    • Real-time traffic from the server to the client and from the client to the server
    • You'll want to use a server that has an event loop
    • With WebSockets it is possible to connect with a server from another domain.
    • It is also possible to use a third party hosted websocket server, for example Pusher or others. This way you'll only have to implement the client side, which is very easy!
    • If you want to read more, I found these very useful: (article), (article) (tutorial).

HTML5 WebSockets

Comet:

Comet is a collection of techniques prior to HTML5 which use streaming and long-polling to achieve real time applications. Read more on wikipedia or this article.


Now, which one of them should I use for a realtime app (that I need to code). I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP ?

You can use PHP with WebSockets, check out Ratchet.

Where do I find the Instagram media ID of a image

In pure JS (provided your browser can handle XHRs, which every major browser [including IE > 6] can):

function igurlretrieve(url) {

  var urldsrc = "http://api.instagram.com/oembed?url=" + url;

  //fetch data from URL data source
  var x = new XMLHttpRequest();
  x.open('GET', urldsrc, true);
  x.send();

  //load resulting JSON data as JS object
  var urldata = JSON.parse(x.responseText);

  //reconstruct data as "instagram://" URL that can be opened in iOS app
  var reconsturl = "instagram://media?id=" + urldata.media_id;
  return reconsturl;

}

Provided this is your goal -- simply opening the page in the Instagram iOS app, which is exactly what this is about -- this should do, especially if you don't want to have to endure licensing fees.

How do I download NLTK data?

It's very simple....

  1. Open pyScripter or any editor
  2. Create a python file eg: install.py
  3. write the below code in it.
import nltk
nltk.download()
  1. A pop-up window will apper and click on download .

The download window]

API vs. Webservice

Basically, a webservice is a method of communication between two machines while an API is an exposed layer allowing you to program against something.

You could very well have an API and the main method of interacting with that API is via a webservice.

The technical definitions (courtesy of Wikipedia) are:

API

An application programming interface (API) is a set of routines, data structures, object classes and/or protocols provided by libraries and/or operating system services in order to support the building of applications.

Webservice

A Web service (also Web Service) is defined by the W3C as "a software system designed to support interoperable machine-to-machine interaction over a network"

Reading Excel files from C#

I did a lot of reading from Excel files in C# a while ago, and we used two approaches:

  • The COM API, where you access Excel's objects directly and manipulate them through methods and properties
  • The ODBC driver that allows to use Excel like a database.

The latter approach was much faster: reading a big table with 20 columns and 200 lines would take 30 seconds via COM, and half a second via ODBC. So I would recommend the database approach if all you need is the data.

Cheers,

Carl

How to use *ngIf else?

<div *ngIf="show; else elseBlock">Text to show</div>
<ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>

How do I include a newline character in a string in Delphi?

Sometimes I don't want to clutter up my code space, especially for a static label. To just have it defined with the form, enter the label text on the form, then right click anywhere on the same form. Choose "View as Text". You will now see all of the objects as designed, but as text only. Scroll down or search for your text. When you find it, edit the caption, so it looks something like:

Caption = 'Line 1'#13'Line 2'#13'Line 3'

#13 means an ordinal 13, or ascii for carriage return. Chr(13) is the same idea, CHR() changes the number to an ordinal type.

Note that there are no semi-colon's in this particular facet of Delphi, and "=" is used rather than ":=". The text for each line is enclosed in single quotes.

Once you are done, right-click once again and choose "View as Form". You can now do any formatting such as bold, right justify, etc. You just can't re-edit the text on the form or you will lose your line breaks.

I also use "View as Text" for multiple changes where I just want to scroll through and do replacements, etc. Quick.

Dave

Datagrid binding in WPF

Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
    <DataGrid.Columns>                
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

String representation of an Enum

I use an extension method:

public static class AttributesHelperExtension
    {
        public static string ToDescription(this Enum value)
        {
            var da = (DescriptionAttribute[])(value.GetType().GetField(value.ToString())).GetCustomAttributes(typeof(DescriptionAttribute), false);
            return da.Length > 0 ? da[0].Description : value.ToString();
        }
}

Now decorate the enum with:

public enum AuthenticationMethod
{
    [Description("FORMS")]
    FORMS = 1,
    [Description("WINDOWSAUTHENTICATION")]
    WINDOWSAUTHENTICATION = 2,
    [Description("SINGLESIGNON ")]
    SINGLESIGNON = 3
}

When you call

AuthenticationMethod.FORMS.ToDescription() you will get "FORMS".

TypeError: object of type 'int' has no len() error assistance needed

Abstract:

The reason why you are getting this error message is because you are trying to call a method on an int type of a variable. This would work if would have called len() function on a list type of a variable. Let's examin the two cases:

Fail:

num = 10

print(len(num))

The above will produce an error similar to yours due to calling len() function on an int type of a variable;

Success:

data = [0, 4, 8, 9, 12]

print(len(data))

The above will work since you are calling a function on a list type of a variable;

Close Window from ViewModel

it may be late, but here is my answer

foreach (Window item in Application.Current.Windows)
{
    if (item.DataContext == this) item.Close();
}

Angular 5 Button Submit On Enter Key Press

In addition to other answers which helped me, you can also add to surrounding div. In my case this was for sign on with user Name/Password fields.

<div (keyup.enter)="login()" class="container-fluid">

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

Create table in SQLite only if it doesn't exist already

Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).

        # for completeness lets do the routine thing of connections and cursors
        conn = sqlite3.connect(db_file, timeout=1000) 

        cursor = conn.cursor() 

        # get the count of tables with the name  
        tablename = 'KABOOM' 
        cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))

        print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.

        # check if the db has existing table named KABOOM
        # if the count is 1, then table exists 
        if cursor.fetchone()[0] ==1 : 
            print('Table exists. I can do my custom stuff here now.... ')
            pass
        else: 
           # then table doesn't exist. 
           custRET = myCustFunc(foo,bar) # replace this with your custom logic

PHP include relative path

You could always include it using __DIR__:

include(dirname(__DIR__).'/config.php');

__DIR__ is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__. In this case, as we need to ascend a directory we use PHP's dirname which ascends the file tree, and from here we can access config.php.

You could set the root path in this method too:

define('ROOT_PATH', dirname(__DIR__) . '/');

in test.php would set your root to be at the /root/ level.

include(ROOT_PATH.'config.php');

Should then work to include the config file from where you want.

Use of Application.DoEvents()

I saw jheriko's comment above and was initially agreeing that I couldn't find a way to avoid using DoEvents if you end up spinning your main UI thread waiting for a long running asynchronous piece of code on another thread to complete. But from Matthias's answer a simple Refresh of a small panel on my UI can replace the DoEvents (and avoid a nasty side effect).

More detail on my case ...

I was doing the following (as suggested here) to ensure that a progress bar type splash screen (How to display a "loading" overlay...) updated during a long running SQL command:

IAsyncResult asyncResult = sqlCmd.BeginExecuteNonQuery();
while (!asyncResult.IsCompleted)  //UI thread needs to Wait for Async SQL command to return
{
      System.Threading.Thread.Sleep(10); 
      Application.DoEvents();  //to make the UI responsive
}

The bad: For me calling DoEvents meant that mouse clicks were sometimes firing on forms behind my splash screen, even if I made it TopMost.

The good/answer: Replace the DoEvents line with a simple Refresh call to a small panel in the centre of my splash screen, FormSplash.Panel1.Refresh(). The UI updates nicely and the DoEvents weirdness others have warned of was gone.

Slide right to left?

An example of right to left animation without jQuery UI, just with jQuery (any version, see https://api.jquery.com/animate/).

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var contentLastMarginLeft = 0;_x000D_
  $(".wrap").click(function() {_x000D_
    var box = $(".content");_x000D_
    var newValue = contentLastMarginLeft;_x000D_
    contentLastMarginLeft = box.css("margin-left");_x000D_
    box.animate({_x000D_
      "margin-left": newValue_x000D_
    }, 500);_x000D_
  });_x000D_
});
_x000D_
.wrap {_x000D_
  background-color: #999;_x000D_
  width: 200px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
.content {_x000D_
  width: 100%;_x000D_
  margin-left: 100%;_x000D_
  background-color: #eee;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrap">_x000D_
  click here_x000D_
  <div class="content">_x000D_
    I would like to have a div go from collapsed to expanded (and vice versa), but do so from right to left. Most everything I see out there is always left to right._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS to hide INPUT BUTTON value text

color:transparent; and then any text-transform property does the trick too.

For example:

color: transparent;
text-transform: uppercase;

Waiting for Target Device to Come Online

For Linux users using KVM and facing this problem try setting the Graphics option on the Android Virtual Device to Software instead of Automatic or Hardware . As previously mentioned in this answer.

I can confirm that the method works for Arch Linux, Ubuntu 16.04, as well as windows with or without a proprietary graphics card using Android Studio version 2.3.1+

PHP Composer update "cannot allocate memory" error (using Laravel 4)

I solved the same problem in Vagrant. I increased the value of memory_limit and delete composer cache: sudo rm -R ~/.composer and finally vagrant reload.

How to compile C programming in Windows 7?

You can get MinGW (as others have suggested) but I would recommend getting a simple IDE (not VS Express). You can try Dev C++ http://www.bloodshed.net/devcpp.html Its a simple IDE for C/C++ and uses MinGW internally. In this you can write and compile single C files without creating a full-blown "project".

How to replace multiple white spaces with one white space

As already pointed out, this is easily done by a regular expression. I'll just add that you might want to add a .trim() to that to get rid of leading/trailing whitespace.

HTML not loading CSS file

Add type="text/css" It worked for me.

How to use EditText onTextChanged event when I press the number?

You have selected correct approach. You have to extend the class with TextWatcher and override afterTextChanged(),beforeTextChanged(), onTextChanged().

You have to write your desired logic in afterTextChanged() method to achieve functionality needed by you.

jQuery - What are differences between $(document).ready and $(window).load?

$(document).ready(function(e) { 
    // executes when HTML-Document is loaded and DOM is ready  
    console.log("page is loading now"); 
});

$(document).load(function(e) { 
    //when html page complete loaded
    console.log("completely loaded"); 
});

Docker: How to delete all local Docker images

To simple clear everything do:

$ docker system prune --all

Everything means:

  • all stopped containers
  • all networks not used by at least one container
  • all images without at least one container associated to them
  • all build cache

Moving from one activity to another Activity in Android

You can do

Intent i = new Intent(classname.this , targetclass.class);
startActivity(i);

Why does Math.Round(2.5) return 2 instead of 3?

This post has the answer you are looking for:

http://weblogs.asp.net/sfurman/archive/2003/03/07/3537.aspx

Basically this is what it says:

Return Value

The number nearest value with precision equal to digits. If value is halfway between two numbers, one of which is even and the other odd, then the even number is returned. If the precision of value is less than digits, then value is returned unchanged.

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. If digits is zero, this kind of rounding is sometimes called rounding toward zero.

What's the difference between deadlock and livelock?

Imagine you've thread A and thread B. They are both synchronised on the same object and inside this block there's a global variable they are both updating;

static boolean commonVar = false;
Object lock = new Object;

...

void threadAMethod(){
    ...
    while(commonVar == false){
         synchornized(lock){
              ...
              commonVar = true
         }
    }
}

void threadBMethod(){
    ...
    while(commonVar == true){
         synchornized(lock){
              ...
              commonVar = false
         }
    }
}

So, when thread A enters in the while loop and holds the lock, it does what it has to do and set the commonVar to true. Then thread B comes in, enters in the while loop and since commonVar is true now, it is be able to hold the lock. It does so, executes the synchronised block, and sets commonVar back to false. Now, thread A again gets it's new CPU window, it was about to quit the while loop but thread B has just set it back to false, so the cycle repeats over again. Threads do something (so they're not blocked in the traditional sense) but for pretty much nothing.

It maybe also nice to mention that livelock does not necessarily have to appear here. I'm assuming that the scheduler favours the other thread once the synchronised block finish executing. Most of the time, I think it's a hard-to-hit expectation and depends on many things happening under the hood.

Trim spaces from end of a NSString

let string = " Test Trimmed String "

For Removing white Space and New line use below code :-

let str_trimmed = yourString.trimmingCharacters(in: .whitespacesAndNewlines)

For Removing only Spaces from string use below code :-

let str_trimmed = yourString.trimmingCharacters(in: .whitespaces)

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

I think you want to speed up your cell loading at the time of image loading for cell in the background. For that we have done the following steps:

  1. Checking the file exists in the document directory or not.

  2. If not then loading the image for the first time, and saving it to our phone document directory. If you don't want to save the image in the phone then you can load cell images directlyin the background.

  3. Now the loading process:

Just include: #import "ManabImageOperations.h"

The code is like below for a cell:

NSString *imagestr=[NSString stringWithFormat:@"http://www.yourlink.com/%@",[dictn objectForKey:@"member_image"]];

        NSString *docDir=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
        NSLog(@"Doc Dir: %@",docDir);

        NSString  *pngFilePath = [NSString stringWithFormat:@"%@/%@",docDir,[dictn objectForKey:@"member_image"]];

        BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:pngFilePath];
        if (fileExists)
        {
            [cell1.memberimage setImage:[UIImage imageWithContentsOfFile:pngFilePath] forState:UIControlStateNormal];
        }
        else
        {
            [ManabImageOperations processImageDataWithURLString:imagestr andBlock:^(NSData *imageData)
             {
                 [cell1.memberimage setImage:[[UIImage alloc]initWithData: imageData] forState:UIControlStateNormal];
                [imageData writeToFile:pngFilePath atomically:YES];
             }];
}

ManabImageOperations.h:

#import <Foundation/Foundation.h>

    @interface ManabImageOperations : NSObject
    {
    }
    + (void)processImageDataWithURLString:(NSString *)urlString andBlock:(void (^)(NSData *imageData))processImage;
    @end

ManabImageOperations.m:

#import "ManabImageOperations.h"
#import <QuartzCore/QuartzCore.h>
@implementation ManabImageOperations

+ (void)processImageDataWithURLString:(NSString *)urlString andBlock:(void (^)(NSData *imageData))processImage
{
    NSURL *url = [NSURL URLWithString:urlString];

    dispatch_queue_t callerQueue = dispatch_get_main_queue();
    dispatch_queue_t downloadQueue = dispatch_queue_create("com.myapp.processsmagequeue", NULL);
    dispatch_async(downloadQueue, ^{
        NSData * imageData = [NSData dataWithContentsOfURL:url];

        dispatch_async(callerQueue, ^{
            processImage(imageData);
        });
    });
  //  downloadQueue=nil;
    dispatch_release(downloadQueue);

}
@end

Please check the answer and comment if there is any problem occurs....

Python: Figure out local timezone

I was asking the same to myself, and I found the answer in 1:

Take a look at section 8.1.7: the format "%z" (lowercase, the Z uppercase returns also the time zone, but not in the 4-digit format, but in the form of timezone abbreviations, like in [3]) of strftime returns the form "+/- 4DIGIT" that is standard in email headers (see section 3.3 of RFC 2822, see [2], which obsoletes the other ways of specifying the timezone for email headers).

So, if you want your timezone in this format, use:

time.strftime("%z")

[1] http://docs.python.org/2/library/datetime.html

[2] http://tools.ietf.org/html/rfc2822#section-3.3

[3] Timezone abbreviations: http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations , only for reference.

select dept names who have more than 2 employees whose salary is greater than 1000

How about something like this?

SELECT D.DeptName FROM
Department D WHERE (SELECT COUNT(*) 
                    FROM Employee E 
                    WHERE E.DeptID = D.DeptID AND
                            E.Salary > 1000) > 2

Negate if condition in bash script

If you're feeling lazy, here's a terse method of handling conditions using || (or) and && (and) after the operation:

wget -q --tries=10 --timeout=20 --spider http://google.com || \
{ echo "Sorry you are Offline" && exit 1; }

How to run or debug php on Visual Studio Code (VSCode)

XDebug changed some configuration settings.

Old settings:

xdebug.remote_enable = 1
xdebug.remote_autostart = 1
xdebug.remote_port = 9000

New settings:

xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.client_port=9000

So you should paste the latter in php.ini file. More info: XDebug Changed Configuration Settings

How to send SMS in Java

It depends on how you're going to work and who your provider is.

If you work with a sms-gateway company you'll probably work through SMPP protocol (3.4 is still the most common), then have a look on OpenSMPP and jSMPP. These are powerful libs to work with SMPP.

If you're going to work with your own hardware (f.e. a gsm-modem) the easiest way to send messages is through AT commands, they differ depends on the model, so, you should find out what AT commands is supported by your modem. Next, if your modem has an IP and open to connection, you can send commands through java socket

Socket smppSocket = new Socket("YOUR_MODEM_IP", YOUR_MODEM_PORT);
DataOutputStream os = new DataOutputStream(smppSocket.getOutputStream());
DataInputStream is = new DataInputStream(smppSocket.getInputStream());

os.write(some_byte_array[]);
is.readLine();

Otherwise you'll work through a COM port, but the method is the same (sending AT commands), you can find more information how to work with serial ports here.

How to load specific image from assets with Swift

You can easily pick image from asset without UIImage(named: "green-square-Retina").

Instead use the image object directly from bundle.
Start typing the image name and you will get suggestions with actual image from bundle. It is advisable practice and less prone to error.

See this Stackoverflow answer for reference.

Query to convert from datetime to date mysql

syntax of date_format:

SELECT date_format(date_born, '%m/%d/%Y' ) as my_date FROM date_tbl

    '%W %D %M %Y %T'    -> Wednesday 5th May 2004 23:56:25
    '%a %b %e %Y %H:%i' -> Wed May 5 2004 23:56
    '%m/%d/%Y %T'       -> 05/05/2004 23:56:25
    '%d/%m/%Y'          -> 05/05/2004
    '%m-%d-%y'          -> 04-08-13

How to select where ID in Array Rails ActiveRecord without exception

If you need more control (perhaps you need to state the table name) you can also do the following:

Model.joins(:another_model_table_name)
  .where('another_model_table_name.id IN (?)', your_id_array)

Create a text file for download on-the-fly

Check out this SO question's accepted solution. Substitute your own filename for basename($File) and change filesize($File) to strlen($your_string). (You may want to use mb_strlen just in case the string contains multibyte characters.)

How to print table using Javascript?

Here is your code in a jsfiddle example. I have tested it and it looks fine.

http://jsfiddle.net/dimshik/9DbEP/4/

I used a simple table, maybe you are missing some CSS on your new page that was created with JavaScript.

<table border="1" cellpadding="3" id="printTable">
    <tbody><tr>
        <th>First Name</th>
        <th>Last Name</th>      
        <th>Points</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>      
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>        
        <td>94</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Doe</td>        
        <td>80</td>
    </tr>
    <tr>
        <td>Adam</td>
        <td>Johnson</td>        
        <td>67</td>
    </tr>
</tbody></table>

android get real path by Uri.getPath()

@Rene Juuse - above in comments... Thanks for this link !

. the code to get the real path is a bit different from one SDK to another so below we have three methods that deals with different SDKs.

getRealPathFromURI_API19(): returns real path for API 19 (or above but not tested) getRealPathFromURI_API11to18(): returns real path for API 11 to API 18 getRealPathFromURI_below11(): returns real path for API below 11

public class RealPathUtil {

@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
    String filePath = "";
    String wholeID = DocumentsContract.getDocumentId(uri);

     // Split at colon, use second item in the array
     String id = wholeID.split(":")[1];

     String[] column = { MediaStore.Images.Media.DATA };     

     // where id is equal to             
     String sel = MediaStore.Images.Media._ID + "=?";

     Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                               column, sel, new String[]{ id }, null);

     int columnIndex = cursor.getColumnIndex(column[0]);

     if (cursor.moveToFirst()) {
         filePath = cursor.getString(columnIndex);
     }   
     cursor.close();
     return filePath;
}


@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
      String[] proj = { MediaStore.Images.Media.DATA };
      String result = null;

      CursorLoader cursorLoader = new CursorLoader(
              context, 
        contentUri, proj, null, null, null);        
      Cursor cursor = cursorLoader.loadInBackground();

      if(cursor != null){
       int column_index = 
         cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       cursor.moveToFirst();
       result = cursor.getString(column_index);
      }
      return result;  
}

public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
           String[] proj = { MediaStore.Images.Media.DATA };
           Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
           int column_index
      = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
           cursor.moveToFirst();
           return cursor.getString(column_index);
}

font: http://hmkcode.com/android-display-selected-image-and-its-real-path/


UPDATE 2016 March

To fix all problems with path of images i try create a custom gallery as facebook and other apps. This is because you can use just local files ( real files, not virtual or temporary) , i solve all problems with this library.

https://github.com/nohana/Laevatein (this library is to take photo from camera or choose from galery , if you choose from gallery he have a drawer with albums and just show local files)

How can I get input radio elements to horizontally align?

To get your radio button to list horizontally , just add

RepeatDirection="Horizontal"

to your .aspx file where the asp:radiobuttonlist is being declared.

anaconda - path environment variable in windows

Instead of giving the path following way:

C:\Users\User_name\AppData\Local\Continuum\anaconda3\python.exe

Do this:

C:\Users\User_name\AppData\Local\Continuum\anaconda3\

Basic HTTP and Bearer Token Authentication

I had a similar problem - authenticate device and user at device. I used a Cookie header alongside an Authorization: Bearer... header. One header authenticated the device, the other authenticated the user. I used a Cookie header because these are commonly used for authentication.

What is the difference between function and procedure in PL/SQL?

  1. we can call a stored procedure inside stored Procedure,Function within function ,StoredProcedure within function but we can not call function within stored procedure.
  2. we can call function inside select statement.
  3. We can return value from function without passing output parameter as a parameter to the stored procedure.

This is what the difference i found. Please let me know if any .

How do I remove all null and empty string values from an object?

Using some ES6 / ES2015:

If you don't like to create an extra function and remove the items 'inline'.

Object.keys(obj).forEach(k => (!obj[k] && obj[k] !== undefined) && delete obj[k]);

jsbin

Same, written as a function.

const removeEmpty = (obj) => {
  Object.keys(obj).forEach((k) => (!obj[k] && obj[k] !== undefined) && delete obj[k]);
  return obj;
};

jsbin

This function uses recursion to delete items from nested objects as well:

const removeEmpty = (obj) => {
  Object.keys(obj).forEach(k =>
    (obj[k] && typeof obj[k] === 'object') && removeEmpty(obj[k]) ||
    (!obj[k] && obj[k] !== undefined) && delete obj[k]
  );
  return obj;
};

jsbin

Same as function before but with ES7 / 2016 Object.entries:

const removeEmpty = (obj) => {
  Object.entries(obj).forEach(([key, val])  =>
    (val && typeof val === 'object') && removeEmpty(val) ||
    (val === null || val === "") && delete obj[key]
  );
  return obj;
};

Same as third example but in plain ES5:

function removeEmpty(obj) {
  Object.keys(obj).forEach(function(key) {
    (obj[key] && typeof obj[key] === 'object') && removeEmpty(obj[key]) ||
    (obj[key] === '' || obj[key] === null) && delete obj[key]
  });
  return obj;
};

jsbin

How to secure the ASP.NET_SessionId cookie?

Found that setting the secure property in Session_Start is sufficient, as recommended in MSDN blog "Securing Session ID: ASP/ASP.NET" with some augmentation.

    protected void Session_Start(Object sender, EventArgs e)
    {
        SessionStateSection sessionState = 
 (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
        string sidCookieName = sessionState.CookieName;

        if (Request.Cookies[sidCookieName] != null)
        {
            HttpCookie sidCookie = Response.Cookies[sidCookieName];
            sidCookie.Value = Session.SessionID;
            sidCookie.HttpOnly = true;
            sidCookie.Secure = true;
            sidCookie.Path = "/";
        }
    }

How can I create C header files

  1. Open your favorite text editor
  2. Create a new file named whatever.h
  3. Put your function prototypes in it

DONE.

Example whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once but it is not guaranteed to be supported on every compiler.

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.

Like this:

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it (if you use GCC):

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

You can test sample:

$ ./sample
3
$

animating addClass/removeClass with jQuery

Although, the question is fairly old, I'm adding info not present in other answers.

The OP is using stop() to stop the current animation as soon as the event completes. However, using the right mix of parameters with the function should help. eg. stop(true,true) or stop(true,false) as this affects the queued animations well.

The following link illustrates a demo that shows the different parameters available with stop() and how they differ from finish().

http://api.jquery.com/finish/

Although the OP had no issues using JqueryUI, this is for other users who may come across similar scenarios but cannot use JqueryUI/need to support IE7 and 8 too.

Getting 400 bad request error in Jquery Ajax POST

Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.

400 Bad Request

Bad Request. Your browser sent a request that this server could not understand.

Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.

415 Unsupported Media Type

Try this.

var newData =   {
                  "subject:title":"Test Name",
                  "subject:description":"Creating test subject to check POST method API",
                  "sub:tags": ["facebook:work", "facebook:likes"],
                  "sampleSize" : 10,
                  "values": ["science", "machine-learning"]
                  };

var dataJson = JSON.stringify(newData);

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: dataJson,
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.

How to set user environment variables in Windows Server 2008 R2 as a normal user?

You can also use this direct command line to open the Advanced System Properties:

sysdm.cpl

Then go to the Advanced Tab -> Environment Variables

Execute a batch file on a remote PC using a batch file on local PC

Use microsoft's tool for remote commands executions: PsExec

If there isn't your bat-file on remote host, copy it first. For example:

copy D:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat \\RemoteServerNameOrIP\d$\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\

And then execute:

psexec \\RemoteServerNameOrIP d:\apache-tomcat-6.0.20\apache-tomcat-7.0.30\bin\shutdown.bat

Note: filepath for psexec is path to file on remote server, not your local.

How to verify if nginx is running or not?

For Mac users

I found out one more way: You can check if /usr/local/var/run/nginx.pid exists. If it is - nginx is running. Useful way for scripting.

Example:

if [ -f /usr/local/var/run/nginx.pid ]; then
   echo "Nginx is running"

fi

Make content horizontally scroll inside a div

if you remove the float: left from the a and add white-space: nowrap to the outer div

#myWorkContent{
    width:530px;
    height:210px;
    border: 13px solid #bed5cd;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
}
#myWorkContent a {
    display: inline;
}

this should work for any size or amount of images..

or even:

#myWorkContent a {
    display: inline-block;
    vertical-align: middle;
}

which would also vertically align images of different heights if required

test code

How to disable Compatibility View in IE

All you need is to force disable C.M. in IE - Just paste This code (in IE9 and under c.m. will be disabled):

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

Source: http://twigstechtips.blogspot.com/2010/03/css-ie8-meta-tag-to-disable.html

Parsing XML with namespace in Python via 'ElementTree'

I've been using similar code to this and have found it's always worth reading the documentation... as usual!

findall() will only find elements which are direct children of the current tag. So, not really ALL.

It might be worth your while trying to get your code working with the following, especially if you're dealing with big and complex xml files so that that sub-sub-elements (etc.) are also included. If you know yourself where elements are in your xml, then I suppose it'll be fine! Just thought this was worth remembering.

root.iter()

ref: https://docs.python.org/3/library/xml.etree.elementtree.html#finding-interesting-elements "Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag, and Element.text accesses the element’s text content. Element.get() accesses the element’s attributes:"

How can I parse a CSV string with JavaScript, which contains comma in data?

I have also faced the same type of problem when I had to parse a CSV file.

The file contains a column address which contains the ',' .

After parsing that CSV file to JSON, I get mismatched mapping of the keys while converting it into a JSON file.

I used Node.js for parsing the file and libraries like baby parse and csvtojson.

Example of file -

address,pincode
foo,baar , 123456

While I was parsing directly without using baby parse in JSON, I was getting:

[{
 address: 'foo',
 pincode: 'baar',
 'field3': '123456'
}]

So I wrote code which removes the comma(,) with any other delimiter with every field:

_x000D_
_x000D_
/*
 csvString(input) = "address, pincode\\nfoo, bar, 123456\\n"
 output = "address, pincode\\nfoo {YOUR DELIMITER} bar, 123455\\n"
*/
const removeComma = function(csvString){
    let delimiter = '|'
    let Baby = require('babyparse')
    let arrRow = Baby.parse(csvString).data;
    /*
      arrRow = [
      [ 'address', 'pincode' ],
      [ 'foo, bar', '123456']
      ]
    */
    return arrRow.map((singleRow, index) => {
        //the data will include
        /*
        singleRow = [ 'address', 'pincode' ]
        */
        return singleRow.map(singleField => {
            //for removing the comma in the feild
            return singleField.split(',').join(delimiter)
        })
    }).reduce((acc, value, key) => {
        acc = acc +(Array.isArray(value) ?
         value.reduce((acc1, val)=> {
            acc1 = acc1+ val + ','
            return acc1
        }, '') : '') + '\n';
        return acc;
    },'')
}
_x000D_
_x000D_
_x000D_

The function returned can be passed into the csvtojson library and thus the result can be used.

_x000D_
_x000D_
const csv = require('csvtojson')

let csvString = "address, pincode\\nfoo, bar, 123456\\n"
let jsonArray = []
modifiedCsvString = removeComma(csvString)
csv()
  .fromString(modifiedCsvString)
  .on('json', json => jsonArray.push(json))
  .on('end', () => {
    /* do any thing with the json Array */
  })
_x000D_
_x000D_
_x000D_

Now you can get the output like:

[{
  address: 'foo, bar',
  pincode: 123456
}]

How to remove multiple indexes from a list at the same time?

another option (in place, any combination of indices):

_marker = object()

for i in indices:
    my_list[i] = _marker  # marked for deletion

obj[:] = [v for v in my_list if v is not _marker]

How to make my font bold using css?

You can use the strong element in html, which is great semantically (also good for screen readers etc.), which typically renders as bold text:

_x000D_
_x000D_
See here, some <strong>emphasized text</strong>.
_x000D_
_x000D_
_x000D_

Or you can use the font-weight css property to style any element's text as bold:

_x000D_
_x000D_
span { font-weight: bold; }
_x000D_
<p>This is a paragraph of <span>bold text</span>.</p>
_x000D_
_x000D_
_x000D_

How to change or add theme to Android Studio?

Windows

File->Settings->Editor->Colors & Fonts->

Mac OSX

Android Studio -> Preferences->Editor->Colors&Fonts

Android: how to make keyboard enter button say "Search" and handle its click?

In Kotlin

evLoginPassword.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        doTheLoginWork()
    }
    true
}

Partial Xml Code

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
       <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="24dp"
            android:paddingRight="24dp">

            <EditText
                android:id="@+id/evLoginUserEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
                android:textColor="@color/black_54_percent" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="24dp"
            android:paddingRight="24dp">

            <EditText
                android:id="@+id/evLoginPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/password"
                android:inputType="textPassword"
                android:imeOptions="actionDone"
                android:textColor="@color/black_54_percent" />
        </android.support.design.widget.TextInputLayout>
</LinearLayout>

Google Chrome form autofill and its yellow background

This fixes the problem on both Safari and Chrome

if(navigator.userAgent.toLowerCase().indexOf("chrome") >= 0 || navigator.userAgent.toLowerCase().indexOf("safari") >= 0){
window.setInterval(function(){
    $('input:-webkit-autofill').each(function(){
        var clone = $(this).clone(true, true);
        $(this).after(clone).remove();
    });
}, 20);
}

How to delete projects in Intellij IDEA 14?

1. Choose project, right click, in context menu, choose Show in Explorer (on Mac, select Reveal in Finder).

enter image description here

2. Choose menu File \ Close Project

enter image description here

3. In Windows Explorer, press Del or Shift+Del for permanent delete.

4. At IntelliJ IDEA startup windows, hover cursor on old project name (what has been deleted) press Del for delelte.

enter image description here

How to add a scrollbar to an HTML5 table?

I first tried the accepted answer by Mr Green, but I found my columns didn't align, that float:left seems very suspicious. When I went from no scollbar to scrollbar -- my table body shifted a few pixels and I lost alignment.

CODE PEN https://codepen.io/majorp/pen/gjrRMx

CSS

.width50px {
    width: 100px !important;
}

.width100px {
    width: 100px !important;
}


.fixed_headers {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;
}

th {
    padding: 5px;
    text-align: left;
    font-weight:bold;
    height:50px;
}

td {
    padding: 5px;
    text-align: left;
}

thead, tr 
{
    display: block;
    position: relative;
}


tbody {
    display: block;
    overflow: auto;
    width: 100%;
    height: 500px;
}

.tableColumnHeader {
    height: 50px;
    font-weight: bold;
}




.lime {
    background-color: lime;
}

$(document).click() not working correctly on iPhone. jquery

try this, applies only to iPhone and iPod so you're not making everything turn blue on chrome or firefox mobile;

/iP/i.test(navigator.userAgent) && $('*').css('cursor', 'pointer');

basically, on iOS, things aren't "clickable" by default -- they're "touchable" (pfffff) so you make them "clickable" by giving them a pointer cursor. makes total sense, right??

keyword not supported data source

I was getting the same problem.
but this code works good try it.

<add name="MyCon" connectionString="Server=****;initial catalog=PortalDb;user id=**;password=**;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />

how to re-format datetime string in php?

date("Y-m-d H:i:s", strtotime("2019-05-13"))

Reading file using fscanf() in C

scanf() and friends return the number of input items successfully matched. For your code, that would be two or less (in case of less matches than specified). In short, be a little more careful with the manual pages:

#include <stdio.h>
#include <errno.h>
#include <stdbool.h>

int main(void)
{
    char item[9], status;

    FILE *fp;

    if((fp = fopen("D:\\Sample\\database.txt", "r+")) == NULL) {
        printf("No such file\n");
        exit(1);
    }

    while (true) {
        int ret = fscanf(fp, "%s %c", item, &status);
        if(ret == 2)
            printf("\n%s \t %c", item, status);
        else if(errno != 0) {
            perror("scanf:");
            break;
        } else if(ret == EOF) {
            break;
        } else {
            printf("No match.\n");
        }
    }
    printf("\n");
    if(feof(fp)) {
        puts("EOF");
    }
    return 0;
}

Usage of MySQL's "IF EXISTS"

if exists(select * from db1.table1 where sno=1 )
begin
select * from db1.table1 where sno=1 
end
else if (select * from db2.table1 where sno=1 )
begin
select * from db2.table1 where sno=1 
end
else
begin
print 'the record does not exits'
end

Where to download visual studio express 2005?

Small tip for you. Microsoft frequently has 'launch parties' or 'launch events' in which they frequently distribute licensed, not for resale copies, of that product. I've gotten the last two versions of VS (2005 and 2008) by attending my local .NET user group chapter during those days.

Spring Boot Remove Whitelabel Error Page

Manual here says that you have to set server.error.whitelabel.enabled to false to disable the standard error page. Maybe it is what you want?

I am experiencing the same error after adding /error mapping, by the way.

Stretch and scale a CSS image in the background - with CSS only

I wanted to center and scale a background image, without stretching it to the entire page, and I wanted the aspect ratio to be maintained. This worked for me, thanks to the variations suggested in other answers:

INLINE IMAGE: ------------------------

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS ----------------------------------

html {
    height:100%;
}

#background {
    text-align: center;
    width: 100%; 
    height: 100%; 
    position: fixed;
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

.stretch {
    margin: auto;
    height:100%;
}

Java's L number (long) specification

There are specific suffixes for long (e.g. 39832L), float (e.g. 2.4f) and double (e.g. -7.832d).

If there is no suffix, and it is an integral type (e.g. 5623), it is assumed to be an int. If it is not an integral type (e.g. 3.14159), it is assumed to be a double.

In all other cases (byte, short, char), you need the cast as there is no specific suffix.

The Java spec allows both upper and lower case suffixes, but the upper case version for longs is preferred, as the upper case L is less easy to confuse with a numeral 1 than the lower case l.

See the JLS section 3.10 for the gory details (see the definition of IntegerTypeSuffix).

How to copy a selection to the OS X clipboard

I am currently on OS X 10.9 and my efforts to compile vim with +xterm_clipboard brought me nothing. So my current solution is to use MacVim in terminal mode with option set clipboard=unnamed in my ~/.vimrc file. Works perfect for me.

Disable form autofill in Chrome without disabling autocomplete

This might help: https://stackoverflow.com/a/4196465/683114

if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
    $(window).load(function(){
        $('input:-webkit-autofill').each(function(){
            var text = $(this).val();
            var name = $(this).attr('name');
            $(this).after(this.outerHTML).remove();
            $('input[name=' + name + ']').val(text);
        });
    });
}

It looks like on load, it finds all inputs with autofill, adds their outerHTML and removes the original, while preserving value and name (easily changed to preserve ID etc)

If this preserves the autofill text, you could just set

var text = "";   /* $(this).val(); */

From the original form where this was posted, it claims to preserve autocomplete. :)

Good luck!

Android view pager with page indicator

Here are a few things you need to do:

1-Download the library if you haven't already done that.

2- Import into Eclipse.

3- Set you project to use the library: Project-> Properties -> Android -> Scroll down to Library section, click Add... and select viewpagerindicator.

4- Now you should be able to import com.viewpagerindicator.TitlePageIndicator.

Now about implementing this without using fragments:

In the sample that comes with viewpagerindicatior, you can see that the library is being used with a ViewPager which has a FragmentPagerAdapter.

But in fact the library itself is Fragment independant. It just needs a ViewPager. So just use a PagerAdapter instead of a FragmentPagerAdapter and you're good to go.

How can I count occurrences with groupBy?

List<String> list = new ArrayList<>();

list.add("Hello");
list.add("Hello");
list.add("World");

Map<String, List<String>> collect = list.stream()
                                        .collect(Collectors.groupingBy(o -> o));
collect.entrySet()
       .forEach(e -> System.out.println(e.getKey() + " - " + e.getValue().size()));

Renaming files in a folder to sequential numbers

Nowadays there is an option after you select multiple files for renaming (I have seen in thunar file manager).

  1. select multiple files
  2. check options
  3. select rename

A prompt comes with all files in that particular dir just check with the category section

Why do package names often begin with "com"

It's the domain name spelt out in reverse.

For example, one of my domains is hedgee.com. So, I use com.hedgee as the base name of all my packages.

Passing an Object from an Activity to a Fragment

To pass an object to a fragment, do the following:

First store the objects in Bundle, don't forget to put implements serializable in class.

            CategoryRowFragment fragment = new CategoryRowFragment();

            // pass arguments to fragment
            Bundle bundle = new Bundle();

            // event list we want to populate
            bundle.putSerializable("eventsList", eventsList);

            // the description of the row
            bundle.putSerializable("categoryRow", categoryRow);

            fragment.setArguments(bundle);

Then retrieve bundles in Fragment

_x000D_
_x000D_
       // events that will be populated in this row_x000D_
        mEventsList = (ArrayList<Event>)getArguments().getSerializable("eventsList");_x000D_
_x000D_
        // description of events to be populated in this row_x000D_
        mCategoryRow = (CategoryRow)getArguments().getSerializable("categoryRow");
_x000D_
_x000D_
_x000D_

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

This solves the problem for me. It's easy and pretty simply explained.

Step 1

  • Right click on project
  • Click on Properties

Step 2

  • Click on Deployment Assembly Tab in the
  • Click Add...

Step 3

  • Click on Java Build Path Entries

Step 4

  • Click on Maven Dependencies
  • Click Finish button

Step 5

  • Redeploy Spring MVC application to Tomcat again
  • Restart Tomcat
  • List item

classnotfoundexception

angular-cli server - how to proxy API requests to another server?

In case if someone is looking for multiple context entries to the same target or TypeScript based configuration.

proxy.conf.ts

const proxyConfig = [
  {
    context: ['/api/v1', '/api/v2],
    target: 'https://example.com',
    secure: true,
    changeOrigin: true
  },
  {
    context: ['**'], // Rest of other API call
    target: 'http://somethingelse.com',
    secure: false,
    changeOrigin: true
  }
];

module.exports = proxyConfig;

ng serve --proxy-config=./proxy.conf.ts -o

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

If you are using WebStorm and you are on Windows i would recommend you to click settings/editor/code style/general tab and select "windows(\r\n) from the dropdown menu.These steps will also apply for Rider.

enter image description here

How to JSON decode array elements in JavaScript?

JSON decoding in JavaScript is simply an eval() if you trust the string or the more safe code you can find on http://json.org if you don't.

You will then have a JavaScript datastructure that you can traverse for the data you need.

Text to speech(TTS)-Android

A minimalistic example to quickly test the TTS system:

private TextToSpeech textToSpeechSystem;

@Override
protected void onStart() {
  super.onStart();
  textToSpeechSystem = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                String textToSay = "Hello world, this is a test message!";
                textToSpeechSystem.speak(textToSay, TextToSpeech.QUEUE_ADD, null);
            }
        }
   });
}

If you don't use localized messages textToSpeechSystem.setLanguage(..) is important as well, since your users probably don't all have English set as their default language so the pronunciation of the words will be wrong. But for testing TTS in general this snippet is enough

Related links: https://developer.android.com/reference/android/speech/tts/TextToSpeech

HTML5 video won't play in Chrome only

I had a similar issue, no videos would play in Chrome. Tried installing beta 64bit, going back to Chrome 32bit release.

The only thing that worked for me was updating my video drivers.

I have the NVIDIA GTS 240. Downloaded, installed the drivers and restarted and Chrome 38.0.2125.77 beta-m (64-bit) starting playing HTML5 videos again on youtube, vimeo and others. Hope this helps anyone else.

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

Difference between Statement and PreparedStatement

Statement will be used for executing static SQL statements and it can't accept input parameters.

PreparedStatement will be used for executing SQL statements many times dynamically. It will accept input parameters.

Check if pull needed in Git

I use a version of a script based on Stephen Haberman's answer:

if [ -n "$1" ]; then
    gitbin="git -C $1"
else
    gitbin="git"
fi

# Fetches from all the remotes, although --all can be replaced with origin
$gitbin fetch --all
if [ $($gitbin rev-parse HEAD) != $($gitbin rev-parse @{u}) ]; then
    $gitbin rebase @{u} --preserve-merges
fi

Assuming this script is called git-fetch-and-rebase, it can be invoked with an optional argument directory name of the local Git repository to perform operation on. If the script is called with no arguments, it assumes the current directory to be part of the Git repository.

Examples:

# Operates on /abc/def/my-git-repo-dir
git-fetch-and-rebase /abc/def/my-git-repo-dir

# Operates on the Git repository which the current working directory is part of
git-fetch-and-rebase

It is available here as well.

Make docker use IPv4 for port binding

By default, docker uses AF_INET6 sockets which can be used for both IPv4 and IPv6 connections. This causes netstat to report an IPv6 address for the listening address.

From RedHat https://access.redhat.com/solutions/3114021

Importing files from different folder

Using sys.path.append with an absolute path is not ideal when moving the application to other environments. Using a relative path won't always work because the current working directory depends on how the script was invoked.

Since the application folder structure is fixed, we can use os.path to get the full path of the module we wish to import. For example, if this is the structure:

/home/me/application/app2/some_folder/vanilla.py
/home/me/application/app2/another_folder/mango.py

And let's say that you want to import the mango module. You could do the following in vanilla.py:

import sys, os.path
mango_dir = (os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
+ '/another_folder/')
sys.path.append(mango_dir)
import mango

Of course, you don't need the mango_dir variable.

To understand how this works look at this interactive session example:

>>> import os
>>> mydir = '/home/me/application/app2/some_folder'
>>> newdir = os.path.abspath(os.path.join(mydir, '..'))
>>> newdir
    '/home/me/application/app2'
>>> newdir = os.path.abspath(os.path.join(mydir, '..')) + '/another_folder'
>>> 
>>> newdir
'/home/me/application/app2/another_folder'
>>> 

And check the os.path documentation.

Also worth noting that dealing with multiple folders is made easier when using packages, as one can use dotted module names.

How to style a div to be a responsive square?

It is as easy as specifying a padding bottom the same size as the width in percent. So if you have a width of 50%, just use this example below

id or class{
    width: 50%;
    padding-bottom: 50%;
}

Here is a jsfiddle http://jsfiddle.net/kJL3u/2/

Edited version with responsive text: http://jsfiddle.net/kJL3u/394

How to validate GUID is a GUID

see http://en.wikipedia.org/wiki/Globally_unique_identifier

There is no guarantee that an alpha will actually be there.

Size-limited queue that holds last N elements in Java

Guava now has an EvictingQueue, a non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full.

import java.util.Queue;
import com.google.common.collect.EvictingQueue;

Queue<Integer> fifo = EvictingQueue.create(2); 
fifo.add(1); 
fifo.add(2); 
fifo.add(3); 
System.out.println(fifo); 

// Observe the result: 
// [2, 3]

jquery: get value of custom attribute

You need some form of iteration here, as val (except when called with a function) only works on the first element:

$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));

should be:

$("input[placeholder]").each( function () {
    $(this).val( $(this).attr("placeholder") );
});

or

$("input[placeholder]").val(function() {
    return $(this).attr("placeholder");
});

Creating a blocking Queue<T> in .NET?

You can use the BlockingCollection and ConcurrentQueue in the System.Collections.Concurrent Namespace

 public class ProducerConsumerQueue<T> : BlockingCollection<T>
{
    /// <summary>
    /// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
    /// </summary>
    public ProducerConsumerQueue()  
        : base(new ConcurrentQueue<T>())
    {
    }

  /// <summary>
  /// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
  /// </summary>
  /// <param name="maxSize"></param>
    public ProducerConsumerQueue(int maxSize)
        : base(new ConcurrentQueue<T>(), maxSize)
    {
    }



}

How to call a PHP function on the click of a button

Yes, you need Ajax here. Please refer to the code below for more details.

 

Change your markup like this

<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />

 

jQuery:

$(document).ready(function(){
    $('.button').click(function(){
        var clickBtnValue = $(this).val();
        var ajaxurl = 'ajax.php',
        data =  {'action': clickBtnValue};
        $.post(ajaxurl, data, function (response) {
            // Response div goes here.
            alert("action performed successfully");
        });
    });
});

In ajax.php

<?php
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'insert':
                insert();
                break;
            case 'select':
                select();
                break;
        }
    }

    function select() {
        echo "The select function is called.";
        exit;
    }

    function insert() {
        echo "The insert function is called.";
        exit;
    }
?>

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

For me, removing and re-adding a reference to Microsoft.CSharp fixed the problem temporarily until the affected file was edited. Closing Visual Studio and reopening the project fixed it more long-term, so that's an option if this situation occurs while Microsoft.CSharp is already referenced.

Maybe restarting the IDE as a first step seems trivial, but here's a reminder for people like me who don't think of that as the first thing to do.

How do I create a new user in a SQL Azure database?

I followed the answers here but when I tried to connect with my new user, I got an error message stating "The server principal 'newuser' is not able to access the database 'master' under the current security context".

I had to also create a new user in the master table to successfully log in with SSMS.

USE [master]
GO
CREATE LOGIN [newuser] WITH PASSWORD=N'blahpw'
GO
CREATE USER [newuser] FOR LOGIN [newuser] WITH DEFAULT_SCHEMA=[dbo]
GO

USE [MyDatabase]
CREATE USER newuser FOR LOGIN newuser WITH DEFAULT_SCHEMA = dbo
GO
EXEC sp_addrolemember N'db_owner', N'newuser'
GO

How to detect the swipe left or Right in Android?

here is generic swipe left detector for any view in kotlin using databinding

@BindingAdapter("onSwipeLeft")
fun View.setOnSwipeLeft(runnable: Runnable) {
    setOnTouchListener(object : View.OnTouchListener {
        var x0 = 0F; var y0 = 0F; var t0 = 0L
        val defaultClickDuration = 200

        override fun onTouch(v: View?, motionEvent: MotionEvent?): Boolean {
            motionEvent?.let { event ->
                when(event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        x0 = event.x; y0 = event.y; t0 = System.currentTimeMillis()
                    }
                    MotionEvent.ACTION_UP -> {
                        val x1 = event.x; val y1 = event.y; val t1 = System.currentTimeMillis()

                        if (x0 == x1 && y0 == y1 && (t1 - t0) < defaultClickDuration) {
                            performClick()
                            return false
                        }
                        if (x0 > x1) { runnable.run() }
                    }
                    else -> {}
                }
            }
            return true
        }
    })
}

and then to use it in your layout:

app:onSwipeLeft="@{() -> viewModel.swipeLeftHandler()}"

Case insensitive std::string.find()

You could use std::search with a custom predicate.

#include <locale>
#include <iostream>
#include <algorithm>
using namespace std;

// templated version of my_equal so it could work with both char and wchar_t
template<typename charT>
struct my_equal {
    my_equal( const std::locale& loc ) : loc_(loc) {}
    bool operator()(charT ch1, charT ch2) {
        return std::toupper(ch1, loc_) == std::toupper(ch2, loc_);
    }
private:
    const std::locale& loc_;
};

// find substring (case insensitive)
template<typename T>
int ci_find_substr( const T& str1, const T& str2, const std::locale& loc = std::locale() )
{
    typename T::const_iterator it = std::search( str1.begin(), str1.end(), 
        str2.begin(), str2.end(), my_equal<typename T::value_type>(loc) );
    if ( it != str1.end() ) return it - str1.begin();
    else return -1; // not found
}

int main(int arc, char *argv[]) 
{
    // string test
    std::string str1 = "FIRST HELLO";
    std::string str2 = "hello";
    int f1 = ci_find_substr( str1, str2 );

    // wstring test
    std::wstring wstr1 = L"????? ??????";
    std::wstring wstr2 = L"??????";
    int f2 = ci_find_substr( wstr1, wstr2 );

    return 0;
}

How do I redirect output to a variable in shell?

I guess compatible way:

hash=`genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5`

but I prefer

hash="$(genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5)"

How can I create a dynamic button click event on a dynamic button?

It is much easier to do:

Button button = new Button();
button.Click += delegate
{
   // Your code
};

Server did not recognize the value of HTTP Header SOAPAction

I've decided to post my own answer here because I've lost a few hours on this and I think that, although the accepted answer is very good and pointed me in the right direction (yes, it got a voteup), it was not detailed enough to explain what was wrong with my application, at least in my case.

I'm running a BPEL module in OpenESB 2.2 and the Test Case of my Composite Application was failing with the following error:

Caused by: System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: .

After doing some research I've noticed that the external WSDL has all the clues we need to fix this problem, e.g., I'm using the following web service to validate a credit card number through a orchestration of Web Services: http://www.webservicex.net/CreditCard.asmx?WSDL

If you check the <wsdl:operation elements you will see that it clearly states the soapAction for that operation:

<wsdl:binding name="CCCheckerSoap" type="tns:CCCheckerSoap">
  <soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
  <wsdl:operation name="ValidateCardNumber">
    <soap:operation soapAction="http://www.webservicex.net/ValidateCardNumber" style="document"/>
    <wsdl:input>
  <soap:body use="literal"/>
</wsdl:input>
...

But, once you create the Composite Application and build the project with the BPEL that invokes this external WSDL service, for some reason (bug?), the XML of the Composite Application Service Assembly (CASA) binding is generated with an empty soapAction parameter:

<binding name="casaBinding1" type="ns:CCCheckerSoap">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <operation name="ValidateCardNumber">
            <soap:operation soapAction="" style="document"/>
            <input>
                <soap:body use="literal"/>
            </input>

Once you copy the proper soapAction (http://www.webservicex.net/ValidateCardNumber) into this parameter, the application's Test Case will correctly and return the expected Soap response.

<soap:operation soapAction="http://www.webservicex.net/ValidateCardNumber" style="document"/>

So, it's a more specific solution that I decided to document based on the information found in this blog post: http://bluebones.net/2003/07/server-did-not-recognize-http-header-soapaction/.

It means (at least in my case) that you are accessing a web service with SOAP and passing a SOAPAction parameter in the HTTP request that does not match what the service is expecting.

Recursively counting files in a Linux directory

If what you need is to count a specific file type recursively, you can do:

find YOUR_PATH -name '*.html' -type f | wc -l 

-l is just to display the number of lines in the output.

If you need to exclude certain folders, use -not -path

find . -not -path './node_modules/*' -name '*.js' -type f | wc -l

Getting the current date in visual Basic 2008

User can use this

Dim todaysdate As String = String.Format("{0:dd/MM/yyyy}", DateTime.Now)

this will format the date as required whereas user can change the string type dd/MM/yyyy or MM/dd/yyyy or yyyy/MM/dd or even can have this format to get the time from date

yyyy/MM/dd HH:mm:ss 

How to redirect in a servlet filter?

I'm trying to find a method to redirect my request from filter to login page

Don't

You just invoke

chain.doFilter(request, response);

from filter and the normal flow will go ahead.

I don't know how to redirect from servlet

You can use

response.sendRedirect(url);

to redirect from servlet

Querying Datatable with where condition

Something like this...

var res = from row in myDTable.AsEnumerable()
where row.Field<int>("EmpID") == 5 &&
(row.Field<string>("EmpName") != "abc" ||
row.Field<string>("EmpName") != "xyz")
select row;

See also LINQ query on a DataTable

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

Bumped into same warning. If you specified goals and built project using "Run as -> Maven build..." option check and remove pom.xml from Profiles: just below Goals:

How do I code my submit button go to an email address

You might use Form tag with action attribute to submit the mailto.

Here is an example:

<form method="post" action="mailto:[email protected]" >
<input type="submit" value="Send Email" /> 
</form>

Jinja2 shorthand conditional

Yes, it's possible to use inline if-expressions:

{{ 'Update' if files else 'Continue' }}

Using lambda expressions for event handlers

EventHandler handler = (s, e) => MessageBox.Show("Woho");

button.Click += handler;
button.Click -= handler;

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

I suspect the problem is the slashes in the format string versus the ones in the data. That's a culture-sensitive date separator character in the format string, and the final argument being null means "use the current culture". If you either escape the slashes ("M'/'d'/'yyyy") or you specify CultureInfo.InvariantCulture, it will be okay.

If anyone's interested in reproducing this:

// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M'/'d'/'yyyy", 
                                  new CultureInfo("de-DE"));

// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy", 
                                  new CultureInfo("en-US"));

// Works
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy", 
                                  CultureInfo.InvariantCulture);

// Fails
DateTime dt = DateTime.ParseExact("9/1/2009", "M/d/yyyy", 
                                  new CultureInfo("de-DE"));

CSS3 100vh not constant in mobile browser

Brave browser on iOS behaves differently (buggy?). It changes viewport height dynamically accordingly to showing/hiding address bar. It is kind of annoying because it changes page's layout dependent on vw/vh units.

Chrome and Safari is fine.

Adjusting the Xcode iPhone simulator scale and size

Check this Image… You can change your simulator size from here

or press CMD+1, CMD+2 or CMD+3

enter image description here

How to change the application launcher icon on Flutter?

you can achieve this by using flutter_launcher_icons in pubspec.yaml

another way is to use one for android and another one for iOS

JavaScript get element by name

You want this:

function validate() {
    var acc = document.getElementsByName('acc')[0].value;
    var pass = document.getElementsByName('pass')[0].value;

    alert (acc);
}

How can I handle the warning of file_get_contents() function in PHP?

You can prepend an @: $content = @file_get_contents($site);

This will supress any warning - use sparingly!. See Error Control Operators

Edit: When you remove the 'http://' you're no longer looking for a web page, but a file on your disk called "www.google....."

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

I had the same problem in my (YouTube player project)... and the following solved the problem for me:

  1. Add this code into your build.gradle (module: app) inside defaultConfing:

    defaultConfig {
        ....
        ....
        multiDexEnabled = true
    }
    
  2. Add this code into your build.gradle (module: app) inside dependencies:

    dependencies {
        compile 'com.android.support:multidex:1.0.1'
        .....
        .....
    }
    
  3. Open AndroidManifest.xml and within application:

    <application
        android:name="android.support.multidex.MultiDexApplication"
        .....
        .....
    </application>
    

    or if you have your App class, extend it from MultiDexApplication like:

    public class MyApp extends MultiDexApplication {
    .....
    

And finally, I think you should have Android Support Repository downloaded, in the Extras in SDK Manager.

C# version of java's synchronized keyword?

static object Lock = new object();

lock (Lock) 
{
// do stuff
}

How to remove a Gitlab project?

  • 1.Gitlab Home Page
  • 2.Select your projects button under Projects Menus
  • 3.Click your desired project
  • 4.Select Settings (from left sidebar)
  • 5.Click Advanced settings Expand the Advanced settings this will be middle of the page
  • 6.Click Remove
  • 7.Project In the Modal write your project name

Hope you can Successfully remove your project. Happy Coding :)

Why can't I inherit static classes?

You can do something that will look like static inheritance.

Here is the trick:

public abstract class StaticBase<TSuccessor>
    where TSuccessor : StaticBase<TSuccessor>, new()
{
    protected static readonly TSuccessor Instance = new TSuccessor();
}

Then you can do this:

public class Base : StaticBase<Base>
{
    public Base()
    {
    }

    public void MethodA()
    {
    }
}

public class Inherited : Base
{
    private Inherited()
    {
    }

    public new static void MethodA()
    {
        Instance.MethodA();
    }
}

The Inherited class is not static itself, but we don't allow to create it. It actually has inherited static constructor which builds Base, and all properties and methods of Base available as static. Now the only thing left to do make static wrappers for each method and property you need to expose to your static context.

There are downsides like the need for manual creation of static wrapper methods and new keyword. But this approach helps support something that is really similar to static inheritance.

P.S. We used this for creating compiled queries, and this actually can be replaced with ConcurrentDictionary, but a static read-only field with its thread safety was good enough.

Convert String to Carbon

Try this

$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;

Iterating Over Dictionary Key Values Corresponding to List in Python

Dictionary objects allow you to iterate over their items. Also, with pattern matching and the division from __future__ you can do simplify things a bit.

Finally, you can separate your logic from your printing to make things a bit easier to refactor/debug later.

from __future__ import division

def Pythag(league):
    def win_percentages():
        for team, (runs_scored, runs_allowed) in league.iteritems():
            win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
            yield win_percentage

    for win_percentage in win_percentages():
        print win_percentage

typeof operator in C

It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.

Hibernate JPA Sequence (non-Id)

I have found a workaround for this on MySql databases using @PostConstruct and JdbcTemplate in a Spring application. It may be doable with other databases but the use case that I will present is based on my experience with MySql, as it uses auto_increment.

First, I had tried defining a column as auto_increment using the ColumnDefinition property of the @Column annotation, but it was not working as the column needed to be an key in order to be auto incremental, but apparently the column wouldn't be defined as an index until after it was defined, causing a deadlock.

Here is where I came with the idea of creating the column without the auto_increment definition, and adding it after the database was created. This is possible using the @PostConstruct annotation, which causes a method to be invoked right after the application has initialized the beans, coupled with JdbcTemplate's update method.

The code is as follows:

In My Entity:

@Entity
@Table(name = "MyTable", indexes = { @Index(name = "my_index", columnList = "mySequencedValue") })
public class MyEntity {
    //...
    @Column(columnDefinition = "integer unsigned", nullable = false, updatable = false, insertable = false)
    private Long mySequencedValue;
    //...
}

In a PostConstructComponent class:

@Component
public class PostConstructComponent {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @PostConstruct
    public void makeMyEntityMySequencedValueAutoIncremental() {
        jdbcTemplate.update("alter table MyTable modify mySequencedValue int unsigned auto_increment");
    }
}

How to validate a date?

One simple way to validate a date string is to convert to a date object and test that, e.g.

_x000D_
_x000D_
// Expect input as d/m/y_x000D_
function isValidDate(s) {_x000D_
  var bits = s.split('/');_x000D_
  var d = new Date(bits[2], bits[1] - 1, bits[0]);_x000D_
  return d && (d.getMonth() + 1) == bits[1];_x000D_
}_x000D_
_x000D_
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {_x000D_
  console.log(s + ' : ' + isValidDate(s))_x000D_
})
_x000D_
_x000D_
_x000D_

When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.

You can also test the bits of the date string:

_x000D_
_x000D_
function isValidDate2(s) {_x000D_
  var bits = s.split('/');_x000D_
  var y = bits[2],_x000D_
    m = bits[1],_x000D_
    d = bits[0];_x000D_
  // Assume not leap year by default (note zero index for Jan)_x000D_
  var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];_x000D_
_x000D_
  // If evenly divisible by 4 and not evenly divisible by 100,_x000D_
  // or is evenly divisible by 400, then a leap year_x000D_
  if ((!(y % 4) && y % 100) || !(y % 400)) {_x000D_
    daysInMonth[1] = 29;_x000D_
  }_x000D_
  return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]_x000D_
}_x000D_
_x000D_
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {_x000D_
  console.log(s + ' : ' + isValidDate2(s))_x000D_
})
_x000D_
_x000D_
_x000D_

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

How to set a cookie for another domain

Here is what I've used. Note, this cookie is passed in the open (http) and is therefore insecure. I don't use it for anything which requires security.

  1. Site A generates a token and passes as a URL parameter to site B.
  2. Site B takes the token and sets it as a session cookie.

You could probably add encryption/signatures to make this secure. Do your research on how to do that correctly.

Google Maps API v2: How to make markers clickable?

Another Solution : you get the marker by its title

public class MarkerDemoActivity extends android.support.v4.app.FragmentActivity implements OnMarkerClickListener
{
      private Marker myMarker;    

      private void setUpMap()
      {
      .......
      googleMap.setOnMarkerClickListener(this);

      myMarker = googleMap.addMarker(new MarkerOptions()
                  .position(latLng)
                  .title("My Spot")
                  .snippet("This is my spot!")
                  .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
      ......
      }

  @Override
  public boolean onMarkerClick(final Marker marker) 
  {

     String name= marker.getTitle();

      if (name.equalsIgnoreCase("My Spot")) 
      {
          //write your code here
      }
  }
}

Find the number of employees in each department - SQL Oracle

Please try:

select count(*) as count,dept.DNAME 
from emp 
inner join dept on emp.DEPTNO = dept.DEPTNO 
group by dept.DNAME

Inner join vs Where

They're both inner joins that do the same thing, one simply uses the newer ANSI syntax.

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

You need to load the helper before loading the view somewhere in your controller.

But I think here you want to use the function site_url()

Before you load your view, basically anywhere inside the method in your controller, add this to your code :

$this->load->helper('url');

Then use the function site_url().

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

My solution here is to loop, just to avoid duplicate option

                            <select class="form-control" name="status" >
                              <?php $lists = ['Current', 'Win', 'Lose']; ?>

                              @foreach($lists as $list)
                              <option value={{$list}} {{(old('status') == $list?'selected':'')}} >{{$list}}</option>
                              @endforeach

                            </select>

Generate UML Class Diagram from Java Project

I use eUML2 plugin from Soyatec, under Eclipse and it works fine for the generation of UML giving the source code. This tool is useful up to Eclipse 4.4.x

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

You're most likely closing the session inside of the RoleDao. If you close the session then try to access a field on an object that was lazy-loaded, you will get this exception. You should probably open and close the session/transaction in your test.

Removing the first 3 characters from a string

Use the substring method of the String class :

String removeCurrency=amount.getText().toString().substring(3);

CSS - Expand float child DIV height to parent's height

<div class="parent" style="height:500px;">
<div class="child-left floatLeft" style="height:100%">
</div>

<div class="child-right floatLeft" style="height:100%">
</div>
</div>

I used inline style just to give idea.

how do I create an infinite loop in JavaScript

By omitting all parts of the head, the loop can also become infinite:

for (;;) {}

Running powershell script within python script, how to make python print the powershell output while it is running

I don't have Python 2.7 installed, but in Python 3.3 calling Popen with stdout set to sys.stdout worked just fine. Not before I had escaped the backslashes in the path, though.

>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_

Spark: subtract two DataFrames

For me , df1.subtract(df2) was inconsistent. Worked correctly on one dataframe but not on the other . That was because of duplicates . df1.exceptAll(df2) returns a new dataframe with the records from df1 that do not exist in df2 , including any duplicates.

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Although I use the following code.

.carousel.fade
{
    opacity: 1;

    .item
    {
        -moz-transition: opacity ease-in-out .7s;
        -o-transition: opacity ease-in-out .7s;
        -webkit-transition: opacity ease-in-out .7s;
        transition: opacity ease-in-out .7s;
        left: 0 !important;
        opacity: 0;
        top:0;
        position:absolute;
        width: 100%;
        display:block !important;
        z-index:1;
        &:first-child{
            top:auto;
            position:relative;
        }

        &.active
        {
            opacity: 1;
            -moz-transition: opacity ease-in-out .7s;
            -o-transition: opacity ease-in-out .7s;
            -webkit-transition: opacity ease-in-out .7s;
            transition: opacity ease-in-out .7s;
            z-index:2;
        }
    }
}

Then change the class on the carousel from "carousel slide" to "carousel fade". This works in safari, chrome, firefox, and IE 10. It will correctly downgrade in IE 9, however, the nice face effect doesn't happen.

Edit: Since this answer has gotten so popular I've added the following which rewritten as pure CSS instead of the above which was LESS:

.carousel.fade {
  opacity: 1;
}
.carousel.fade .item {
  -moz-transition: opacity ease-in-out .7s;
  -o-transition: opacity ease-in-out .7s;
  -webkit-transition: opacity ease-in-out .7s;
  transition: opacity ease-in-out .7s;
  left: 0 !important;
  opacity: 0;
  top:0;
  position:absolute;
  width: 100%;
  display:block !important;
  z-index:1;
}
.carousel.fade .item:first-child {
  top:auto;
  position:relative;
}
.carousel.fade .item.active {
  opacity: 1;
  -moz-transition: opacity ease-in-out .7s;
  -o-transition: opacity ease-in-out .7s;
  -webkit-transition: opacity ease-in-out .7s;
  transition: opacity ease-in-out .7s;
  z-index:2;
}

How to get the week day name from a date?

To do this for oracle sql, the syntax would be:

,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field

for this example, I look for the second '-' and take the substring to the end

VBA setting the formula for a cell

Try:

.Formula = "='" & strProjectName & "'!" & Cells(2, 7).Address

If your worksheet name (strProjectName) has spaces, you need to include the single quotes in the formula string.

If this does not resolve it, please provide more information about the specific error or failure.

Update

In comments you indicate you're replacing spaces with underscores. Perhaps you are doing something like:

strProjectName = Replace(strProjectName," ", "_")

But if you're not also pushing that change to the Worksheet.Name property, you can expect these to happen:

  1. The file browse dialog appears
  2. The formula returns #REF error

The reason for both is that you are passing a reference to a worksheet that doesn't exist, which is why you get the #REF error. The file dialog is an attempt to let you correct that reference, by pointing to a file wherein that sheet name does exist. When you cancel out, the #REF error is expected.

So you need to do:

Worksheets(strProjectName).Name = Replace(strProjectName," ", "_")
strProjectName = Replace(strProjectName," ", "_")

Then, your formula should work.

How to convert a GUID to a string in C#?

String guid = System.Guid.NewGuid().ToString();

Otherwise it's a delegate.

Line continue character in C#

String Constants

Just use the + operator and break the string up into human-readable lines. The compiler will pick up that the strings are constant and concatenate them at compile time. See the MSDN C# Programming Guide here.

e.g.

const string myVeryLongString = 
    "This is the opening paragraph of my long string. " +
    "Which is split over multiple lines to improve code readability, " +
    "but is in fact, just one long string.";

IL_0003: ldstr "This is the opening paragraph of my long string. Which is split over multiple lines to improve code readability, but is in fact, just one long string."

String Variables

Note that when using string interpolation to substitute values into your string, that the $ character needs to precede each line where a substitution needs to be made:

var interpolatedString = 
    "This line has no substitutions. " +
    $" This line uses {count} widgets, and " +
    $" {CountFoos()} foos were found.";

However, this has the negative performance consequence of multiple calls to string.Format and eventual concatenation of the strings (marked with ***)

IL_002E:  ldstr       "This line has no substitutions. "
IL_0033:  ldstr       " This line uses {0} widgets, and "
IL_0038:  ldloc.0     // count
IL_0039:  box         System.Int32
IL_003E:  call        System.String.Format ***
IL_0043:  ldstr       " {0} foos were found."
IL_0048:  ldloc.1     // CountFoos
IL_0049:  callvirt    System.Func<System.Int32>.Invoke
IL_004E:  box         System.Int32
IL_0053:  call        System.String.Format ***
IL_0058:  call        System.String.Concat ***

Although you could either use $@ to provide a single string and avoid the performance issues, unless the whitespace is placed inside {} (which looks odd, IMO), this has the same issue as Neil Knight's answer, as it will include any whitespace in the line breakdowns:

var interpolatedString = $@"When breaking up strings with `@` it introduces
    <- [newLine and whitespace here!] each time I break the string.
    <- [More whitespace] {CountFoos()} foos were found.";

The injected whitespace is easy to spot:

IL_002E:  ldstr       "When breaking up strings with `@` it introduces
    <- [newLine and whitespace here!] each time I break the string.
    <- [More whitespace] {0} foos were found."

An alternative is to revert to string.Format. Here, the formatting string is a single constant as per my initial answer:

const string longFormatString = 
    "This is the opening paragraph of my long string with {0} chars. " +
    "Which is split over multiple lines to improve code readability, " +
    "but is in fact, just one long string with {1} widgets.";

And then evaluated as such:

string.Format(longFormatString, longFormatString.Length, CountWidgets());

However this can still be tricky to maintain given the potential separation between the formatting string and the substitution tokens.

Why in C++ do we use DWORD rather than unsigned int?

For myself, I would assume unsigned int is platform specific. Integer could be 8 bits, 16 bits, 32 bits or even 64 bits.

DWORD in the other hand, specifies its own size, which is Double Word. Word are 16 bits so DWORD will be known as 32 bit across all platform

Should operator<< be implemented as a friend or as a member function?

friend operator = equal rights as class

friend std::ostream& operator<<(std::ostream& os, const Object& object) {
    os << object._atribute1 << " " << object._atribute2 << " " << atribute._atribute3 << std::endl;
    return os;
}

How to resume Fragment from BackStack if exists

Reading the documentation, there is a way to pop the back stack based on either the transaction name or the id provided by commit. Using the name may be easier since it shouldn't require keeping track of a number that may change and reinforces the "unique back stack entry" logic.

Since you want only one back stack entry per Fragment, make the back state name the Fragment's class name (via getClass().getName()). Then when replacing a Fragment, use the popBackStackImmediate() method. If it returns true, it means there is an instance of the Fragment in the back stack. If not, actually execute the Fragment replacement logic.

private void replaceFragment (Fragment fragment){
  String backStateName = fragment.getClass().getName();

  FragmentManager manager = getSupportFragmentManager();
  boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);

  if (!fragmentPopped){ //fragment not in back stack, create it.
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.addToBackStack(backStateName);
    ft.commit();
  }
}

EDIT

The problem is - when i launch A and then B, then press back button, B is removed and A is resumed. and pressing again back button should exit the app. But it is showing a blank window and need another press to close it.

This is because the FragmentTransaction is being added to the back stack to ensure that we can pop the fragments on top later. A quick fix for this is overriding onBackPressed() and finishing the Activity if the back stack contains only 1 Fragment

@Override
public void onBackPressed(){
  if (getSupportFragmentManager().getBackStackEntryCount() == 1){
    finish();
  }
  else {
    super.onBackPressed();
  }
}

Regarding the duplicate back stack entries, your conditional statement that replaces the fragment if it hasn't been popped is clearly different than what my original code snippet's. What you are doing is adding to the back stack regardless of whether or not the back stack was popped.

Something like this should be closer to what you want:

private void replaceFragment (Fragment fragment){
  String backStateName =  fragment.getClass().getName();
  String fragmentTag = backStateName;

  FragmentManager manager = getSupportFragmentManager();
  boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);

  if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null){ //fragment not in back stack, create it.
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content_frame, fragment, fragmentTag);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.addToBackStack(backStateName);
    ft.commit();
  } 
}

The conditional was changed a bit since selecting the same fragment while it was visible also caused duplicate entries.

Implementation:

I highly suggest not taking the the updated replaceFragment() method apart like you did in your code. All the logic is contained in this method and moving parts around may cause problems.

This means you should copy the updated replaceFragment() method into your class then change

backStateName = fragmentName.getClass().getName();
fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped) {
            ft.replace(R.id.content_frame, fragmentName);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();

so it is simply

replaceFragment (fragmentName);

EDIT #2

To update the drawer when the back stack changes, make a method that accepts in a Fragment and compares the class names. If anything matches, change the title and selection. Also add an OnBackStackChangedListener and have it call your update method if there is a valid Fragment.

For example, in the Activity's onCreate(), add

getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {

  @Override
  public void onBackStackChanged() {
    Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_frame);
    if (f != null){
      updateTitleAndDrawer (f);
    }

  }
});

And the other method:

private void updateTitleAndDrawer (Fragment fragment){
  String fragClassName = fragment.getClass().getName();

  if (fragClassName.equals(A.class.getName())){
    setTitle ("A");
    //set selected item position, etc
  }
  else if (fragClassName.equals(B.class.getName())){
    setTitle ("B");
    //set selected item position, etc
  }
  else if (fragClassName.equals(C.class.getName())){
    setTitle ("C");
    //set selected item position, etc
  }
}

Now, whenever the back stack changes, the title and checked position will reflect the visible Fragment.

How to remove foreign key constraint in sql server?

Alternatively, you can also delete a Foreign Key Constraint from the SQL Server Management Studio itself. You can try it if the commands do not work.

  1. Expand your database view.
  2. Right Click on Table which has foreign key constraint. Choose Design. A tab with the information about table columns will open.
  3. Right click on the column which has the foreign key reference. Or you can right click on any column. Choose Relationships.
  4. A list of relationships will appear (if you have one) in a pop up window.
  5. From there you can delete the foreign key constraint.

I hope that helps

Val and Var in Kotlin

You can easily think it as:

var is used for setter (value will change).

val is used for getter (read-only, value won't change).

Convert string to decimal, keeping fractions

decimal d = 3.00 is still 3. I guess you want to show it some where on screen or print it on log file as 3.00. You can do following

string str = d.ToString("F2");

or if you are using database to store the decimal then you can set pricision value in database.

Why does find -exec mv {} ./target/ + not work?

find . -name "*.mp3" -exec mv --target-directory=/home/d0k/??????/ {} \+

Windows Bat file optional argument parsing

If you want to use optional arguments, but not named arguments, then this approach worked for me. I think this is much easier code to follow.

REM Get argument values.  If not specified, use default values.
IF "%1"=="" ( SET "DatabaseServer=localhost" ) ELSE ( SET "DatabaseServer=%1" )
IF "%2"=="" ( SET "DatabaseName=MyDatabase" ) ELSE ( SET "DatabaseName=%2" )

REM Do work
ECHO Database Server = %DatabaseServer%
ECHO Database Name   = %DatabaseName%

Create an ArrayList with multiple object types?

(1)

   ArrayList<Object> list = new ArrayList <>();`     
   list.add("ddd");
   list.add(2);
   list.add(11122.33);    
   System.out.println(list);

(2)

 ArrayList arraylist = new ArrayList();
 arraylist.add(5);        
 arraylist.add("saman");     
 arraylist.add(4.3);        
 System.out.println(arraylist);

PHP: trying to create a new line with "\n"

We can use \n as a new line in php.

Code Snippet :

 <?php
  echo"Fo\n";
  echo"Pro";
?>

Output:

Fo
Pro

How do you create a remote Git branch?

I know this question is well answered, but just wanted to list the steps I take to create a new branch "myNewBranch" and push to remote ("origin" in my case) and set up tracking. Consider this the "TL;DR" version :)

# create new branch and checkout that branch
git checkout -b myNewBranch
# now push branch to remote 
git push origin myNewBranch
# set up the new branch to track remote branch from origin
git branch --set-upstream-to=origin/myNewBranch myNewBranch

What is the difference between String and string in C#?

There is practically no difference

The C# keyword string maps to the .NET type System.String - it is an alias that keeps to the naming conventions of the language.

How do I add items to an array in jQuery?

You are making an ajax request which is asynchronous therefore your console log of the list length occurs before the ajax request has completed.

The only way of achieving what you want is changing the ajax call to be synchronous. You can do this by using the .ajax and passing in asynch : false however this is not recommended as it locks the UI up until the call has returned, if it fails to return the user has to crash out of the browser.

What exactly does the "u" do? "git push -u origin master" vs "git push origin master"

In more simple terms:

Technically, the -u flag adds a tracking reference to the upstream server you are pushing to.

What is important here is that this lets you do a git pull without supplying any more arguments. For example, once you do a git push -u origin master, you can later call git pull and git will know that you actually meant git pull origin master.

Otherwise, you'd have to type in the whole command.

Scala check if element is present in a list

And if you didn't want to use strict equality, you could use exists:


myFunction(strings.exists { x => customPredicate(x) })

Writing a dictionary to a csv file with one line for every 'key: value'

outfile = open( 'dict.txt', 'w' )
for key, value in sorted( mydict.items() ):
    outfile.write( str(key) + '\t' + str(value) + '\n' )

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

For Bootstrap 4 stable:

Since beta Bootstrap 4 doesn't depend on Tether but Popper.js. All scripts (must be in this order):

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>

See the current documentation for the newest script versions.


Only Bootstrap 4 alpha:

Bootstrap 4 alpha needs Tether, so you need to include tether.min.js before you include bootstrap.min.js, eg.

<script src="https://npmcdn.com/[email protected]/dist/js/tether.min.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/js/bootstrap.min.js"></script>

How to make an autocomplete address field with google maps api?

I really doubt it--google maps API is great for geocoding known addresses, but it generally return data that is suitable for autocomplete-style operations. Nevermind the challenge of not hitting the API in such a way as to eat up your geocoding query limit very quickly.

OpenCV with Network Cameras

I just do it like this:

CvCapture *capture = cvCreateFileCapture("rtsp://camera-address");

Also make sure this dll is available at runtime else cvCreateFileCapture will return NULL

opencv_ffmpeg200d.dll

The camera needs to allow unauthenticated access too, usually set via its web interface. MJPEG format worked via rtsp but MPEG4 didn't.

hth

Si

How to check if any Checkbox is checked in Angular

This is re-post for insert code also. This example included: - One object list - Each object hast child list. Ex:

var list1 = {
    name: "Role A",
    name_selected: false,
    subs: [{
      sub: "Read",
      id: 1,
      selected: false
    }, {
      sub: "Write",
      id: 2,
      selected: false
    }, {
      sub: "Update",
      id: 3,
      selected: false
    }],
  };

I'll 3 list like above and i'll add to a one object list

newArr.push(list1);
  newArr.push(list2);
  newArr.push(list3);

Then i'll do how to show checkbox with multiple group:

$scope.toggleAll = function(item) {
    var toogleStatus = !item.name_selected;
    console.log(toogleStatus);
    angular.forEach(item, function() {
      angular.forEach(item.subs, function(sub) {
        sub.selected = toogleStatus;
      });
    });
  };

  $scope.optionToggled = function(item, subs) {
    item.name_selected = subs.every(function(itm) {
      return itm.selected;
    })
    $scope.txtRet = item.name_selected;
  }

HTML:

<li ng-repeat="item in itemDisplayed" class="ng-scope has-pretty-child">
      <div>
        <ul>
          <input type="checkbox" class="checkall" ng-model="item.name_selected" ng-click="toggleAll(item)"><span>{{item.name}}</span>
          <div>
            <li ng-repeat="sub in item.subs" class="ng-scope has-pretty-child">
              <input type="checkbox" kv-pretty-check="" ng-model="sub.selected" ng-change="optionToggled(item,item.subs)"><span>{{sub.sub}}</span>
            </li>
          </div>
        </ul>
      </div>
      <span>{{txtRet}}</span>
    </li>

Fiddle: example

Excel CSV - Number cell format

I had this issue when exporting CSV data from C# code, and resolved this by prepending the leading zero data with the tab character \t, so the data was interpreted as text rather than numeric in Excel (yet unlike prepending other characters, it wouldn't be seen).

I did like the ="001" approach, but this wouldn't allow exported CSV data to be re-imported again to my C# application without removing all this formatting from the import CSV file (instead I'll just trim the import data).

How to run Nginx within a Docker container without halting?

For all who come here trying to run a nginx image in a docker container, that will run as a service

As there is no whole Dockerfile, here is my whole Dockerfile solving the issue.

Nice and working. Thanks to all answers here in order to solve the final nginx issue.

FROM ubuntu:18.04
MAINTAINER stackoverfloguy "[email protected]"
RUN apt-get update -y
RUN apt-get install net-tools nginx ufw sudo -y
RUN adduser --disabled-password --gecos '' docker
RUN adduser docker sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
USER docker
RUN sudo ufw default allow incoming
RUN sudo rm /etc/nginx/nginx.conf
RUN sudo rm /etc/nginx/sites-available/default
RUN sudo rm /var/www/html/index.nginx-debian.html
VOLUME /var/log
VOLUME /usr/share/nginx/html
VOLUME /etc/nginx
VOLUME /var/run
COPY conf/nginx.conf /etc/nginx/nginx.conf
COPY content/* /var/www/html/
COPY Dockerfile /var/www/html
COPY start.sh /etc/nginx/start.sh
RUN sudo chmod +x /etc/nginx/start.sh
RUN sudo chmod -R 777 /var/www/html
EXPOSE 80
EXPOSE 443
ENTRYPOINT sudo nginx -c /etc/nginx/nginx.conf -g 'daemon off;'

And run it with:

docker run -p 80:80 -p 443:443 -dit

Is it possible to put a ConstraintLayout inside a ScrollView?

I had NestedScrollView inside ConstraintLayout, and this NestedScrollView has one ConstraintLayout.

If you're facing issue with NestedScrollView,

add android:fillViewport="true" to NestedScrollView, worked.

Why is the console window closing immediately once displayed my output?

Instead of using

Console.Readline()
Console.Read()
Console.ReadKey()

you can run your program using Ctrl+F5 (if you are in Visual Studio). Then Visual Studio will keep the console window open, until you press a key.

Note: You cannot debug your code in this approach.

Rotating a Div Element in jQuery

I doubt you can rotate an element using DOM/CSS. Your best bet would be to render to a canvas and rotate that (not sure on the specifics).

Debugging in Maven?

If you are using Maven 2.0.8+, run the mvnDebug command in place of mvn and attach a debugger on port 8000.

For Maven <2.0.8, uncomment the following line in your %M2_HOME%/bin/mvn.bat (and maybe save the modified version as mvnDebug.bat):

@REM set MAVEN_OPTS=-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000

More details in MNG-2105 and Dealing with Eclipse-based IDE.

How to get all table names from a database?

If you want to use a high-level API, that hides a lot of the JDBC complexity around database schema metadata, take a look at this article: http://www.devx.com/Java/Article/32443/1954

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

Most of the solutions provided either don't use TRUNCATE, which is different from DELETE, or they don't deal with the issue of foreign key constraints. The solution provided by Chaitanya comes close, but it falls back to using DELETE, and it does it in a stored procedure, which seems to not fit a situation where you are nuking all data in a database.

So, below is my variation which does use TRUNCATE and does address the foreign key constraint problem.

    /* TRUNCATE ALL TABLES IN A DATABASE */

DECLARE @dropAndCreateConstraintsTable TABLE
        (
         DropStmt VARCHAR(MAX)
        ,CreateStmt VARCHAR(MAX)
        )
/* Gather information to drop and then recreate the current foreign key constraints  */
INSERT  @dropAndCreateConstraintsTable
        SELECT  DropStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema
                + '].[' + ForeignKeys.ForeignTableName + '] DROP CONSTRAINT ['
                + ForeignKeys.ForeignKeyName + ']; '
               ,CreateStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema
                + '].[' + ForeignKeys.ForeignTableName
                + '] WITH CHECK ADD CONSTRAINT [' + ForeignKeys.ForeignKeyName
                + '] FOREIGN KEY([' + ForeignKeys.ForeignTableColumn
                + ']) REFERENCES [' + SCHEMA_NAME(sys.objects.schema_id)
                + '].[' + sys.objects.[name] + ']([' + sys.columns.[name]
                + ']); '
        FROM    sys.objects
        INNER JOIN sys.columns
                ON ( sys.columns.[object_id] = sys.objects.[object_id] )
        INNER JOIN ( SELECT sys.foreign_keys.[name] AS ForeignKeyName
                           ,SCHEMA_NAME(sys.objects.schema_id) AS ForeignTableSchema
                           ,sys.objects.[name] AS ForeignTableName
                           ,sys.columns.[name] AS ForeignTableColumn
                           ,sys.foreign_keys.referenced_object_id AS referenced_object_id
                           ,sys.foreign_key_columns.referenced_column_id AS referenced_column_id
                     FROM   sys.foreign_keys
                     INNER JOIN sys.foreign_key_columns
                            ON ( sys.foreign_key_columns.constraint_object_id = sys.foreign_keys.[object_id] )
                     INNER JOIN sys.objects
                            ON ( sys.objects.[object_id] = sys.foreign_keys.parent_object_id )
                     INNER JOIN sys.columns
                            ON ( sys.columns.[object_id] = sys.objects.[object_id] )
                               AND ( sys.columns.column_id = sys.foreign_key_columns.parent_column_id )
                   ) ForeignKeys
                ON ( ForeignKeys.referenced_object_id = sys.objects.[object_id] )
                   AND ( ForeignKeys.referenced_column_id = sys.columns.column_id )
        WHERE   ( sys.objects.[type] = 'U' )
                AND ( sys.objects.[name] NOT IN ( 'sysdiagrams' ) )

/* SELECT * FROM @dropAndCreateConstraintsTable AS DACCT */

DECLARE @DropStatement NVARCHAR(MAX)
DECLARE @RecreateStatement NVARCHAR(MAX)

/* Drop Constraints */
DECLARE C1 CURSOR READ_ONLY
FOR
        SELECT  DropStmt
        FROM    @dropAndCreateConstraintsTable
OPEN C1

FETCH NEXT FROM C1 INTO @DropStatement

WHILE @@FETCH_STATUS = 0
      BEGIN
            PRINT 'Executing ' + @DropStatement
            EXECUTE sp_executesql @DropStatement
            FETCH NEXT FROM C1 INTO @DropStatement
      END
CLOSE C1
DEALLOCATE C1

/* Truncate all tables in the database in the dbo schema */
DECLARE @DeleteTableStatement NVARCHAR(MAX)
DECLARE C2 CURSOR READ_ONLY
FOR
        SELECT  'TRUNCATE TABLE [dbo].[' + TABLE_NAME + ']'
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE   TABLE_SCHEMA = 'dbo'
                AND TABLE_TYPE = 'BASE TABLE'
  /* Change your schema appropriately if you don't want to use dbo */
OPEN C2

FETCH NEXT FROM C2 INTO @DeleteTableStatement

WHILE @@FETCH_STATUS = 0
      BEGIN
            PRINT 'Executing ' + @DeleteTableStatement
            EXECUTE sp_executesql @DeleteTableStatement
            FETCH NEXT FROM C2 INTO @DeleteTableStatement
      END
CLOSE C2
DEALLOCATE C2

/* Recreate foreign key constraints  */
DECLARE C3 CURSOR READ_ONLY
FOR
        SELECT  CreateStmt
        FROM    @dropAndCreateConstraintsTable
OPEN C3

FETCH NEXT FROM C3 INTO @RecreateStatement

WHILE @@FETCH_STATUS = 0
      BEGIN
            PRINT 'Executing ' + @RecreateStatement
            EXECUTE sp_executesql @RecreateStatement
            FETCH NEXT FROM C3 INTO @RecreateStatement
      END
CLOSE C3
DEALLOCATE C3

GO

How to get the mouse position without events (without moving the mouse)?

The most simple solution but not 100% accurate

$(':hover').last().offset()

Result: {top: 148, left: 62.5}
The result depend on the nearest element size and return undefined when user switched the tab

How often should you use git-gc?

You can do it without any interruption, with the new (Git 2.0 Q2 2014) setting gc.autodetach.

See commit 4c4ac4d and commit 9f673f9 (Nguy?n Thái Ng?c Duy, aka pclouds):

gc --auto takes time and can block the user temporarily (but not any less annoyingly).
Make it run in background on systems that support it.
The only thing lost with running in background is printouts. But gc output is not really interesting.
You can keep it in foreground by changing gc.autodetach.


Since that 2.0 release, there was a bug though: git 2.7 (Q4 2015) will make sure to not lose the error message.
See commit 329e6e8 (19 Sep 2015) by Nguy?n Thái Ng?c Duy (pclouds).
(Merged by Junio C Hamano -- gitster -- in commit 076c827, 15 Oct 2015)

gc: save log from daemonized gc --auto and print it next time

While commit 9f673f9 (gc: config option for running --auto in background - 2014-02-08) helps reduce some complaints about 'gc --auto' hogging the terminal, it creates another set of problems.

The latest in this set is, as the result of daemonizing, stderr is closed and all warnings are lost. This warning at the end of cmd_gc() is particularly important because it tells the user how to avoid "gc --auto" running repeatedly.
Because stderr is closed, the user does not know, naturally they complain about 'gc --auto' wasting CPU.

Daemonized gc now saves stderr to $GIT_DIR/gc.log.
Following gc --auto will not run and gc.log printed out until the user removes gc.log
.

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

When your browser redirects the user to Google's oAuth page, are you passing as a parameter the redirect URI you want Google's server to return to with the token response? Setting a redirect URI in the console is not a way of telling Google where to go when a login attempt comes in, but rather it's a way of telling Google what the allowed redirect URIs are (so if someone else writes a web app with your client ID but a different redirect URI it will be disallowed); your web app should, when someone clicks the "login" button, send the browser to:

https://accounts.google.com/o/oauth2/auth?client_id=XXXXX&redirect_uri=http://localhost:8080/WEBAPP/youtube-callback.html&response_type=code&scope=https://www.googleapis.com/auth/youtube.upload

(the callback URI passed as a parameter must be url-encoded, btw).

When Google's server gets authorization from the user, then, it'll redirect the browser to whatever you sent in as the redirect_uri. It'll include in that request the token as a parameter, so your callback page can then validate the token, get an access token, and move on to the other parts of your app.

If you visit:

http://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow

You can see better samples of the java client there, demonstrating that you have to override the getRedirectUri method to specify your callback path so the default isn't used.

The redirect URIs are in the client_secrets.json file for multiple reasons ... one big one is so that the oAuth flow can verify that the redirect your app specifies matches what your app allows.

If you visit https://developers.google.com/api-client-library/java/apis/youtube/v3 You can generate a sample application for yourself that's based directly off your app in the console, in which (again) the getRedirectUri method is overwritten to use your specific callbacks.

Jquery Hide table rows

You just need to traverse up the DOM tree to the nearest <tr> like so...

$("#ID_OF_ELEMENT").parents("tr").hide();

jQuery API Reference

JQuery .on() method with multiple event handlers to one selector

I learned something really useful and fundamental from here.

chaining functions is very usefull in this case which works on most jQuery Functions including on function output too.

It works because output of most jQuery functions are the input objects sets so you can use them right away and make it shorter and smarter

function showPhotos() {
    $(this).find("span").slideToggle();
}

$(".photos")
    .on("mouseenter", "li", showPhotos)
    .on("mouseleave", "li", showPhotos);

Commit history on remote repository

git isn't a centralized scm like svn so you have two options:

It may be annoying to implement for many different platforms (GitHub, GitLab, BitBucket, SourceForge, Launchpad, Gogs, ...) but fetching data is pretty slow (we talk about seconds) - no solution is perfect.


An example with fetching into a temporary directory:

git clone https://github.com/rust-lang/rust.git -b master --depth 3 --bare --filter=blob:none -q .
git log -n 3 --no-decorate --format=oneline

Alternatively:

git init --bare -q
git remote add -t master origin https://github.com/rust-lang/rust.git
git fetch --depth 3 --filter=blob:none -q
git log -n 3 --no-decorate --format=oneline origin/master

Both are optimized for performance by restricting to exactly 3 commits of one branch into a minimal local copy without file contents and preventing console outputs. Though opening a connection and calculating deltas during fetch takes some time.


An example with GitHub:

GET https://api.github.com/repos/rust-lang/rust/commits?sha=master&per_page=3

An example with GitLab:

GET https://gitlab.com/api/v4/projects/inkscape%2Finkscape/repository/commits?ref_name=master&per_page=3

Both are really fast but have different interfaces (like every platform).


Disclaimer: Rust and Inkscape were chosen because of their size and safety to stay, no advertisement

How do I set a textbox's text to bold at run time?

 txtText.Font = new Font("Segoe UI", 8,FontStyle.Bold);
 //Font(Font Name,Font Size,Font.Style)

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

Convert a python 'type' object to a string

In case you want to use str() and a custom str method. This also works for repr.

class TypeProxy:
    def __init__(self, _type):
        self._type = _type

    def __call__(self, *args, **kwargs):
        return self._type(*args, **kwargs)

    def __str__(self):
        return self._type.__name__

    def __repr__(self):
        return "TypeProxy(%s)" % (repr(self._type),)

>>> str(TypeProxy(str))
'str'
>>> str(TypeProxy(type("")))
'str'

T-SQL How to create tables dynamically in stored procedures?

You can write the below code:-

create procedure spCreateTable
   as
    begin
       create table testtb(Name varchar(20))
    end

execute it as:-

exec spCreateTable

jQuery: Setting select list 'selected' based on text, failing strangely

The following works for text entries both with and without spaces:

$("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

Instead of loading a stream into a byte array and writing it to the response stream, you should have a look at HttpResponse.TransmitFile

Response.ContentType = "Application/pdf";
Response.TransmitFile(pathtofile);

If you want the PDF to open in a new window you would have to open the downloading page in a new window, for example like this:

<a href="viewpdf.aspx" target="_blank">View PDF</a>

Fit background image to div

try any of the following,

background-size: contain;
background-size: cover;
background-size: 100%;

.container{
    background-size: 100%;
}

Command to get latest Git commit hash from a branch

Note that when using "git log -n 1 [branch_name]" option. -n returns only one line of log but order in which this is returned is not guaranteed. Following is extract from git-log man page

.....
.....
Commit Limiting

Besides specifying a range of commits that should be listed using the special notations explained in the     description, additional commit limiting may be applied.

Using more options generally further limits the output (e.g. --since=<date1> limits to commits newer than <date1>, and using it with --grep=<pattern> further limits to commits whose log message has a line that matches <pattern>), unless otherwise noted.

Note that these are applied before commit ordering and formatting options, such as --reverse.

-<number>
-n <number>
.....
.....