Programs & Examples On #Gso

Can I use library that used android support with Androidx projects.

Manually adding android.useAndroidX=true and android.enableJetifier=true giving me hard time. Because it's throw some error or Suggestion: add 'tools:replace="android:appComponentFactory"' to <application>

To Enable Jet-fire in project there is option in android Studio

Select Your Project ---> Right Click

app----> Refactor ----> Migrate to AndroidX

Shown in below image:-

enter image description here

After click on Migrate to AndroidX.

It will ask for confirmation and back up for your project.

enter image description here

And last step it will ask you for to do refactor.

enter image description here

After doing Refactor check your gradle.properties have android.useAndroidX=true and android.enableJetifier=true. If they are not then add these two lines to your gradle.properties file:

android.useAndroidX=true
android.enableJetifier=true

Note:- Upgrading using Android Studio, this option works if you have android studio 3.2 and onward. Check this

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

Go to the build.gradle(Module App) in your project:

enter image description here

Follow the pic and change those version:

compileSdkVersion: 27
targetSdkVersion: 27

and if android studio version 2: Change the line with this line:

compile 'com.android.support:appcompat-v7:27.1.1'

else Change the line with this line:

implementation 'com.android.support:appcompat-v7:27.1.1'

and hopefully, you will solve your bug.

error: resource android:attr/fontVariationSettings not found

If you have stumbled upon this problem due to getting this error recently out of nowhere in react native- this is due to the latest BREAKING CHANGE in Google Play service and Firebase. Check this thread first -

https://github.com/facebook/react-native/issues/25293

And solution would mostly be like this -

https://github.com/facebook/react-native/issues/25293#issuecomment-503045776

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

It might be cause of a library, I faced it because of Glide.

It was

implementation 'com.github.bumptech.glide:glide:4.7.1'

So I added exclude group: "com.android.support" And it becomes

implementation ('com.github.bumptech.glide:glide:4.7.1') {
        exclude group: "com.android.support"
    }

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I solved it by deleting "/.idea/libraries" from project. Thanks

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

This is due to the series df[cat] containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna operation.

In other words

pandas data type 'Object' indicates mixed types rather than str type

so using the following line:

df[cat] = le.fit_transform(df[cat].astype(str))


should help

Unable to merge dex

I had same problem. I just enabled Instant Run(It was disabled) then my project worked. You can find it in-

File->Settings-> Build,Execution,Deployment->Instant Run

In Android studio 3.5 Instant Run have been removed. Please see here for reference

Android dependency has different version for the compile and runtime

I had the same error, what solve my problem was. In my library instead of using compile or implementation i use "api". So in the end my dependencies:

dependencies {
api fileTree(dir: 'libs', include: ['*.jar'])
api files('libs/model.jar')
testApi 'junit:junit:4.12'
api 'com.android.support:percent:26.0.0-beta2'
api 'com.android.support:appcompat-v7:26.0.0-beta2'
api 'com.android.support:support-core-utils:26.0.0-beta2'

api 'com.squareup.retrofit2:retrofit:2.0.2'
api 'com.squareup.picasso:picasso:2.4.0'
api 'com.squareup.retrofit2:converter-gson:2.0.2'
api 'com.squareup.okhttp3:logging-interceptor:3.2.0'
api 'uk.co.chrisjenx:calligraphy:2.2.0'
api 'com.google.code.gson:gson:2.2.4'
api 'com.android.support:design:26.0.0-beta2'
api 'com.github.PhilJay:MPAndroidChart:v3.0.1'
}

You can find more info about "api", "implementation" in this link https://stackoverflow.com/a/44493379/3479489

More than one file was found with OS independent path 'META-INF/LICENSE'

If you have this problem and you have a gradle .jar dependency, like this:

implementation group: 'org.mortbay.jetty', name: 'jetty', version: '6.1.26'

Interval versions until one matches and resolves the excepetion,and apply the best answer of this thread.`

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

Remember to pipe Observables to async, like *ngFor item of items$ | async, where you are trying to *ngFor item of items$ where items$ is obviously an Observable because you notated it with the $ similar to items$: Observable<IValuePair>, and your assignment may be something like this.items$ = this.someDataService.someMethod<IValuePair>() which returns an Observable of type T.

Adding to this... I believe I have used notation like *ngFor item of (items$ | async)?.someProperty

Seaborn Barplot - Displaying Values

Hope this helps for item #2: a) You can sort by total bill then reset the index to this column b) Use palette="Blue" to use this color to scale your chart from light blue to dark blue (if dark blue to light blue then use palette="Blues_d")

import pandas as pd
import seaborn as sns
%matplotlib inline

df=pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/master/ch08/tips.csv", sep=',')
groupedvalues=df.groupby('day').sum().reset_index()
groupedvalues=groupedvalues.sort_values('total_bill').reset_index()
g=sns.barplot(x='day',y='tip',data=groupedvalues, palette="Blues")

Retrofit 2: Get JSON from Response body

A better approach is to let Retrofit generate POJO for you from the json (using gson). First thing is to add .addConverterFactory(GsonConverterFactory.create()) when creating your Retrofit instance. For example, if you had a User java class (such as shown below) that corresponded to your json, then your retrofit api could return Call<User>

class User {
    private String id;
    private String Username;
    private String Level;
    ...
}    

error: package com.android.annotations does not exist

For Ionic, try this:

ionic cordova plugin add cordova-plugin-androidx
ionic cordova plugin add cordova-plugin-androidx-adapter

The error comes because this app is not using androidX but these plugins solve errors.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

Using Moshi:

When building your Retrofit Service add .asLenient() to your MoshiConverterFactory. You don't need a ScalarsConverter. It should look something like this:

return Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(ENDPOINT)
                .addConverterFactory(MoshiConverterFactory.create().asLenient())
                .build()
                .create(UserService::class.java)

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

Duplicate name Classes

like

class BackGroundTask extends AsyncTask<String, Void, Void> {

and

class BackgroundTask extends AsyncTask<String, Void, Void> {

Gson library in Android Studio

Add following dependency or download Gson jar file

implementation 'com.google.code.gson:gson:2.8.6'

Follow github repo for documentation and more.

The number of method references in a .dex file cannot exceed 64k API 17

This is what worked for me:

This happens because there are too many unused methods. Most of these methods are coming from included libraries in your build.gradle

Use minify and shrink resources to fix this with gradle and clean up your code at the same time.

buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            minifyEnabled true
            shrinkResources true
        }
    }

Execution failed for task ':app:processDebugResources' even with latest build tools

as a quick fix to this question, make sure your compile Sdk verion, your buildtoolsversion, your appcompat, and finally your support library are all running on the same sdk version, for further clarity take a look at the image i just uploaded. Cheers. Follow the red annotations and get rid of that trouble.

enter image description here

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

Add this line to ProGuard-rules.pro file:

-keepparameternames

That helped me while obfuscating library. I was getting zip exception when I add library as dependency.

File URL "Not allowed to load local resource" in the Internet Browser

For people do not like to modify chrome's security options, we can simply start a python http server from directory which contains your local file:

python -m SimpleHTTPServer

and for python 3:

python3 -m http.server

Now you can reach any local file directly from your js code or externally with http://127.0.0.1:8000/some_file.txt

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Just Android studio run 'Run as administrator' it will work

Or verify your package name on google-services.json file

android : Error converting byte to dex

I found in my case, this issue was caused by an improper configuration of build.gradle. I had two different versions of com.google.firebase. Once the versions were the same, the issue was solved

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

I was finding the same error complaining about mixing google play services version when switching from 8.3 to 8.4. Bizarrely I saw reference to the app-measurement lib which I wasn't using.

I thought maybe one of my app's dependencies was referencing the older version so I ran ./gradlew app:dependencies to find the offending library (non were).

But at the top of task output I found a error message saying that the google plugin could not be found and defaulting to google play services 8.3. I used the sample project @TheYann linked to compare. My setup was identical except I applied the apply plugin: 'com.google.gms.google-services' at the top my app's build.gradle file. I moved to bottom of the file and that fixed the gradle compile error.

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

Logging with Retrofit 2

Kotlin Code

        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
        val retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        return retrofit.create(PointApi::class.java)

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

The best solution is to change buildDir in build.gradle:

For example:

allprojects {
    buildDir = "C:/tmp/${rootProject.name}/${project.name}"
    repositories {
        jcenter()
    }
}

Rebuild and happy coding.

Send Post Request with params using Retrofit

You should create an interface for that like it is working well

public interface Service {
    @FormUrlEncoded
    @POST("v1/EmergencyRequirement.php/?op=addPatient")
    Call<Result> addPerson(@Field("BloodGroup") String bloodgroup,
           @Field("Address") String Address,
           @Field("City") String city, @Field("ContactNumber") String  contactnumber, 
           @Field("PatientName") String name, 
           @Field("Time") String Time, @Field("DonatedBy") String donar);
}

or you can visit to http://teachmeandroidhub.blogspot.com/2018/08/post-data-using-retrofit-in-android.html

and youcan vist to https://github.com/rajkumu12/GetandPostUsingRatrofit

how to parse JSON file with GSON

You have to fetch the whole data in the list and then do the iteration as it is a file and will become inefficient otherwise.

private static final Type REVIEW_TYPE = new TypeToken<List<Review>>() {
}.getType();
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
List<Review> data = gson.fromJson(reader, REVIEW_TYPE); // contains the whole reviews list
data.toScreen(); // prints to screen some values

How to set timeout in Retrofit library?

public class ApiClient {
    private static Retrofit retrofit = null;
    private static final Object LOCK = new Object();

    public static void clear() {
        synchronized (LOCK) {
            retrofit = null;
        }
    }

    public static Retrofit getClient() {
        synchronized (LOCK) {
            if (retrofit == null) {

                Gson gson = new GsonBuilder()
                        .setLenient()
                        .create();

                OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                        .connectTimeout(40, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();

                // Log.e("jjj", "=" + (MySharedPreference.getmInstance().isEnglish() ? Constant.WEB_SERVICE : Constant.WEB_SERVICE_ARABIC));
                retrofit = new Retrofit.Builder()
                        .client(okHttpClient)
                        .baseUrl(Constants.WEB_SERVICE)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .build();
            }
            return retrofit;
        }`enter code here`

    }

    public static RequestBody plain(String content) {
        return getRequestBody("text/plain", content);
    }

    public static RequestBody getRequestBody(String type, String content) {
        return RequestBody.create(MediaType.parse(type), content);
    }
}


-------------------------------------------------------------------------


    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

Convert Map to JSON using Jackson

You can convert Map to JSON using Jackson as follows:

Map<String,String> payload = new HashMap<>();
payload.put("key1","value1");
payload.put("key2","value2");

String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);

Android java.exe finished with non-zero exit value 1

Maybe you can change your buildToolsVersion num.

this is my problem:

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'D:\ProgramTools\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1

my build.gradle:

android {
    compileSdkVersion 23
    buildToolsVersion "24.0.0"

    defaultConfig {
        applicationId "com.pioneers.recyclerviewitemanimation"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

I just change buildToolsVersion to buildToolsVersion "23.0.2" and the problem was solved.

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

Try to clean and rebuild the project. I had the absolutely same question, this solved it.

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

In my case, my custom http-client didn't support the gzip encoding. I was sending the "Accept-Encoding: gzip" header, and so the response was sent back as a gzip string and couldn't be decoded.

The solution was to not send that header.

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

For those who are getting the "Unable to resolve dependencies" error:
Toggle "Offline Mode" off
('View'->Tool Windows->Gradle)

gradle window

Gradle DSL method not found: 'runProguard'

By changing runProguard to minifyEnabled, part of the issue gets fixed.

But the fix can cause "Library Projects cannot set application Id" (you can find the fix for this here Android Studio 1.0 and error "Library projects cannot set applicationId").

By removing application Id in the build.gradle file, you should be good to go.

Disable Logback in SpringBoot

I found that excluding the full spring-boot-starter-logging module is not necessary. All that is needed is to exclude the org.slf4j:slf4j-log4j12 module.

Adding this to a Gradle build file will resolve the issue:

configurations {
    runtime.exclude group: "org.slf4j", module: "slf4j-log4j12"
    compile.exclude group: "org.slf4j", module: "slf4j-log4j12"
}

See this other StackOverflow answer for more details.

Send POST request with JSON data using Volley

JsonObjectRequest actually accepts JSONObject as body.

From this blog article,

final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{\"type\":\"example\"}");

new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });

Here is the source code and JavaDoc (@param jsonRequest):

/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
        Listener<JSONObject> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
}

When do you use map vs flatMap in RxJava?

In some cases you might end up having chain of observables, wherein your observable would return another observable. 'flatmap' kind of unwraps the second observable which is buried in the first one and let you directly access the data second observable is spitting out while subscribing.

Http 415 Unsupported Media type error with JSON

If you are using AJAX jQuery Request this is a must to apply. If not it will throw you 415 Error.

dataType: "json",
contentType:'application/json'

Groovy - Convert object to JSON string

You can use JsonBuilder for that.

Example Code:

import groovy.json.JsonBuilder

class Person {
    String name
    String address
}

def o = new Person( name: 'John Doe', address: 'Texas' )

println new JsonBuilder( o ).toPrettyString()

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Response you are getting is in object form i.e.

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

Replace below line of code :

List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))

with

Post post = gson.fromJson(reader, Post.class);

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

A similar dex issue resolved method

gradle.build was containing:

compile files('libs/httpclient-4.2.1.jar')
compile 'org.apache.httpcomponents:httpclient:4.5'
compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'

The issue was resolved when i removed

compile files('libs/httpclient-4.2.1.jar') 

My gradle now looks like:

apply plugin: 'com.android.application'

android {

compileSdkVersion 24
buildToolsVersion "24.0.3"

defaultConfig {
    applicationId "com.mmm.ll"
    minSdkVersion 16
    targetSdkVersion 24
    useLibrary  'org.apache.http.legacy'
}

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
}

dependencies {

compile 'com.google.android.gms:play-services:6.1.+'
compile files('libs/PayPalAndroidSDK.jar')
compile files('libs/ksoap2-android-assembly-3.0.0-RC.4-jar-with-dependencies.jar')
compile files('libs/picasso-2.1.1.jar')
compile files('libs/gcm.jar')
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}

There was a redundancy in the JAR file and the compiled gradle project

So keenly look for dependency and jar files having same classes.

And remove redundancy.
This worked for me.

No Access-Control-Allow-Origin header is present on the requested resource

Solution:
Instead of using setHeader method I have used addHeader.

response.addHeader("Access-Control-Allow-Origin", "*");

* in above line will allow access to all domains, For allowing access to specific domain only:

response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");

For issues related to IE<=9, Please see here.

Bootstrap 3 - 100% height of custom div inside column

I was just looking for a smiliar issue and I found this:

.div{
  height : 100vh;
}

more info

vw: 1/100th viewport width
vh: 1/100th viewport height
vmin: 1/100th of the smallest side
vmax: 1/100th of the largest side

How to run JUnit tests with Gradle?

How do I add a junit 4 dependency correctly?

Assuming you're resolving against a standard Maven (or equivalent) repo:

dependencies {
    ...
    testCompile "junit:junit:4.11"  // Or whatever version
}

Run those tests in the folders of tests/model?

You define your test source set the same way:

sourceSets {
    ...

    test {
        java {
            srcDirs = ["test/model"]  // Note @Peter's comment below
        }
    }
}

Then invoke the tests as:

./gradlew test

EDIT: If you are using JUnit 5 instead, there are more steps to complete, you should follow this tutorial.

How to add local .jar file dependency to build.gradle file?

The best way to do it is to add this in your build.gradle file and hit the sync option

dependency{
    compile files('path.jar')
}

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

In my case I only need to add to project's build.gradle file:

android {
  packagingOptions {
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
  }

   ...
}

Testing Spring's @RequestBody using Spring MockMVC

I have encountered a similar problem with a more recent version of Spring. I tried to use a new ObjectMapper().writeValueAsString(...) but it would not work in my case.

I actually had a String in a JSON format, but I feel like it is literally transforming the toString() method of every field into JSON. In my case, a date LocalDate field would end up as:

"date":{"year":2021,"month":"JANUARY","monthValue":1,"dayOfMonth":1,"chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfWeek":"FRIDAY","leapYear":false,"dayOfYear":1,"era":"CE"}

which is not the best date format to send in a request ...

In the end, the simplest solution in my case is to use the Spring ObjectMapper. Its behaviour is better since it uses Jackson to build your JSON with complex types.

@Autowired
private ObjectMapper objectMapper;

and I simply used it in mytest:

mockMvc.perform(post("/api/")
                .content(objectMapper.writeValueAsString(...))
                .contentType(MediaType.APPLICATION_JSON)
);

Parsing JSON in Java without knowing JSON format

JSON of unknown format to HashMap

writing JSON And reading Json

public static JsonParser parser = new JsonParser();
public static void main(String args[]) {
     writeJson("JsonFile.json");
     readgson("JsonFile.json");
}
public static void readgson(String file) {
    try {
        System.out.println( "Reading JSON file from Java program" );

        FileReader fileReader = new FileReader( file );
        com.google.gson.JsonObject object = (JsonObject) parser.parse( fileReader );

        Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys = object.entrySet();
        if ( keys.isEmpty() ) {
            System.out.println( "Empty JSON Object" );
        }else {
            Map<String, Object> map = json_UnKnown_Format( keys );
            System.out.println("Json 2 Map : "+map);
        }

    } catch (IOException ex) {
        System.out.println("Input File Does not Exists.");
    }
}
public static Map<String, Object> json_UnKnown_Format( Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys ){
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    for (Entry<String, JsonElement> entry : keys) {
        String keyEntry = entry.getKey();
        System.out.println(keyEntry + " : ");
        JsonElement valuesEntry =  entry.getValue();
        if (valuesEntry.isJsonNull()) {
            System.out.println(valuesEntry);
            jsonMap.put(keyEntry, valuesEntry);
        }else if (valuesEntry.isJsonPrimitive()) {
            System.out.println("P - "+valuesEntry);
            jsonMap.put(keyEntry, valuesEntry);
        }else if (valuesEntry.isJsonArray()) {
            JsonArray array = valuesEntry.getAsJsonArray();
            List<Object> array2List = new ArrayList<Object>();
            for (JsonElement jsonElements : array) {
                System.out.println("A - "+jsonElements);
                array2List.add(jsonElements);
            }
            jsonMap.put(keyEntry, array2List);
        }else if (valuesEntry.isJsonObject()) {             
             com.google.gson.JsonObject obj = (JsonObject) parser.parse(valuesEntry.toString());                    
             Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> obj_key = obj.entrySet();
             jsonMap.put(keyEntry, json_UnKnown_Format(obj_key));
        }
    }
    return jsonMap;
}
@SuppressWarnings("unchecked")
public static void writeJson( String file ) {

    JSONObject json = new JSONObject();

    json.put("Key1", "Value");
    json.put("Key2", 777); // Converts to "777"
    json.put("Key3", null);
    json.put("Key4", false);

        JSONArray jsonArray = new JSONArray();
        jsonArray.put("Array-Value1");
        jsonArray.put(10); 
        jsonArray.put("Array-Value2");

    json.put("Array : ", jsonArray); // "Array":["Array-Value1", 10,"Array-Value2"]

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("Obj-Key1", 20);
        jsonObj.put("Obj-Key2", "Value2");
        jsonObj.put(4, "Value2"); // Converts to "4"

    json.put("InnerObject", jsonObj);

        JSONObject jsonObjArray = new JSONObject();
            JSONArray objArray = new JSONArray();
            objArray.put("Obj-Array1");
            objArray.put(0, "Obj-Array3");
        jsonObjArray.put("ObjectArray", objArray);

    json.put("InnerObjectArray", jsonObjArray);

        Map<String, Integer> sortedTree = new TreeMap<String, Integer>();
        sortedTree.put("Sorted1", 10);
        sortedTree.put("Sorted2", 103);
        sortedTree.put("Sorted3", 14);

    json.put("TreeMap", sortedTree);        

    try {
        System.out.println("Writting JSON into file ...");
        System.out.println(json);
        FileWriter jsonFileWriter = new FileWriter(file);
        jsonFileWriter.write(json.toJSONString());
        jsonFileWriter.flush();
        jsonFileWriter.close();
        System.out.println("Done");

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

}

How do I use the new computeIfAbsent function?

Recently I was playing with this method too. I wrote a memoized algorithm to calcualte Fibonacci numbers which could serve as another illustration on how to use the method.

We can start by defining a map and putting the values in it for the base cases, namely, fibonnaci(0) and fibonacci(1):

private static Map<Integer,Long> memo = new HashMap<>();
static {
   memo.put(0,0L); //fibonacci(0)
   memo.put(1,1L); //fibonacci(1)
}

And for the inductive step all we have to do is redefine our Fibonacci function as follows:

public static long fibonacci(int x) {
   return memo.computeIfAbsent(x, n -> fibonacci(n-2) + fibonacci(n-1));
}

As you can see, the method computeIfAbsent will use the provided lambda expression to calculate the Fibonacci number when the number is not present in the map. This represents a significant improvement over the traditional, tree recursive algorithm.

how to bind datatable to datagridview in c#

Even better:

DataTable DTable = new DataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = DTable;
DataGridView ServersTable = new DataGridView();

ServersTable.AutoGenerateColumns = false;
ServersTable.DataSource = DTable;

ServersTable.DataSource = SBind;
ServersTable.Refresh();

You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

Parsing JSON array into java.util.List with Gson

Definitely the easiest way to do that is using Gson's default parsing function fromJson().

There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType (e.g., any List), which is fromJson(JsonElement json, Type typeOfT).

In your case, you just need to get the Type of a List<String> and then parse the JSON array into that Type, like this:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();

List<String> yourList = new Gson().fromJson(yourJson, listType);

In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.

You may want to take a look at Gson API documentation.

Using GSON to parse a JSON array

Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);

class Wrapper{
    int number;
    String title;       
}

Seems to work fine. But there is an extra , Comma in your string.

[
    { 
        "number" : "3",
        "title" : "hello_world"
    },
    { 
        "number" : "2",
        "title" : "hello_world"
    }
]

Android list view inside a scroll view

using this ListView Worked for me

   package net.londatiga.android.widget;

      import android.util.AttributeSet;
      import android.view.ViewGroup;
      import android.widget.ListView;
      import android.content.Context;

   public class ExpandableHeightListView extends ListView
      {

    boolean expanded = false;

      public ExpandableHeightListView(Context context)
    {
    super(context);
}

public ExpandableHeightListView(Context context, AttributeSet attrs)
{
    super(context, attrs);
}

public ExpandableHeightListView(Context context, AttributeSet attrs,
        int defStyle)
{
    super(context, attrs, defStyle);
}

public boolean isExpanded()
{
    return expanded;
}

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    // HACK! TAKE THAT ANDROID!
    if (isExpanded())
    {
        // Calculate entire height by providing a very large height hint.
        // But do not use the highest 2 bits of this integer; those are
        // reserved for the MeasureSpec mode.
        int expandSpec = MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);

        ViewGroup.LayoutParams params = getLayoutParams();
        params.height = getMeasuredHeight();
    }
    else
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

public void setExpanded(boolean expanded)
{
    this.expanded = expanded;
}
}

and in xml

            <com.pakagename.ExpandableHeightListView
                android:id="@+id/expandableHeightListView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >
            </com.Example.ExpandableHeightListView>

and in MainActivity

  ExpandableHeightListView listView = new ExpandableHeightListView(this);
    listview=(ExpandableHeightListView)findViewById(R.id.expandableHeightListView);
   listView.setAdapter(adapter); //set your adaper
   listView.setExpanded(true);

Refer This article for more info and also to know how to keep gridview inside scroll view

how to refresh my datagridview after I add new data

In the code of the button that saves the changes to the database eg the update button, add the following lines of code:

MyDataGridView.DataSource = MyTableBindingSource

MyDataGridView.Update()

MyDataGridView.RefreshEdit()

Populate a datagridview with sql query results

Years late but here's the simplest for others in case.

String connectionString = @"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";

SqlConnection cnn = new SqlConnection(connectionString);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);

DataTable data = new DataTable();
sda.Fill(data);

DataGridView1.DataSource = data;

Using DataSet is not necessary and DataTable should be good enough. SQLCommandBuilder is unnecessary either.

Update my gradle dependencies in eclipse

Looking at the Eclipse plugin docs I found some useful tasks that rebuilt my classpath and updated the required dependencies.

  • First try gradle cleanEclipse to clean the Eclipse configuration completely. If this doesn;t work you may try more specific tasks:
    • gradle cleanEclipseProject to remove the .project file
    • gradle cleanEclipseClasspath to empty the project's classpath
  • Finally gradle eclipse to rebuild the Eclipse configuration

How to use Tomcat 8 in Eclipse?

I follow Jason's step, but not works.

And then I find the WTP Update site http://download.eclipse.org/webtools/updates/.

Help -> Install new software -> Add > WTP:http://download.eclipse.org/webtools/updates/ -> OK

Then Help -> Check for update, just works, I don't know whether Jason's affect this .

How to use new PasswordEncoder from Spring Security

Here is the implementation of BCrypt which is working for me.

in spring-security.xml

<authentication-manager >
    <authentication-provider ref="authProvider"></authentication-provider>  
    </authentication-manager>
<beans:bean id="authProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
  <beans:property name="userDetailsService" ref="userDetailsServiceImpl" />
  <beans:property name="passwordEncoder" ref="encoder" />
</beans:bean>
<!-- For hashing and salting user passwords -->
    <beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

In java class

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String hashedPassword = passwordEncoder.encode(yourpassword);

For more detailed example of spring security Click Here

Hope this will help.

Thanks

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

Android Studio: Add jar as library?

Download & Copy Your .jar file in libs folder then adding these line to build.gradle:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.code.gson:gson:2.3.1'
}

Do not forget to click "Sync now"

Is it possible to use argsort in descending order?

Instead of using np.argsort you could use np.argpartition - if you only need the indices of the lowest/highest n elements.

That doesn't require to sort the whole array but just the part that you need but note that the "order inside your partition" is undefined, so while it gives the correct indices they might not be correctly ordered:

>>> avgDists = [1, 8, 6, 9, 4]
>>> np.array(avgDists).argpartition(2)[:2]  # indices of lowest 2 items
array([0, 4], dtype=int64)

>>> np.array(avgDists).argpartition(-2)[-2:]  # indices of highest 2 items
array([1, 3], dtype=int64)

Parse JSON file using GSON

One thing that to be remembered while solving such problems is that in JSON file, a { indicates a JSONObject and a [ indicates JSONArray. If one could manage them properly, it would be very easy to accomplish the task of parsing the JSON file. The above code was really very helpful for me and I hope this content adds some meaning to the above code.

The Gson JsonReader documentation explains how to handle parsing of JsonObjects and JsonArrays:

  • Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
  • Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().

Spring MVC @PathVariable with dot (.) is getting truncated

In Spring Boot, The Regular expression solve the problem like

@GetMapping("/path/{param1:.+}")

Eclipse will not start and I haven't changed anything

If you deleted all data in .metadata directory. There is a quick way to import all your projects again. Try this:

File --> Import --> General: Select Existing projects into workspace --> Select root directory: Browse to old workspace folder (the SAME with the current workspace folder is OK) --> Finish.

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

it can only be lazily loaded whilst within a transaction. So you could access the collection in your repository, which has a transaction - or what I normally do is a get with association, or set fetchmode to eager.

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

To me the solution was just deleted the specific folder which is giving the error from ~/.m2/repository/org/hsqldb/

After deleting the hsqldb folder I have build the project and everything is fine.

How to convert list data into json in java

i wrote my own function to return list of object for populate combo box :

public static String getJSONList(java.util.List<Object> list,String kelas,String name, String label) {
        try {
            Object[] args={};
            Class cl = Class.forName(kelas);
            Method getName = cl.getMethod(name, null);
            Method getLabel = cl.getMethod(label, null);
            String json="[";
            for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            if(i>0){
                json+=",";
            }
            json+="{\"label\":\""+getLabel.invoke(o,args)+"\",\"name\":\""+getName.invoke(o,args)+"\"}";
            //System.out.println("Object = " + i+" -> "+o.getNumber());
            }
            json+="]";
            return json;
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(JSONHelper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            System.out.println("Error in get JSON List");
            ex.printStackTrace();
        }
        return "";
    }

and call it from anywhere like :

String toreturn=JSONHelper.getJSONList(list, "com.bean.Contact", "getContactID", "getNumber");

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

This is the solution for my old question:

I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature.

package org.lig.hadas.services.mapper;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

@Produces(MediaType.APPLICATION_JSON)
@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper>
{
   ObjectMapper mapper;

   public ObjectMapperProvider(){
       mapper = new ObjectMapper();
       mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
   }
   @Override
   public ObjectMapper getContext(Class<?> type) {
       return mapper;
   }
}

And in the web.xml I registered my package into the servlet definition...

<servlet>
    <servlet-name>...</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>...;org.lig.hadas.services.mapper</param-value>        
    </init-param>
    ...
</servlet>

... all the rest is transparently done by jersey/jackson.

@Cacheable key on multiple method arguments

After some limited testing with Spring 3.2, it seems one can use a SpEL list: {..., ..., ...}. This can also include null values. Spring passes the list as the key to the actual cache implementation. When using Ehcache, such will at some point invoke List#hashCode(), which takes all its items into account. (I am not sure if Ehcache only relies on the hash code.)

I use this for a shared cache, in which I include the method name in the key as well, which the Spring default key generator does not include. This way I can easily wipe the (single) cache, without (too much...) risking matching keys for different methods. Like:

@Cacheable(value="bookCache", 
  key="{ #root.methodName, #isbn?.id, #checkWarehouse }")
public Book findBook(ISBN isbn, boolean checkWarehouse) 
...

@Cacheable(value="bookCache", 
  key="{ #root.methodName, #asin, #checkWarehouse }")
public Book findBookByAmazonId(String asin, boolean checkWarehouse)
...

Of course, if many methods need this and you're always using all parameters for your key, then one can also define a custom key generator that includes the class and method name:

<cache:annotation-driven mode="..." key-generator="cacheKeyGenerator" />
<bean id="cacheKeyGenerator" class="net.example.cache.CacheKeyGenerator" />

...with:

public class CacheKeyGenerator 
  implements org.springframework.cache.interceptor.KeyGenerator {

    @Override
    public Object generate(final Object target, final Method method, 
      final Object... params) {

        final List<Object> key = new ArrayList<>();
        key.add(method.getDeclaringClass().getName());
        key.add(method.getName());

        for (final Object o : params) {
            key.add(o);
        }
        return key;
    }
}

Jersey client: How to add a list as query parameter

One could use the queryParam method, passing it parameter name and an array of values:

    public WebTarget queryParam(String name, Object... values);

Example (jersey-client 2.23.2):

    WebTarget target = ClientBuilder.newClient().target(URI.create("http://localhost"));
    target.path("path")
            .queryParam("param_name", Arrays.asList("paramVal1", "paramVal2").toArray())
            .request().get();

This will issue request to following URL:

    http://localhost/path?param_name=paramVal1&param_name=paramVal2

Gson - convert from Json to a typed ArrayList<T>

Why nobody wrote this simple way of converting JSON string in List ?

List<Object> list = Arrays.asList(new GsonBuilder().create().fromJson(jsonString, Object[].class));

How to change column width in DataGridView?

In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode property to None.

gson throws MalformedJsonException

In the debugger you don't need to add back slashes, the input field understands the special chars.

In java code you need to escape the special chars

How to modify values of JsonObject / JsonArray directly?

This works for modifying childkey value using JSONObject. import used is

import org.json.JSONObject;

ex json:(convert json file to string while giving as input)

{
    "parentkey1": "name",
    "parentkey2": {
     "childkey": "test"
    },
}

Code

JSONObject jObject  = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);

output:

{
    "parentkey1": "name",
    "parentkey2": {
     "childkey": "data1"
    },
}

how to save canvas as png image?

To accomodate all three points:

  • button
  • save the image as a png file
  • open up the save, open, close dialog box

The file dialog is a setting in the browser.

For the button/save part assign the following function, boiled down from other answers, to your buttons onclick:

function DownloadCanvasAsImage(){
    let downloadLink = document.createElement('a');
    downloadLink.setAttribute('download', 'CanvasAsImage.png');
    let canvas = document.getElementById('myCanvas');
    let dataURL = canvas.toDataURL('image/png');
    let url = dataURL.replace(/^data:image\/png/,'data:application/octet-stream');
    downloadLink.setAttribute('href', url);
    downloadLink.click();
}

Example on Codepen

Another, somewhat cleaner, approach is using Canvas.toBlob():

function DownloadCanvasAsImage(){
    let downloadLink = document.createElement('a');
    downloadLink.setAttribute('download', 'CanvasAsImage.png');
    let canvas = document.getElementById('myCanvas');
    canvas.toBlob(function(blob) {
      let url = URL.createObjectURL(blob);
      downloadLink.setAttribute('href', url);
      downloadLink.click();
    });
}

Example on Codepen

Neither solution is 100% cross browser compatible, so check the client

RESTful Authentication via Spring

You might consider Digest Access Authentication. Essentially the protocol is as follows:

  1. Request is made from client
  2. Server responds with a unique nonce string
  3. Client supplies a username and password (and some other values) md5 hashed with the nonce; this hash is known as HA1
  4. Server is then able to verify client's identity and serve up the requested materials
  5. Communication with the nonce can continue until the server supplies a new nonce (a counter is used to eliminate replay attacks)

All of this communication is made through headers, which, as jmort253 points out, is generally more secure than communicating sensitive material in the url parameters.

Digest Access Authentication is supported by Spring Security. Notice that, although the docs say that you must have access to your client's plain-text password, you can successfully authenticate if you have the HA1 hash for your client.

change <audio> src with javascript

Try this:

Replace:

audio.load();

with:

audio.play();

Does Spring Data JPA have any way to count entites using method name resolving?

Thanks you all! Now it's work. DATAJPA-231

It will be nice if was possible to create count…By… methods just like find…By ones. Example:

public interface UserRepository extends JpaRepository<User, Long> {

   public Long /*or BigInteger */ countByActiveTrue();
}

How to query data out of the box using Spring data JPA by both Sort and Pageable?

in 2020, the accepted answer is kinda out of date since the PageRequest is deprecated, so you should use code like this :

Pageable page = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by("id").descending());
return repository.findAll(page);

Find a row in dataGridView based on column and value

Those who use WPF

for (int i = 0; i < dataGridName.Items.Count; i++)
{
      string cellValue= ((DataRowView)dataGridName.Items[i]).Row["columnName"].ToString();                
      if (cellValue.Equals("Search_string")) // check the search_string is present in the row of ColumnName
      {
         object item = dataGridName.Items[i];
         dataGridName.SelectedItem = item; // selecting the row of dataGridName
         dataGridName.ScrollIntoView(item);                    
         break;
      }
}

if you want to get the selected row items after this, the follwing code snippet is helpful

DataRowView drv = dataGridName.SelectedItem as DataRowView;
DataRow dr = drv.Row;
string item1= Convert.ToString(dr.ItemArray[0]);// get the first column value from selected row 
string item2= Convert.ToString(dr.ItemArray[1]);// get the second column value from selected row 

Converting Object to JSON and JSON to Object in PHP, (library like Gson for Java)

for more extendability for large scale apps use oop style with encapsulated fields.

Simple way :-

  class Fruit implements JsonSerializable {

        private $type = 'Apple', $lastEaten = null;

        public function __construct() {
            $this->lastEaten = new DateTime();
        }

        public function jsonSerialize() {
            return [
                'category' => $this->type,
                'EatenTime' => $this->lastEaten->format(DateTime::ISO8601)
            ];
        }
    }

echo json_encode(new Fruit()); //which outputs:

{"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"}

Real Gson on PHP :-

  1. http://jmsyst.com/libs/serializer
  2. http://symfony.com/doc/current/components/serializer.html
  3. http://framework.zend.com/manual/current/en/modules/zend.serializer.html
  4. http://fractal.thephpleague.com/ - serialize only

Insert variable into Header Location PHP

header('Location: http://linkhere.com/' . $your_variable);

Getting the Facebook like/share count for a given URL

UPDATE: This solution is no longer valid. FQLs are deprecated since August 7th, 2016.


https://api.facebook.com/method/fql.query?query=select%20%20like_count%20from%20link_stat%20where%20url=%22http://www.techlila.com%22

Also http://api.facebook.com/restserver.php?method=links.getStats&urls=http://www.techlila.com will show you all the data like 'Share Count', 'Like Count' and 'Comment Count' and total of all these.

Change the URL (i.e. http://www.techlila.com) as per your need.

This is the correct URL, I'm getting right results.

EDIT (May 2017): as of v2.9 you can make a graph API call where ID is the URL and select the 'engagement' field, below is a link with the example from the graph explorer.

https://developers.facebook.com/tools/explorer/?method=GET&path=%3Fid%3Dhttp%3A%2F%2Fcomunidade.edp.pt%26fields%3Dengagement&version=v2.9

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

You need to let Gson know additional type of your response as below

import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type;


Type collectionType = new TypeToken<List<UserSite>>(){}.getType();
List<UserSite> userSites  = gson.fromJson( response.getBody() , collectionType);

No matching bean of type ... found for dependency

I had the same issue but in my case, implemented class was accidently become 'abstract' as a result autowiring was failing.

How to fluently build JSON in Java?

It sounds like you probably want to get ahold of json-lib:

http://json-lib.sourceforge.net/

Douglas Crockford is the guy who invented JSON; his Java library is here:

http://www.json.org/java/

It sounds like the folks at json-lib picked up where Crockford left off. Both fully support JSON, both use (compatible, as far as I can tell) JSONObject, JSONArray and JSONFunction constructs.

'Hope that helps ..

How to Parse JSON Array with Gson

[
      {
           id : '1',
           title: 'sample title',
           ....
      },
      {
           id : '2',
           title: 'sample title',
           ....
     },
      ...
 ]

Check Easy code for this output

 Gson gson=new GsonBuilder().create();
                List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));

Gson: Is there an easier way to serialize a map

I'm pretty sure GSON serializes/deserializes Maps and multiple-nested Maps (i.e. Map<String, Map<String, Object>>) just fine by default. The example provided I believe is nothing more than just a starting point if you need to do something more complex.

Check out the MapTypeAdapterFactory class in the GSON source: http://code.google.com/p/google-gson/source/browse/trunk/gson/src/main/java/com/google/gson/internal/bind/MapTypeAdapterFactory.java

So long as the types of the keys and values can be serialized into JSON strings (and you can create your own serializers/deserializers for these custom objects) you shouldn't have any issues.

Parse JSON String to JSON Object in C#.NET

I see that this question is very old, but this is the solution I used for the same problem, and it seems to require a bit less code than the others.

As @Maloric mentioned in his answer to this question:

var jo = JObject.Parse(myJsonString);

To use JObject, you need the following in your class file

using Newtonsoft.Json.Linq;

Maven plugin not using Eclipse's proxy settings

Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.

Parsing JSON from URL

GSON has a builder that takes a Reader object: fromJson(Reader json, Class classOfT).

This means you can create a Reader from a URL and then pass it to Gson to consume the stream and do the deserialisation.

Only three lines of relevant code.

import java.io.InputStreamReader;
import java.net.URL;
import java.util.Map;

import com.google.gson.Gson;

public class GsonFetchNetworkJson {

    public static void main(String[] ignored) throws Exception {

        URL url = new URL("https://httpbin.org/get?color=red&shape=oval");
        InputStreamReader reader = new InputStreamReader(url.openStream());
        MyDto dto = new Gson().fromJson(reader, MyDto.class);

        // using the deserialized object
        System.out.println(dto.headers);
        System.out.println(dto.args);
        System.out.println(dto.origin);
        System.out.println(dto.url);
    }

    private class MyDto {
        Map<String, String> headers;
        Map<String, String> args;
        String origin;
        String url;
    }
}

If you happen to get a 403 error code with an endpoint which otherwise works fine (e.g. with curl or other clients) then a possible cause could be that the endpoint expects a User-Agent header and by default Java URLConnection is not setting it. An easy fix is to add at the top of the file e.g. System.setProperty("http.agent", "Netscape 1.0");.

How do I use a custom Serializer with Jackson?

These are behavior patterns I have noticed while trying to understand Jackson serialization.

1) Assume there is an object Classroom and a class Student. I've made everything public and final for ease.

public class Classroom {
    public final double double1 = 1234.5678;
    public final Double Double1 = 91011.1213;
    public final Student student1 = new Student();
}

public class Student {
    public final double double2 = 1920.2122;
    public final Double Double2 = 2324.2526;
}

2) Assume that these are the serializers we use for serializing the objects into JSON. The writeObjectField uses the object's own serializer if it is registered with the object mapper; if not, then it serializes it as a POJO. The writeNumberField exclusively only accepts primitives as arguments.

public class ClassroomSerializer extends StdSerializer<Classroom> {
    public ClassroomSerializer(Class<Classroom> t) {
        super(t);
    }

    @Override
    public void serialize(Classroom value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
        jgen.writeStartObject();
        jgen.writeObjectField("double1-Object", value.double1);
        jgen.writeNumberField("double1-Number", value.double1);
        jgen.writeObjectField("Double1-Object", value.Double1);
        jgen.writeNumberField("Double1-Number", value.Double1);
        jgen.writeObjectField("student1", value.student1);
        jgen.writeEndObject();
    }
}

public class StudentSerializer extends StdSerializer<Student> {
    public StudentSerializer(Class<Student> t) {
        super(t);
    }

    @Override
    public void serialize(Student value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
        jgen.writeStartObject();
        jgen.writeObjectField("double2-Object", value.double2);
        jgen.writeNumberField("double2-Number", value.double2);
        jgen.writeObjectField("Double2-Object", value.Double2);
        jgen.writeNumberField("Double2-Number", value.Double2);
        jgen.writeEndObject();
    }
}

3) Register only a DoubleSerializer with DecimalFormat output pattern ###,##0.000, in SimpleModule and the output is:

{
  "double1" : 1234.5678,
  "Double1" : {
    "value" : "91,011.121"
  },
  "student1" : {
    "double2" : 1920.2122,
    "Double2" : {
      "value" : "2,324.253"
    }
  }
}

You can see that the POJO serialization differentiates between double and Double, using the DoubleSerialzer for Doubles and using a regular String format for doubles.

4) Register DoubleSerializer and ClassroomSerializer, without the StudentSerializer. We expect that the output is such that if we write a double as an object, it behaves like a Double, and if we write a Double as a number, it behaves like a double. The Student instance variable should be written as a POJO and follow the pattern above since it does not register.

{
  "double1-Object" : {
    "value" : "1,234.568"
  },
  "double1-Number" : 1234.5678,
  "Double1-Object" : {
    "value" : "91,011.121"
  },
  "Double1-Number" : 91011.1213,
  "student1" : {
    "double2" : 1920.2122,
    "Double2" : {
      "value" : "2,324.253"
    }
  }
}

5) Register all serializers. The output is:

{
  "double1-Object" : {
    "value" : "1,234.568"
  },
  "double1-Number" : 1234.5678,
  "Double1-Object" : {
    "value" : "91,011.121"
  },
  "Double1-Number" : 91011.1213,
  "student1" : {
    "double2-Object" : {
      "value" : "1,920.212"
    },
    "double2-Number" : 1920.2122,
    "Double2-Object" : {
      "value" : "2,324.253"
    },
    "Double2-Number" : 2324.2526
  }
}

exactly as expected.

Another important note: If you have multiple serializers for the same class registered with the same Module, then the Module will select the serializer for that class that is most recently added to the list. This should not be used - it's confusing and I am not sure how consistent this is

Moral: if you want to customize serialization of primitives in your object, you must write your own serializer for the object. You cannot rely on the POJO Jackson serialization.

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

Here is a blog post that compares @Resource, @Inject, and @Autowired, and appears to do a pretty comprehensive job.

From the link:

With the exception of test 2 & 7 the configuration and outcomes were identical. When I looked under the hood I determined that the ‘@Autowired’ and ‘@Inject’ annotation behave identically. Both of these annotations use the ‘AutowiredAnnotationBeanPostProcessor’ to inject dependencies. ‘@Autowired’ and ‘@Inject’ can be used interchangeable to inject Spring beans. However the ‘@Resource’ annotation uses the ‘CommonAnnotationBeanPostProcessor’ to inject dependencies. Even though they use different post processor classes they all behave nearly identically. Below is a summary of their execution paths.

Tests 2 and 7 that the author references are 'injection by field name' and 'an attempt at resolving a bean using a bad qualifier', respectively.

The Conclusion should give you all the information you need.

GSON - Date format

In case if you hate Inner classes, by taking the advantage of functional interface you can write less code in Java 8 with a lambda expression.

JsonDeserializer<Date> dateJsonDeserializer = 
     (json, typeOfT, context) -> json == null ? null : new Date(json.getAsLong());
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class,dateJsonDeserializer).create();

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

We can add "AwaitTerminationSeconds" property for both taskExecutor and taskScheduler as below,

<property name="awaitTerminationSeconds" value="${taskExecutor .awaitTerminationSeconds}" />

<property name="awaitTerminationSeconds" value="${taskScheduler .awaitTerminationSeconds}" />

Documentation for "waitForTasksToCompleteOnShutdown" property says, when shutdown is called

"Spring's container shutdown continues while ongoing tasks are being completed. If you want this executor to block and wait for the termination of tasks before the rest of the container continues to shut down - e.g. in order to keep up other resources that your tasks may need -, set the "awaitTerminationSeconds" property instead of or in addition to this property."

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.html#setWaitForTasksToCompleteOnShutdown-boolean-

So it is always advised to use waitForTasksToCompleteOnShutdown and awaitTerminationSeconds properties together. Value of awaitTerminationSeconds depends on our application.

Using a list as a data source for DataGridView

this Func may help you . it add every list object to grid view

private void show_data()
        {
            BindingSource Source = new BindingSource();

            for (int i = 0; i < CC.Contects.Count; i++)
            {
                Source.Add(CC.Contects.ElementAt(i));
            };


            Data_View.DataSource = Source;

        }

I write this for simple database app

Fastest way to download a GitHub project

I agree with the current answers, I just wanna add little more information, Here's a good functionality

if you want to require just zip file but the owner has not prepared a zip file,

To simply download a repository as a zip file: add the extra path /zipball/master/ to the end of the repository URL, This will give you a full ZIP file

For example, here is your repository

https://github.com/spring-projects/spring-data-graph-examples

Add zipball/master/ in your repository link

https://github.com/spring-projects/spring-data-graph-examples/zipball/master/

Paste the URL into your browser and it will give you a zip file to download

Binding Combobox Using Dictionary as the Datasource

A dictionary cannot be directly used as a data source, you should do more.

SortedDictionary<string, int> userCache =  UserCache.getSortedUserValueCache();
KeyValuePair<string, int> [] ar= new KeyValuePair<string,int>[userCache.Count];
userCache.CopyTo(ar, 0);
comboBox1.DataSource = ar; new BindingSource(ar, "Key"); //This line is causing the error
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

How to solve "Plugin execution not covered by lifecycle configuration" for Spring Data Maven Builds

Goto workspace/rtc-ws/.metadata/.plugins/org.eclipse.m2e.core/lifecycle-mapping-metadata.xml then create lifecycle-mapping-metadata.xml file and paste below and reload configuration as below

If you are using Eclipse 4.2 and have troubles with mapping and won't put mess into yours pom.xml create new file lifecycle-mapping-metadata.xml configure it in Windows -> Preferences -> Lifecycle mapping (don't forget press Reload workspace lifecycle mappings metadata after each change of this file!). Here is example based on eclipse/plugins/org.eclipse.m2e.lifecyclemapping.defaults_1.2.0.20120903-1050.jar/lifecycle-mapping-metadata.xml

<?xml version="1.0" encoding="UTF-8"?>
<lifecycleMappingMetadata>
    <pluginExecutions>
        <pluginExecution>
            <pluginExecutionFilter>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>buildnumber-maven-plugin</artifactId>
                <goals>
                    <goal>create-timestamp</goal>
                </goals>
                <versionRange>[0.0,)</versionRange>
            </pluginExecutionFilter>
            <action>
                <ignore />
            </action>
        </pluginExecution>

        <pluginExecution>
            <pluginExecutionFilter>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <goals>
                    <goal>list</goal>
                </goals>
                <versionRange>[0.0,)</versionRange>
            </pluginExecutionFilter>
            <action>
                <ignore />
            </action>
        </pluginExecution>

        <pluginExecution>
            <pluginExecutionFilter>
                <groupId>org.zeroturnaround</groupId>
                <artifactId>jrebel-maven-plugin</artifactId>
                <goals>
                    <goal>generate</goal>
                </goals>
                <versionRange>[0.0,)</versionRange>
            </pluginExecutionFilter>
            <action>
                <ignore />
            </action>
        </pluginExecution>

        <pluginExecution>
            <pluginExecutionFilter>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>gwt-maven-plugin</artifactId>
                <goals>
                    <goal>compile</goal>
                </goals>
                <versionRange>[0.0,)</versionRange>
            </pluginExecutionFilter>
            <action>
                <ignore />
            </action>
        </pluginExecution>

        <pluginExecution>
            <pluginExecutionFilter>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <goals>
                    <goal>copy-dependencies</goal>
                    <goal>unpack</goal>
                </goals>
                <versionRange>[0.0,)</versionRange>
            </pluginExecutionFilter>
            <action>
                <ignore />
            </action>
        </pluginExecution>

        <pluginExecution>
            <pluginExecutionFilter>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <versionRange>[1.7,)</versionRange>
                <goals>
                    <goal>run</goal>
                </goals>
            </pluginExecutionFilter>
            <action>
                <ignore />
            </action>
        </pluginExecution>


        <pluginExecution>
            <pluginExecutionFilter>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
                <versionRange>[2.8,)</versionRange>
                <goals>
                    <goal>check</goal>
                </goals>
            </pluginExecutionFilter>
            <action>
                <ignore />
            </action>
        </pluginExecution>

    </pluginExecutions>
</lifecycleMappingMetadata>

Returning JSON response from Servlet to Javascript/JSP page

Got it working! I should have been building a JSONArray of JSONObjects and then add the array to a final "Addresses" JSONObject. Observe the following:

JSONObject json      = new JSONObject();
JSONArray  addresses = new JSONArray();
JSONObject address;
try
{
   int count = 15;

   for (int i=0 ; i<count ; i++)
   {
       address = new JSONObject();
       address.put("CustomerName"     , "Decepticons" + i);
       address.put("AccountId"        , "1999" + i);
       address.put("SiteId"           , "1888" + i);
       address.put("Number"            , "7" + i);
       address.put("Building"          , "StarScream Skyscraper" + i);
       address.put("Street"            , "Devestator Avenue" + i);
       address.put("City"              , "Megatron City" + i);
       address.put("ZipCode"          , "ZZ00 XX1" + i);
       address.put("Country"           , "CyberTron" + i);
       addresses.add(address);
   }
   json.put("Addresses", addresses);
}
catch (JSONException jse)
{ 

}
response.setContentType("application/json");
response.getWriter().write(json.toString());

This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel

Spring MVC UTF-8 Encoding

right-click to your controller.java then properties and check if your text file is encoded with utf-8, if not this is your mistake.

Filtering DataGridView without changing datasource

A simpler way is to transverse the data, and hide the lines with the Visible property.

// Prevent exception when hiding rows out of view
CurrencyManager currencyManager = (CurrencyManager)BindingContext[dataGridView3.DataSource];
currencyManager.SuspendBinding();

// Show all lines
for (int u = 0; u < dataGridView3.RowCount; u++)
{
    dataGridView3.Rows[u].Visible = true;
    x++;
}

// Hide the ones that you want with the filter you want.
for (int u = 0; u < dataGridView3.RowCount; u++)
{
    if (dataGridView3.Rows[u].Cells[4].Value == "The filter string")
    {
        dataGridView3.Rows[u].Visible = true;
    }
    else
    {
        dataGridView3.Rows[u].Visible = false;
    }
}

// Resume data grid view binding
currencyManager.ResumeBinding();

Just an idea... it works for me.

Google Gson - deserialize list<class> object? (generic type)

Method to deserialize generic collection:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

...

Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType();
List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);

Since several people in the comments have mentioned it, here's an explanation of how the TypeToken class is being used. The construction new TypeToken<...>() {}.getType() captures a compile-time type (between the < and >) into a runtime java.lang.reflect.Type object. Unlike a Class object, which can only represent a raw (erased) type, the Type object can represent any type in the Java language, including a parameterized instantiation of a generic type.

The TypeToken class itself does not have a public constructor, because you're not supposed to construct it directly. Instead, you always construct an anonymous subclass (hence the {}, which is a necessary part of this expression).

Due to type erasure, the TypeToken class is only able to capture types that are fully known at compile time. (That is, you can't do new TypeToken<List<T>>() {}.getType() for a type parameter T.)

For more information, see the documentation for the TypeToken class.

JSON parsing using Gson for Java

You can use a separate class to represent the JSON object and use @SerializedName annotations to specify the field name to grab for each data member:

public class Response {

   @SerializedName("data")
   private Data data;

   private static class Data {
      @SerializedName("translations")
      public Translation[] translations;
   }

   private static class Translation {
      @SerializedName("translatedText")
      public String translatedText;
   }

   public String getTranslatedText() {
      return data.translations[0].translatedText;
   }
}

Then you can do the parsing in your parse() method using a Gson object:

Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Response.class);

System.out.println("Translated text: " + response.getTranslatedText());

With this approach, you can reuse the Response class to add any other additional fields to pick up other data members you might want to extract from JSON -- in case you want to make changes to get results for, say, multiple translations in one call, or to get an additional string for the detected source language.

How to convert a String to JsonObject using gson library

You don't need to use JsonObject. You should be using Gson to convert to/from JSON strings and your own Java objects.

See the Gson User Guide:

(Serialization)

Gson gson = new Gson();
gson.toJson(1);                   // prints 1
gson.toJson("abcd");              // prints "abcd"
gson.toJson(new Long(10));        // prints 10
int[] values = { 1 };
gson.toJson(values);              // prints [1]

(Deserialization)

int one = gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false = gson.fromJson("false", Boolean.class);
String str = gson.fromJson("\"abc\"", String.class);
String anotherStr = gson.fromJson("[\"abc\"]", String.class)

JSON and escaping characters

This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.

So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader instance. Any time you are creating a Reader from an InputStream, you need to specify the character encoding, or java.nio.charset.Charset instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8). If you don't specify a Charset, Java will use your platform default encoding, which on Windows is usually CP-1252.

Gson: How to exclude specific fields from Serialization without annotations

I came up with a class factory to support this functionality. Pass in any combination of either fields or classes you want to exclude.

public class GsonFactory {

    public static Gson build(final List<String> fieldExclusions, final List<Class<?>> classExclusions) {
        GsonBuilder b = new GsonBuilder();
        b.addSerializationExclusionStrategy(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                return fieldExclusions == null ? false : fieldExclusions.contains(f.getName());
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return classExclusions == null ? false : classExclusions.contains(clazz);
            }
        });
        return b.create();

    }
}

To use, create two lists (each is optional), and create your GSON object:

static {
 List<String> fieldExclusions = new ArrayList<String>();
 fieldExclusions.add("id");
 fieldExclusions.add("provider");
 fieldExclusions.add("products");

 List<Class<?>> classExclusions = new ArrayList<Class<?>>();
 classExclusions.add(Product.class);
 GSON = GsonFactory.build(null, classExclusions);
}

private static final Gson GSON;

public String getSomeJson(){
    List<Provider> list = getEntitiesFromDatabase();
    return GSON.toJson(list);
}

Maven Could not resolve dependencies, artifacts could not be resolved

Turns out that it happened because of the firewall on my computer. Turning it off worked for me.

Does Spring @Transactional attribute work on a private method?

If you need to wrap a private method inside a transaction and don't want to use aspectj, you can use TransactionTemplate.

@Service
public class MyService {

    @Autowired
    private TransactionTemplate transactionTemplate;

    private void process(){
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                processInTransaction();
            }
        });

    }

    private void processInTransaction(){
        //...
    }

}

Spring @ContextConfiguration how to put the right location for the xml

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"/Beans.xml"}) public class DemoTest{}

How to deserialize a list using GSON or another JSON library in Java?

Be careful using the answer provide by @DevNG. Arrays.asList() returns internal implementation of ArrayList that doesn't implement some useful methods like add(), delete(), etc. If you call them an UnsupportedOperationException will be thrown. In order to get real ArrayList instance you need to write something like this:

List<Video> = new ArrayList<>(Arrays.asList(videoArray));

Gson: Directly convert String to JsonObject (no POJO)

I believe this is a more easy approach:

public class HibernateProxyTypeAdapter implements JsonSerializer<HibernateProxy>{

    public JsonElement serialize(HibernateProxy object_,
        Type type_,
        JsonSerializationContext context_) {
        return new GsonBuilder().create().toJsonTree(initializeAndUnproxy(object_)).getAsJsonObject();
        // that will convert enum object to its ordinal value and convert it to json element

    }

    public static <T> T initializeAndUnproxy(T entity) {
        if (entity == null) {
            throw new 
               NullPointerException("Entity passed for initialization is null");
        }

        Hibernate.initialize(entity);
        if (entity instanceof HibernateProxy) {
            entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
                    .getImplementation();
        }
        return entity;
    }
}

And then you will be able to call it like this:

Gson gson = new GsonBuilder()
        .registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxyTypeAdapter())
        .create();

This way all the hibernate objects will be converted automatically.

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

Adding the @ElementCollection to the List field solved this issue:

    @Column
    @ElementCollection(targetClass=Integer.class)
    private List<Integer> countries;

Gson and deserializing an array of objects with arrays in it

The example Java data structure in the original question does not match the description of the JSON structure in the comment.

The JSON is described as

"an array of {object with an array of {object}}".

In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is

"an array of {TypeDTO object with an array of {ItemDTO object}}".

But the Java data structure provided in the question is not this. Instead it's

"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".

A two-dimensional array != a single-dimensional array.

This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      {"id":2,"name":"name2","valid":true},
      {"id":3,"name":"name3","valid":false},
      {"id":4,"name":"name4","valid":true}
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      {"id":6,"name":"name6","valid":true},
      {"id":7,"name":"name7","valid":false}
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      {"id":9,"name":"name9","valid":true},
      {"id":10,"name":"name10","valid":false},
      {"id":11,"name":"name11","valid":false},
      {"id":12,"name":"name12","valid":true}
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items;
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      [
        {"id":2,"name":"name2","valid":true},
        {"id":3,"name":"name3","valid":false}
      ],
      [
        {"id":4,"name":"name4","valid":true}
      ]
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      [
        {"id":6,"name":"name6","valid":true}
      ],
      [
        {"id":7,"name":"name7","valid":false}
      ]
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      [
        {"id":9,"name":"name9","valid":true},
        {"id":10,"name":"name10","valid":false}
      ],
      [
        {"id":11,"name":"name11","valid":false},
        {"id":12,"name":"name12","valid":true}
      ]
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items[];
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

Regarding the remaining two questions:

is Gson extremely fast?

Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.

That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.

Or am I better to stick with what I've got working already?

I wouldn't. I would most always rather have one simple line of code like

TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);

...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.

Mobile Redirect using htaccess

I modified Tim Stone's solution even further. This allows the cookie to be in 2 states, 1 for mobile and 0 for full. When the mobile cookie is set to 0 even a mobile browser will go to the full site.

Here is the code:

<IfModule mod_rewrite.c>
    RewriteBase /
    RewriteEngine On

    # Check if mobile=1 is set and set cookie 'mobile' equal to 1
    RewriteCond %{QUERY_STRING} (^|&)mobile=1(&|$)
    RewriteRule ^ - [CO=mobile:1:%{HTTP_HOST}]

    # Check if mobile=0 is set and set cookie 'mobile' equal to 0
    RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
    RewriteRule ^ - [CO=mobile:0:%{HTTP_HOST}]

    # cookie can't be set and read in the same request so check
    RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
    RewriteRule ^ - [S=1]

    # Check if this looks like a mobile device
    RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
    RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
    RewriteCond %{HTTP:Profile}       !^$

    # Check if we're not already on the mobile site
    RewriteCond %{HTTP_HOST}          !^m\.
    # Check to make sure we haven't set the cookie before
    RewriteCond %{HTTP:Cookie}        !\mobile=0(;|$)
    # Now redirect to the mobile site
    RewriteRule ^ http://m.example.com%{REQUEST_URI} [R,L]
</IfModule>

Logging framework incompatibility

Just to help those in a similar situation to myself...

This can be caused when a dependent library has accidentally bundled an old version of slf4j. In my case, it was tika-0.8. See https://issues.apache.org/jira/browse/TIKA-556

The workaround is exclude the component and then manually depends on the correct, or patched version.

EG.

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>0.8</version>
    <exclusions>
        <exclusion>
            <!-- NOTE: Version 4.2 has bundled slf4j -->
            <groupId>edu.ucar</groupId>
            <artifactId>netcdf</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <!-- Patched version 4.2-min does not bundle slf4j -->
    <groupId>edu.ucar</groupId>
    <artifactId>netcdf</artifactId>
    <version>4.2-min</version>
</dependency>

Example of SOAP request authenticated with WS-UsernameToken

The core thing is to define prefixes for namespaces and use them to fortify each and every tag - you are mixing 3 namespaces and that just doesn't fly by trying to hack defaults. It's also good to use exactly the prefixes used in the standard doc - just in case that the other side get a little sloppy.

Last but not least, it's much better to use default types for fields whenever you can - so for password you have to list the type, for the Nonce it's already Base64.

Make sure that you check that the generated token is correct before you send it via XML and don't forget that the content of wsse:Password is Base64( SHA-1 (nonce + created + password) ) and date-time in wsu:Created can easily mess you up. So once you fix prefixes and namespaces and verify that yout SHA-1 work fine without XML (just imagine you are validating the request and do the server side of SHA-1 calculation) you can also do a truial wihtout Created and even without Nonce. Oh and Nonce can have different encodings so if you really want to force another encoding you'll have to look further into wsu namespace.

<S11:Envelope xmlns:S11="..." xmlns:wsse="..." xmlns:wsu= "...">
  <S11:Header>
  ...
    <wsse:Security>
      <wsse:UsernameToken>
        <wsse:Username>NNK</wsse:Username>
        <wsse:Password Type="...#PasswordDigest">weYI3nXd8LjMNVksCKFV8t3rgHh3Rw==</wsse:Password>
        <wsse:Nonce>WScqanjCEAC4mQoBE07sAQ==</wsse:Nonce>
        <wsu:Created>2003-07-16T01:24:32</wsu:Created>
      </wsse:UsernameToken>
    </wsse:Security>
  ...
  </S11:Header>
...
</S11:Envelope>

Infinite Recursion with Jackson JSON and Hibernate JPA issue

@JsonIgnoreProperties is the answer.

Use something like this ::

@OneToMany(mappedBy = "course",fetch=FetchType.EAGER)
@JsonIgnoreProperties("course")
private Set<Student> students;

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes

Using prepared statements with JDBCTemplate

Try the following:

PreparedStatementCreator creator = new PreparedStatementCreator() {
    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        PreparedStatement updateSales = con.prepareStatement(
        "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
        updateSales.setInt(1, 75); 
        updateSales.setString(2, "Colombian"); 
        return updateSales;
    }
};

How can I convert JSON to a HashMap using Gson?

This code works:

Gson gson = new Gson(); 
String json = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
Map<String,Object> map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(json, map.getClass());

Iterating through a JSON object

I believe you probably meant:

from __future__ import print_function

for song in json_object:
    # now song is a dictionary
    for attribute, value in song.items():
        print(attribute, value) # example usage

NB: You could use song.iteritems instead of song.items if in Python 2.

How can I give eclipse more memory than 512M?

You can copy this to your eclipse.ini file to have 1024M:

-clean -showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vmargs
-Xms512m
-Xmx1024m
-XX:PermSize=128m
-XX:MaxPermSize=256m 

Is there a way to specify a default property value in Spring XML?

http://thiamteck.blogspot.com/2008/04/spring-propertyplaceholderconfigurer.html points out that "local properties" defined on the bean itself will be considered defaults to be overridden by values read from files:

<bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  <property name="location"><value>my_config.properties</value></property>  
  <property name="properties">  
    <props>  
      <prop key="entry.1">123</prop>  
    </props>  
  </property>  
</bean> 

Injecting Mockito mocks into a Spring bean

Posting a few examples based on the above approaches

With Spring:

@ContextConfiguration(locations = { "classpath:context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class TestServiceTest {
    @InjectMocks
    private TestService testService;
    @Mock
    private TestService2 testService2;
}

Without Spring:

@RunWith(MockitoJUnitRunner.class)
public class TestServiceTest {
    @InjectMocks
    private TestService testService = new TestServiceImpl();
    @Mock
    private TestService2 testService2;
}

Jackson Vs. Gson

It seems that GSon don't support JAXB. By using JAXB annotated class to create or process the JSON message, I can share the same class to create the Restful Web Service interface by using spring MVC.

Converting JSON data to Java object

Bewaaaaare of Gson! It's very cool, very great, but the second you want to do anything other than simple objects, you could easily need to start building your own serializers (which isn't that hard).

Also, if you have an array of Objects, and you deserialize some json into that array of Objects, the true types are LOST! The full objects won't even be copied! Use XStream.. Which, if using the jsondriver and setting the proper settings, will encode ugly types into the actual json, so that you don't loose anything. A small price to pay (ugly json) for true serialization.

Note that Jackson fixes these issues, and is faster than GSON.

How to bind list to dataGridView?

may be little late but useful for future. if you don't require to set custom properties of cell and only concern with header text and cell value then this code will help you

public class FileName
{        
     [DisplayName("File Name")] 
     public string FileName {get;set;}
     [DisplayName("Value")] 
     public string Value {get;set;}
}

and then you can bind List as datasource as

private void BindGrid()
{
    var filelist = GetFileListOnWebServer().ToList();    
    gvFilesOnServer.DataSource = filelist.ToArray();
}

for further information you can visit this page Bind List of Class objects as Datasource to DataGridView

hope this will help you.

Spring - @Transactional - What happens in background?

The simplest answer is:

On whichever method you declare @Transactional the boundary of transaction starts and boundary ends when method completes.

If you are using JPA call then all commits are with in this transaction boundary.

Lets say you are saving entity1, entity2 and entity3. Now while saving entity3 an exception occur, then as enitiy1 and entity2 comes in same transaction so entity1 and entity2 will be rollback with entity3.

Transaction :

  1. entity1.save
  2. entity2.save
  3. entity3.save

Any exception will result in rollback of all JPA transactions with DB.Internally JPA transaction are used by Spring.

How to bind a List to a ComboBox?

For a backgrounder, there are 2 ways to use a ComboBox/ListBox

1) Add Country Objects to the Items property and retrieve a Country as Selecteditem. To use this you should override the ToString of Country.

2) Use DataBinding, set the DataSource to a IList (List<>) and use DisplayMember, ValueMember and SelectedValue

For 2) you will need a list of countries first

// not tested, schematic:
List<Country> countries = ...;
...; // fill 

comboBox1.DataSource = countries;
comboBox1.DisplayMember="Name";
comboBox1.ValueMember="Cities";

And then in the SelectionChanged,

if (comboBox1.Selecteditem != null)
{
   comboBox2.DataSource=comboBox1.SelectedValue;

}

Options for HTML scraping?

The Ruby world's equivalent to Beautiful Soup is why_the_lucky_stiff's Hpricot.

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

If you have SELINUX enabled, it will prevent this file being created. You need to turn it off.

  1. vi /etc/selinux/config
  2. set SELINUX=disabled
  3. reboot

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

VM arguments worked for me in eclipse. If you are using eclipse version 3.4, do the following

go to Run --> Run Configurations --> then select the project under maven build --> then select the tab "JRE" --> then enter -Xmx1024m.

Alternatively you could do Run --> Run Configurations --> select the "JRE" tab --> then enter -Xmx1024m

This should increase the memory heap for all the builds/projects. The above memory size is 1 GB. You can optimize the way you want.

TypeScript and array reduce function

Just a note in addition to the other answers.

If an initial value is supplied to reduce then sometimes its type must be specified, viz:-

a.reduce(fn, [])

may have to be

a.reduce<string[]>(fn, [])

or

a.reduce(fn, <string[]>[])

Mythical man month 10 lines per developer day - how close on large projects?

I think this comes from from the waterfall development days, where the actual development phase of a project could be as little as 20-30% of the total project time. Take the total lines of code and divide by the entire project time and you'll get around 10 lines/day. Divide by just the coding period, and you'll get closer to what people are quoting.

Where is Java's Array indexOf?

There are a couple of ways to accomplish this using the Arrays utility class.

If the array is not sorted and is not an array of primitives:

java.util.Arrays.asList(theArray).indexOf(o)

If the array is primitives and not sorted, one should use a solution offered by one of the other answers such as Kerem Baydogan's, Andrew McKinlay's or Mishax's. The above code will compile even if theArray is primitive (possibly emitting a warning) but you'll get totally incorrect results nonetheless.

If the array is sorted, you can make use of a binary search for performance:

java.util.Arrays.binarySearch(theArray, o)

How to succinctly write a formula with many variables from a data frame?

Yes of course, just add the response y as first column in the dataframe and call lm() on it:

d2<-data.frame(y,d)
> d2
  y x1 x2 x3
1 1  4  3  4
2 4 -1  9 -4
3 6  3  8 -2
> lm(d2)

Call:
lm(formula = d2)

Coefficients:
(Intercept)           x1           x2           x3  
    -5.6316       0.7895       1.1579           NA  

Also, my information about R points out that assignment with <- is recommended over =.

How do I right align div elements?

Simple answer is here:

<div style="text-align: right;">
    anything:
    <select id="locality-dropdown" name="locality" class="cls" style="width: 200px; height: 28px; overflow:auto;">
    </select>
</div>

Run php function on button click

You are trying to call a javascript function. If you want to call a PHP function, you have to use for example a form:

    <form action="action_page.php">
       First name:<br>
       <input type="text" name="firstname" value="Mickey">
       <br>
       Last name:<br>
       <input type="text" name="lastname" value="Mouse">
       <br><br>
       <input type="submit" value="Submit">
     </form> 

(Original Code from: http://www.w3schools.com/html/html_forms.asp)

So if you want do do a asynchron call, you could use 'Ajax' - and yeah, that's the Javascript-Way. But I think, that my code example is enough for this time :)

Can I remove the URL from my print css, so the web address doesn't print?

@media print 
{
  a[href]:after { content: none !important; }
  img[src]:after { content: none !important; }
}

What are best practices for REST nested resources?

I've tried both design strategies - nested and non-nested endpoints. I've found that:

  1. if the nested resource has a primary key and you don't have its parent primary key, the nested structure requires you to get it, even though the system doesn't actually require it.

  2. nested endpoints typically require redundant endpoints. In other words, you will more often than not, need the additional /employees endpoint so you can get a list of employees across departments. If you have /employees, what exactly does /companies/departments/employees buy you?

  3. nesting endpoints don't evolve as nicely. E.g. you might not need to search for employees now but you might later and if you have a nested structure, you have no choice but to add another endpoint. With a non-nested design, you just add more parameters, which is simpler.

  4. sometimes a resource could have multiple types of parents. Resulting in multiple endpoints all returning the same resource.

  5. redundant endpoints makes the docs harder to write and also makes the api harder to learn.

In short, the non-nested design seems to allow a more flexible and simpler endpoint schema.

How do you read scanf until EOF in C?

Try:

while(scanf("%15s", words) != EOF)

You need to compare scanf output with EOF

Since you are specifying a width of 15 in the format string, you'll read at most 15 char. So the words char array should be of size 16 ( 15 +1 for null char). So declare it as:

char words[16];

HTTP redirect: 301 (permanent) vs. 302 (temporary)

301 redirects are cached indefinitely (at least by some browsers).

This means, if you set up a 301, visit that page, you not only get redirected, but that redirection gets cached.

When you visit that page again, your Browser* doesn't even bother to request that URL, it just goes to the cached redirection target.

The only way to undo a 301 for a visitor with that redirection in Cache, is re-redirecting back to the original URL**. In that case, the Browser will notice the loop, and finally really request the entered URL.

Obviously, that's not an option if you decided to 301 to facebook or any other resource you're not fully under control.

Unfortunately, many Hosting Providers offer a feature in their Admin Interface simply called "Redirection", which does a 301 redirect. If you're using this to temporarily redirect your domain to facebook as a coming soon page, you're basically screwed.

*at least Chrome and Firefox, according to How long do browsers cache HTTP 301s?. Just tried it with Chrome 45. Edit: Safari 7.0.6 on Mac also caches, a browser restart didn't help (Link says that on Safari 5 on Windows it does help.)

**I tried javascript window.location = '', because it would be the solution which could be applied in most cases - it doesn't work. It results in an undetected infinite Loop. However, php header('Location: new.url') does break the loop

Bottom Line: only use 301s if you're absolutely sure you're never going to use that URL again. Usually never on the root dir (example.com/)

Getting CheckBoxList Item values

This will do the trick for you:

foreach (int indexChecked in checkedListBox1.CheckedIndices)
{
    string itemtxt = checkedListBox11.Items[indexChecked];
}

It will return whatever string value is in the checkedlistbox items.

Lists: Count vs Count()

myList.Count is a method on the list object, it just returns the value of a field so is very fast. As it is a small method it is very likely to be inlined by the compiler (or runtime), they may then allow other optimization to be done by the compiler.

myList.Count() is calling an extension method (introduced by LINQ) that loops over all the items in an IEnumerable, so should be a lot slower.

However (In the Microsoft implementation) the Count extension method has a “special case” for Lists that allows it to use the list’s Count property, this means the Count() method is only a little slower than the Count property.

It is unlikely you will be able to tell the difference in speed in most applications.

So if you know you are dealing with a List use the Count property, otherwise if you have a "unknown" IEnumerabl, use the Count() method and let it optimise for you.

How to see full query from SHOW PROCESSLIST

If one want to keep getting updated processes (on the example, 2 seconds) on a shell session without having to manually interact with it use:

watch -n 2 'mysql -h 127.0.0.1 -P 3306 -u some_user -psome_pass some_database -e "show full processlist;"'

The only bad thing about the show [full] processlist is that you can't filter the output result. On the other hand, issuing the SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST open possibilities to remove from the output anything you don't want to see:

SELECT * from INFORMATION_SCHEMA.PROCESSLIST
WHERE DB = 'somedatabase'
AND COMMAND <> 'Sleep'
AND HOST NOT LIKE '10.164.25.133%' \G

How to add text at the end of each line in Vim?

The substitute command can be applied to a visual selection. Make a visual block over the lines that you want to change, and type :, and notice that the command-line is initialized like this: :'<,'>. This means that the substitute command will operate on the visual selection, like so:

:'<,'>s/$/,/

And this is a substitution that should work for your example, assuming that you really want the comma at the end of each line as you've mentioned. If there are trailing spaces, then you may need to adjust the command accordingly:

:'<,'>s/\s*$/,/

This will replace any amount of whitespace preceding the end of the line with a comma, effectively removing trailing whitespace.

The same commands can operate on a range of lines, e.g. for the next 5 lines: :,+5s/$/,/, or for the entire buffer: :%s/$/,/.

laravel select where and where condition

After rigorous testing, I found out that the source of my problem is Hash::make('password'). Apparently this kept generating a different hash each time. SO I replaced this with my own hashing function (wrote previously in codeigniter) and viola! things worked well.

Thanks again for helping out :) Really appreciate it!

How to specify multiple conditions in an if statement in javascript

function go(type, pageCount) {
    if ((type == 2 && pageCount == 0) || (type == 2 && pageCount == '')) {
        pageCount = document.getElementById('<%=hfPageCount.ClientID %>').value;
    }
}

Standardize data columns in R

Again, even though this is an old question, it is very relevant! And I have found a simple way to normalise certain columns without the need of any packages:

normFunc <- function(x){(x-mean(x, na.rm = T))/sd(x, na.rm = T)}

For example

x<-rnorm(10,14,2)
y<-rnorm(10,7,3)
z<-rnorm(10,18,5)
df<-data.frame(x,y,z)

df[2:3] <- apply(df[2:3], 2, normFunc)

You will see that the y and z columns have been normalised. No packages needed :-)

How do I get logs/details of ansible-playbook module executions?

Using callback plugins, you can have the stdout of your commands output in readable form with the play: gist: human_log.py

Edit for example output:

 _____________________________________
< TASK: common | install apt packages >
 -------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||


changed: [10.76.71.167] => (item=htop,vim-tiny,curl,git,unzip,update-motd,ssh-askpass,gcc,python-dev,libxml2,libxml2-dev,libxslt-dev,python-lxml,python-pip)

stdout:
Reading package lists...
Building dependency tree...
Reading state information...
libxslt1-dev is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 24 not upgraded.


stderr:

start:
2015-03-27 17:12:22.132237

end:
2015-03-27 17:12:22.136859

How to break a while loop from an if condition inside the while loop?

The break keyword does exactly that. Here is a contrived example:

public static void main(String[] args) {
  int i = 0;
  while (i++ < 10) {
    if (i == 5) break;
  }
  System.out.println(i); //prints 5
}

If you were actually using nested loops, you would be able to use labels.

Opening the Settings app from another app

You can use the below code for it.

[[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

I got this from using the Anaconda default environment instead of my custom one with pandas installed.

Changing to the right environment and reopening the Jupyter notebooks did not fix this for me (python 3.7, pandas 0.23.0). Restarting Anaconda did.

How do I get hour and minutes from NSDate?

With iOS 8, Apple introduced a helper method to retrieve the hour, minute, second and nanosecond from an NSDate object.

Objective-C

NSDate *date = [NSDate currentDate];
NSInteger hour = 0;
NSInteger minute = 0;
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
[currentCalendar getHour:&hour minute:&minute second:NULL nanosecond:NULL fromDate:date];
NSLog(@"the hour is %ld and minute is %ld", (long)hour, (long)minute);

Swift

let date = NSDate()
var hour = 0
var minute = 0
let calendar = NSCalendar.currentCalendar()
if #available(iOS 8.0, *) {
    calendar.getHour(&hour, minute: &minute, second: nil, nanosecond: nil, fromDate: date)
    print("the hour is \(hour) and minute is \(minute)")
}

SQL Server after update trigger

you can call INSERTED, SQL Server uses these tables to capture the data of the modified row before and after the event occurs.I assume in your table the name of the key is Id

I think the following code can help you

CREATE TRIGGER [dbo].[after_update]
ON [dbo].[MYTABLE]
   AFTER UPDATE
AS
BEGIN
    UPDATE dbo.[MYTABLE]
    SET    dbo.[MYTABLE].CHANGED_ON = GETDATE(),
           dbo.[MYTABLE].CHANGED_BY = USER_NAME(USER_ID())
    FROM   INSERTED
    WHERE  INSERTED.Id = dbo.[MYTABLE].[Id]
END

How do I Validate the File Type of a File Upload?

As some people have mentioned, Javascript is the way to go. Bear in mind that the "validation" here is only by file extension, it won't validate that the file is a real excel spreadsheet!

Formatting "yesterday's" date in python

This should do what you want:

import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

You don't need Xvfb

It is failing to start due to a mismatch between the chrome version and the chromedriver version. Downloading and installing the same versions or latest versions would solve the issue.

Facebook Callback appends '#_=_' to Return URL

You can also specify your own hash on the redirect_uri parameter for the Facebook callback, which might be helpful in certain circumstances e.g. /api/account/callback#home. When you are redirected back, it'll at least be a hash that corresponds to a known route if you are using backbone.js or similar (not sure about jquery mobile).

Excel Formula to SUMIF date falls in particular month

=Sumifs(B:B,A:A,">=1/1/2013",A:A,"<=1/31/2013")

The beauty of this formula is you can add more data to columns A and B and it will just recalculate.

Querying Windows Active Directory server using ldapsearch from command line

You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify

Maven dependency for Servlet 3.0 API?

I found an example POM for the Servlet 3.0 API on DZone from September.

Suggest you use the java.net repo, at http://download.java.net/maven/2/

There are Java EE APIs in there, for example http://download.java.net/maven/2/javax/javaee-web-api/6.0/ with POM that look like they might be what you're after, for example:

<dependency>
  <groupId>javax</groupId>
  <artifactId>javaee-web-api</artifactId>
  <version>6.0</version>
</dependency>

I'm guessing that the version conventions for the APIs have been changed to match the version of the overall EE spec (i.e. Java EE 6 vs. Servlets 3.0) as part of the new 'profiles'. Looking in the JAR, looks like all the 3.0 servlet stuff is in there. Enjoy!

LoDash: Get an array of values from an array of object properties

In the new lodash release v4.0.0 _.pluck has removed in favor of _.map

Then you can use this:

_.map(users, 'id'); // [12, 14, 16, 18]

You can see in Github Changelog

Delete specific line from a text file?

Are you on a Unix operating system?

You can do this with the "sed" stream editor. Read the man page for "sed"

Controlling Maven final name of jar artifact

I am using the following

        ....
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <finalName>${project.groupId}/${project.artifactId}-${baseVersion}.${monthlyVersion}.${instanceVersion}</finalName>
            </configuration>
        </plugin>
        ....

This way you can define each value individually or pragmatically from Jenkins of some other system.

mvn package -DbaseVersion=1 -monthlyVersion=2 -instanceVersion=3

This will place a folder target\{group.id}\projectName-1.2.3.jar

A better way to save time might be

        ....
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <finalName>${project.groupId}/${project.artifactId}-${baseVersion}</finalName>
            </configuration>
        </plugin>
        ....

Like the same except I use on variable.

  mvn package -DbaseVersion=0.3.4

This will place a folder target\{group.id}\projectName-1.2.3.jar

you can also use outputDirectory inside of configuration to specify a location you may want the package to be located.

How do you dynamically add elements to a ListView on Android?

First, you have to add a ListView, an EditText and a button into your activity_main.xml.

Now, in your ActivityMain:

private EditText editTxt;
private Button btn;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;

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

    editTxt = (EditText) findViewById(R.id.editText);
    btn = (Button) findViewById(R.id.button);
    list = (ListView) findViewById(R.id.listView);
    arrayList = new ArrayList<String>();

    // Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
    // and the array that contains the data
    adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);

    // Here, you set the data in your ListView
    list.setAdapter(adapter);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // this line adds the data of your EditText and puts in your array
            arrayList.add(editTxt.getText().toString());
            // next thing you have to do is check if your adapter has changed
            adapter.notifyDataSetChanged();
        }
    });
}

This works for me, I hope I helped you

How to grep, excluding some patterns?

Just use awk, it's much simpler than grep in letting you clearly express compound conditions.

If you want to skip lines that contains both loom and gloom:

awk '/loom/ && !/gloom/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)

or if you want to print them:

awk '/(^|[^g])loom/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)

and if the reality is you just want lines where loom appears as a word by itself:

awk '/\<loom\>/{ print FILENAME, FNR, $0 }' ~/projects/**/trunk/src/**/*.@(h|cpp)

Best place to insert the Google Analytics code

As google says:

Paste it into your web page, just before the closing </head> tag.

One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the <head> section, and we recommend placing the snippet at the bottom of the <head> section for best performance

how can the textbox width be reduced?

Is not nice to define textbox width without using CSS, be warned ;-)

<input type="text" name="d" value="4" size="4" />

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

The reason for the exception is the re-creation of the FragmentActivity during the runtime of the AsyncTask and the access to the previous, destroyed FragmentActivity in onPostExecute() afterwards.

The problem is to get a valid reference to the new FragmentActivity. There is no method for this neither getActivity() nor findById() or something similar. This forum is full of threads according this issue (e.g. search for "Activity context in onPostExecute"). Some of them are describing workarounds (until now I didn't find a good one).

Maybe it would be a better solution to use a Service for my purpose.

Regex replace (in Python) - a simpler way?

>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a callable, it's passed the match object and must return
    a replacement string to be used.

:last-child not working as expected?

The last-child selector is used to select the last child element of a parent. It cannot be used to select the last child element with a specific class under a given parent element.

The other part of the compound selector (which is attached before the :last-child) specifies extra conditions which the last child element must satisfy in-order for it to be selected. In the below snippet, you would see how the selected elements differ depending on the rest of the compound selector.

_x000D_
_x000D_
.parent :last-child{ /* this will select all elements which are last child of .parent */_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.parent div:last-child{ /* this will select the last child of .parent only if it is a div*/_x000D_
  background: crimson;_x000D_
}_x000D_
_x000D_
.parent div.child-2:last-child{ /* this will select the last child of .parent only if it is a div and has the class child-2*/_x000D_
  color: beige;_x000D_
}
_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child-2'>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <p>Child w/o class</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


To answer your question, the below would style the last child li element with background color as red.

li:last-child{
    background-color: red;
}

But the following selector would not work for your markup because the last-child does not have the class='complete' even though it is an li.

li.complete:last-child{
    background-color: green;
}

It would have worked if (and only if) the last li in your markup also had class='complete'.


To address your query in the comments:

@Harry I find it rather odd that: .complete:last-of-type does not work, yet .complete:first-of-type does work, regardless of it's position it's parents element. Thanks for your help.

The selector .complete:first-of-type works in the fiddle because it (that is, the element with class='complete') is still the first element of type li within the parent. Try to add <li>0</li> as the first element under the ul and you will find that first-of-type also flops. This is because the first-of-type and last-of-type selectors select the first/last element of each type under the parent.

Refer to the answer posted by BoltClock, in this thread for more details about how the selector works. That is as comprehensive as it gets :)

What does `set -x` do?

-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.

-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.

-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).

Compare the following differences:

/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root

/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root

/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET

How to include layout inside layout?

Edit: As in a comment rightly requested here some more information. Use the include tag

<include
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   layout="@layout/yourlayout" />

to include the layout you want to reuse.

Check this link out...

How to load image to WPF in runtime?

Make sure that your sas.png is marked as Build Action: Content and Copy To Output Directory: Copy Always in its Visual Studio Properties...

I think the C# source code goes like this...

Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;

and XAML should be

<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" 
       Name="image1" Stretch="Fill" VerticalAlignment="Top" 
       Source="../Bilder/sas.png"
       Width="350" />  

EDIT

Dynamically I think XAML would provide best way to load Images ...

<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
       x:Name="MyImage"/>

where image.DataContext is string path.

MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";

public class MyImageSourceConverter : IValueConverter
{
    public object Convert(object value_, Type targetType_, 
    object parameter_, System.Globalization.CultureInfo culture_)
    {
        return (new ImageSourceConverter()).ConvertFromString (value.ToString());
    }

    public object ConvertBack(object value, Type targetType, 
    object parameter, CultureInfo culture)
    {
          throw new NotImplementedException();
    }
}

Now as you set a different data context, Image would be automatically loaded at runtime.

"You have mail" message in terminal, os X

Probably it is some message from your system.

Type in terminal:

man mail

, and see how can you get this message from your system.

What does "connection reset by peer" mean?

This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

This can happen if the other side crashes and then comes back up or if it calls close() on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.

It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.

Get Table and Index storage size in sql server

This query here will list the total size that a table takes up - clustered index, heap and all nonclustered indices:

SELECT 
    s.Name AS SchemaName,
    t.NAME AS TableName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM 
    sys.tables t
INNER JOIN 
    sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.NAME NOT LIKE 'dt%'    -- filter out system tables for diagramming
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows
ORDER BY 
    s.Name, t.Name

If you want to separate table space from index space, you need to use AND i.index_id IN (0,1) for the table space (index_id = 0 is the heap space, index_id = 1 is the size of the clustered index = data pages) and AND i.index_id > 1 for the index-only space

Illegal character in path at index 16

I got this error today and unlike all the above answers my error was due to a new reason.

In my Japanese translation strings.xml file, I had removed a required string.

Some how android mixed up all the other string and this caused an error.

The solution was to include all the strings from my normal, English strings.xml

Including those strings which weren't translated to Japanese.

PHP Get all subdirectories of a given directory

This is the one liner code:

 $sub_directories = array_map('basename', glob($directory_path . '/*', GLOB_ONLYDIR));

How to get a table creation script in MySQL Workbench?

To get an individual table's creation script just right click on the table name and click Copy to Clipboard > Create Statement.

To enable the File > Forward Engineering SQL_CREATE Script.. option and to get the creation script for your entire database :

  1. Database > Reverse Engineer (Ctrl+R)
  2. Go through the steps to create the EER Diagram
  3. When viewing the EER Diagram click File > Forward Engineering SQL_CREATE Script... (Ctrl+Shift+G)

Simple 'if' or logic statement in Python

Here's a Boolean thing:

if (not suffix == "flac" )  or (not suffix == "cue" ):   # WRONG! FAILS
    print  filename + ' is not a flac or cue file'

but

if not (suffix == "flac"  or suffix == "cue" ):     # CORRECT!
       print  filename + ' is not a flac or cue file'

(not a) or (not b) == not ( a and b ) , is false only if a and b are both true

not (a or b) is true only if a and be are both false.

Download multiple files as a zip-file using php

This is a working example of making ZIPs in PHP:

$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name,  ZipArchive::CREATE);
foreach ($files as $file) {
  echo $path = "uploadpdf/".$file;
  if(file_exists($path)){
  $zip->addFromString(basename($path),  file_get_contents($path));  
  }
  else{
   echo"file does not exist";
  }
}
$zip->close();

AngularJS : The correct way of binding to a service properties

Late to the party, but for future Googlers - don't use the provided answer.

JavaScript has a mechanism of passing objects by reference, while it only passes a shallow copy for values "numbers, strings etc".

In above example, instead of binding attributes of a service, why don't we expose the service to the scope?

$scope.hello = HelloService;

This simple approach will make angular able to do two-way binding and all the magical things you need. Don't hack your controller with watchers or unneeded markup.

And if you are worried about your view accidentally overwriting your service attributes, use defineProperty to make it readable, enumerable, configurable, or define getters and setters. You can gain lots of control by making your service more solid.

Final tip: if you spend your time working on your controller more than your services then you are doing it wrong :(.

In that particular demo code you supplied I would recommend you do:

 function TimerCtrl1($scope, Timer) {
   $scope.timer = Timer;
 }
///Inside view
{{ timer.time_updated }}
{{ timer.other_property }}
etc...

Edit:

As I mentioned above, you can control the behaviour of your service attributes using defineProperty

Example:

// Lets expose a property named "propertyWithSetter" on our service
// and hook a setter function that automatically saves new value to db !
Object.defineProperty(self, 'propertyWithSetter', {
  get: function() { return self.data.variable; },
  set: function(newValue) { 
         self.data.variable = newValue; 
         // let's update the database too to reflect changes in data-model !
         self.updateDatabaseWithNewData(data);
       },
  enumerable: true,
  configurable: true
});

Now in our controller if we do

$scope.hello = HelloService;
$scope.hello.propertyWithSetter = 'NEW VALUE';

our service will change the value of propertyWithSetter and also post the new value to database somehow!

Or we can take any approach we want.

Refer to the MDN documentation for defineProperty.

How to increase time in web.config for executing sql query

SQL Server has no setting to control query timeout in the connection string, and as far as I know this is the same for other major databases. But, this doesn't look like the problem you're seeing: I'd expect to see an exception raised

Error: System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

if there genuinely was a timeout executing the query.

If this does turn out to be a problem, you can change the default timeout for a SQL Server database as a property of the database itself; use SQL Server Manager for this.

Be sure that the query is exactly the same from your Web application as the one you're running directly. Use a profiler to verify this.

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

for IIS 7 try according to the given picture ... mark me helpful if it works for you.

enter image description here

Accessing @attribute from SimpleXML

You can get the attributes of an XML element by calling the attributes() function on an XML node. You can then var_dump the return value of the function.

More info at php.net http://php.net/simplexmlelement.attributes

Example code from that page:

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}

How to show soft-keyboard when edittext is focused

It worked for me. You can try with this also to show the keyboard:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

MySQL 'Order By' - sorting alphanumeric correctly

I know this post is closed but I think my way could help some people. So there it is :

My dataset is very similar but is a bit more complex. It has numbers, alphanumeric data :

1
2
Chair 
3
0
4
5
-
Table
10
13
19
Windows
99
102
Dog

I would like to have the '-' symbol at first, then the numbers, then the text.

So I go like this :

SELECT name, (name = '-') boolDash, (name = '0') boolZero, (name+0 > 0) boolNum 
FROM table 
ORDER BY boolDash DESC, boolZero DESC, boolNum DESC, (name+0), name

The result should be something :

-
0    
1
2
3
4
5
10
13
99
102
Chair
Dog
Table
Windows

The whole idea is doing some simple check into the SELECT and sorting with the result.

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

 $ yum -y install comapt-libstdc* libstdc++ libstdc++-devel libbaio-devel glib-devel glibc-headers glib-common kernel-header

$ yum -y install compat-libcap1 gcc gcc-c++ ksh compat-libstdc++-33 libaio-devel 

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

The W3 specification that talks about these seem to suggest that word-break: break-all is for requiring a particular behaviour with CJK (Chinese, Japanese, and Korean) text, whereas word-wrap: break-word is the more general, non-CJK-aware, behaviour.

libclntsh.so.11.1: cannot open shared object file.

For the benefit of anyone else coming here by far the best thing to do is to update cx_Oracle to the latest version (6+). This version does not need LD_LIBRARY_PATH set at all.

How do I read a resource file from a Java jar file?

It looks as if you are using the URL.toString result as the argument to the FileReader constructor. URL.toString is a bit broken, and instead you should generally use url.toURI().toString(). In any case, the string is not a file path.

Instead, you should either:

  • Pass the URL to ServicesLoader and let it call openStream or similar.
  • Use Class.getResourceAsStream and just pass the stream over, possibly inside an InputSource. (Remember to check for nulls as the API is a bit messy.)

pop/remove items out of a python tuple

There is a simple but practical solution.

As DSM said, tuples are immutable, but we know Lists are mutable. So if you change a tuple to a list, it will be mutable. Then you can delete the items by the condition, then after changing the type to a tuple again. That’s it.

Please look at the codes below:

tuplex = list(tuplex)
for x in tuplex:
  if (condition):
     tuplex.pop(tuplex.index(x))
tuplex = tuple(tuplex)
print(tuplex)

For example, the following procedure will delete all even numbers from a given tuple.

tuplex = (1, 2, 3, 4, 5, 6, 7, 8, 9)
tuplex = list(tuplex)
for x in tuplex:
  if (x % 2 == 0):
     tuplex.pop(tuplex.index(x))
tuplex = tuple(tuplex)
print(tuplex)

if you test the type of the last tuplex, you will find it is a tuple.

Finally, if you want to define an index counter as you did (i.e., n), you should initialize it before the loop, not in the loop.

Converting Hexadecimal String to Decimal Integer

//package com.javatutorialhq.tutorial;

import java.util.Scanner;

/* * Java code convert hexadecimal to decimal */ 
public class HexToDecimal {

    public static void main(String[] args) {

        // TODO Auto-generated method stub 

        System.out.print("Hexadecimal Input:");

        // read the hexadecimal input from the console 

        Scanner s = new Scanner(System.in); 

        String inputHex = s.nextLine();

        try{ 

// actual conversion of hex to decimal

            Integer outputDecimal = Integer.parseInt(inputHex, 16);

            System.out.println("Decimal Equivalent : "+outputDecimal);


        }

        catch(NumberFormatException ne){

            // Printing a warning message if the input is not a valid hex number

            System.out.println("Invalid Input"); 

        }

        finally{ s.close();

        }
    } 
}

How to calculate sum of a formula field in crystal Reports?

(Assuming you are looking at the reports in the Crystal Report Designer...)

Your menu options might be a little different depending on the version of Crystal Reports you're using, but you can either:

  • Make a summary field: Right-click on the desired formula field in your detail section and choose "Insert Summary". Choose "sum" from the drop-down box and verify that the correct account grouping is selected, then click OK. You will then have a simple sum field in your group footer section.
  • Make a running total field: Click on the "Insert" menu and choose "Running Total Field..."*** Click on the New button and give your new running total field a name. Choose your formula field under "Field to summarize" and choose "sum" under "Type of Summary". Here you can also change when the total is evaluated and reset, leave these at their default if you're wanting a sum on each record. You can also use a formula to determine when a certain field should be counted in the total. (Evaluate: Use Formula)

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

Convert Date To String

Use name Space

using System.Globalization;

Code

string date = DateTime.ParseExact(datetext.Text, "dd-MM-yyyy", CultureInfo.InstalledUICulture).ToString("yyyy-MM-dd");

How to check if a column exists before adding it to an existing table in PL/SQL?

All the metadata about the columns in Oracle Database is accessible using one of the following views.

user_tab_cols; -- For all tables owned by the user

all_tab_cols ; -- For all tables accessible to the user

dba_tab_cols; -- For all tables in the Database.

So, if you are looking for a column like ADD_TMS in SCOTT.EMP Table and add the column only if it does not exist, the PL/SQL Code would be along these lines..

DECLARE
  v_column_exists number := 0;  
BEGIN
  Select count(*) into v_column_exists
    from user_tab_cols
    where upper(column_name) = 'ADD_TMS'
      and upper(table_name) = 'EMP';
      --and owner = 'SCOTT --*might be required if you are using all/dba views

  if (v_column_exists = 0) then
      execute immediate 'alter table emp add (ADD_TMS date)';
  end if;
end;
/

If you are planning to run this as a script (not part of a procedure), the easiest way would be to include the alter command in the script and see the errors at the end of the script, assuming you have no Begin-End for the script..

If you have file1.sql

alter table t1 add col1 date;
alter table t1 add col2 date;
alter table t1 add col3 date;

And col2 is present,when the script is run, the other two columns would be added to the table and the log would show the error saying "col2" already exists, so you should be ok.

How to create an Explorer-like folder browser control?

Microsoft provides a walkthrough for creating a Windows Explorer style interface in C#.

There are also several examples on Code Project and other sites. Immediate examples are Explorer Tree, My Explorer, File Browser and Advanced File Explorer but there are others. Explorer Tree seems to look the best from the brief glance I took.

I used the search term windows explorer tree view C# in Google to find these links.

How to create a HTML Table from a PHP array?

Array into table. Array into div. JSON into table. JSON into div.

All are nicely handle this class. Click here to get a class

How to use it?

Just get and object

$obj = new Arrayinto();

Create an array you want to convert

$obj->array_object = array("AAA" => "1111",
                  "BBB" => "2222",
                  "CCC" => array("CCC-1" => "123",
                                 "CCC-2" => array("CCC-2222-A" => "CA2",
                                                  "CCC-2222=B" => "CB2"
                                                 )
                                )

                 );

If you want to convert Array into table. Call this.

$result = $obj->process_table();

If you want to convert Array into div. Call this.

$result = $obj->process_div();

Let suppose if you have a JSON

$obj->json_string = '{
            "AAA":"11111",
            "BBB":"22222",
            "CCC":[
                    {
                        "CCC-1":"123"
                    },
                    {
                        "CCC-2":"456"
                    }
                  ] 
         }
        ';

You can convert into table/div like this

$result = $obj->process_json('div');

OR

$result = $obj->process_json('table');

Check OS version in Swift?

Mattt Thompson shares a very handy way

switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) {
case .OrderedSame, .OrderedDescending:
    println("iOS >= 8.0")
case .OrderedAscending:
    println("iOS < 8.0")
}

How is the java memory pool divided?

The new keyword allocates memory on the Java heap. The heap is the main pool of memory, accessible to the whole of the application. If there is not enough memory available to allocate for that object, the JVM attempts to reclaim some memory from the heap with a garbage collection. If it still cannot obtain enough memory, an OutOfMemoryError is thrown, and the JVM exits.

The heap is split into several different sections, called generations. As objects survive more garbage collections, they are promoted into different generations. The older generations are not garbage collected as often. Because these objects have already proven to be longer lived, they are less likely to be garbage collected.

When objects are first constructed, they are allocated in the Eden Space. If they survive a garbage collection, they are promoted to Survivor Space, and should they live long enough there, they are allocated to the Tenured Generation. This generation is garbage collected much less frequently.

There is also a fourth generation, called the Permanent Generation, or PermGen. The objects that reside here are not eligible to be garbage collected, and usually contain an immutable state necessary for the JVM to run, such as class definitions and the String constant pool. Note that the PermGen space is planned to be removed from Java 8, and will be replaced with a new space called Metaspace, which will be held in native memory. reference:http://www.programcreek.com/2013/04/jvm-run-time-data-areas/

Diagram of Java memory for several threads Diagram of Java memory distribution

Way to ng-repeat defined number of times instead of repeating over array?

If n is not too high, another option could be to use split('') with a string of n characters :

<div ng-controller="MainCtrl">
<div ng-repeat="a in 'abcdefgh'.split('')">{{$index}}</div>
</div>

Can't find @Nullable inside javax.annotation.*

In the case of Android projects, you can fix this error by changing the project/module gradle file (build.gradle) as follows:

dependencies { implementation 'com.android.support:support-annotations:24.2.0' }

For more informations, please refer here.

Do copyright dates need to be updated?

Your OCD is to blame :)

You do not have to put anything about copyright on your page - copyright automatically applies until you explicitly license it otherwise. Copyright also applies for a preset number of years as determined by international treaties. I do not know what the exact number of years is, but it is a lot, so there is absolutely no point in updating the year in your copyright notice.

How to turn on front flash light programmatically in Android?

Try this.

CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    String cameraId = null; // Usually front camera is at 0 position.
    try {
        cameraId = camManager.getCameraIdList()[0];
        camManager.setTorchMode(cameraId, true);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

How to compare if two structs, slices or maps are equal?

You can use reflect.DeepEqual, or you can implement your own function (which performance wise would be better than using reflection):

http://play.golang.org/p/CPdfsYGNy_

m1 := map[string]int{   
    "a":1,
    "b":2,
}
m2 := map[string]int{   
    "a":1,
    "b":2,
}
fmt.Println(reflect.DeepEqual(m1, m2))

How can I convert an image into a Base64 string?

You can use the Base64 Android class:

String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

You'll have to convert your image into a byte array though. Here's an example:

Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the bitmap object
byte[] b = baos.toByteArray();

* Update *

If you're using an older SDK library (because you want it to work on phones with older versions of the OS) you won't have the Base64 class packaged in (since it just came out in API level 8 AKA version 2.2).

Check this article out for a workaround:

How to base64 encode decode Android

How do I refresh the page in ASP.NET? (Let it reload itself by code)

Response.Write("<script>window.opener.location.href = window.opener.location.href </script>");

Drop rows with all zeros in pandas data frame

Replace the zeros with nan and then drop the rows with all entries as nan. After that replace nan with zeros.

import numpy as np
df = df.replace(0, np.nan)
df = df.dropna(how='all', axis=0)
df = df.replace(np.nan, 0)

Can Selenium WebDriver open browser windows silently in the background?

I had the same problem with my chromedriver using Python and options.add_argument("headless") did not work for me, but then I realized how to fix it so I bring it in the code below:

opt = webdriver.ChromeOptions()
opt.arguments.append("headless")

Equal sized table cells to fill the entire width of the containing table

Just use percentage widths and fixed table layout:

<table>
<tr>
  <td>1</td>
  <td>2</td>
  <td>3</td>
</tr>
</table>

with

table { table-layout: fixed; }
td { width: 33%; }

Fixed table layout is important as otherwise the browser will adjust the widths as it sees fit if the contents don't fit ie the widths are otherwise a suggestion not a rule without fixed table layout.

Obviously, adjust the CSS to fit your circumstances, which usually means applying the styling only to a tables with a given class or possibly with a given ID.

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

I run selenium tests with Jenkins running on an Ubuntu 18 LTS linux. I had this error until I added the argument 'headless' like this (and some other arguments):

ChromeOptions options = new ChromeOptions();
options.addArguments("headless"); // headless -> no browser window. needed for jenkins
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox"); // Bypass OS security model
ChromeDriver driver = new ChromeDriver(options);

driver.get("www.google.com");

Tricks to manage the available memory in an R session

If you are working on Linux and want to use several processes and only have to do read operations on one or more large objects use makeForkCluster instead of a makePSOCKcluster. This also saves you the time sending the large object to the other processes.

What is hashCode used for? Is it unique?

MSDN says:

A hash code is a numeric value that is used to identify an object during equality testing. It can also serve as an index for an object in a collection.

The GetHashCode method is suitable for use in hashing algorithms and data structures such as a hash table.

The default implementation of the GetHashCode method does not guarantee unique return values for different objects. Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework. Consequently, the default implementation of this method must not be used as a unique object identifier for hashing purposes.

The GetHashCode method can be overridden by a derived type. Value types must override this method to provide a hash function that is appropriate for that type and to provide a useful distribution in a hash table. For uniqueness, the hash code must be based on the value of an instance field or property instead of a static field or property.

Objects used as a key in a Hashtable object must also override the GetHashCode method because those objects must generate their own hash code. If an object used as a key does not provide a useful implementation of GetHashCode, you can specify a hash code provider when the Hashtable object is constructed. Prior to the .NET Framework version 2.0, the hash code provider was based on the System.Collections.IHashCodeProvider interface. Starting with version 2.0, the hash code provider is based on the System.Collections.IEqualityComparer interface.

Basically, hash codes exist to make hashtables possible.
Two equal objects are guaranteed to have equal hashcodes.
Two unequal objects are not guaranteed to have unequal hashcodes (that's called a collision).

Random integer in VB.NET

Just for reference, VB NET Fuction definition for RND and RANDOMIZE (which should give the same results of BASIC (1980 years) and all versions after is:

Public NotInheritable Class VBMath
    ' Methods
    Private Shared Function GetTimer() As Single
        Dim now As DateTime = DateTime.Now
        Return CSng((((((60 * now.Hour) + now.Minute) * 60) + now.Second) + (CDbl(now.Millisecond) / 1000)))
    End Function

    Public Shared Sub Randomize()
        Dim timer As Single = VBMath.GetTimer
        Dim projectData As ProjectData = ProjectData.GetProjectData
        Dim rndSeed As Integer = projectData.m_rndSeed
        Dim num3 As Integer = BitConverter.ToInt32(BitConverter.GetBytes(timer), 0)
        num3 = (((num3 And &HFFFF) Xor (num3 >> &H10)) << 8)
        rndSeed = ((rndSeed And -16776961) Or num3)
        projectData.m_rndSeed = rndSeed
    End Sub

    Public Shared Sub Randomize(ByVal Number As Double)
        Dim num2 As Integer
        Dim projectData As ProjectData = ProjectData.GetProjectData
        Dim rndSeed As Integer = projectData.m_rndSeed
        If BitConverter.IsLittleEndian Then
            num2 = BitConverter.ToInt32(BitConverter.GetBytes(Number), 4)
        Else
            num2 = BitConverter.ToInt32(BitConverter.GetBytes(Number), 0)
        End If
        num2 = (((num2 And &HFFFF) Xor (num2 >> &H10)) << 8)
        rndSeed = ((rndSeed And -16776961) Or num2)
        projectData.m_rndSeed = rndSeed
    End Sub

    Public Shared Function Rnd() As Single
        Return VBMath.Rnd(1!)
    End Function

    Public Shared Function Rnd(ByVal Number As Single) As Single
        Dim projectData As ProjectData = ProjectData.GetProjectData
        Dim rndSeed As Integer = projectData.m_rndSeed
        If (Number <> 0) Then
            If (Number < 0) Then
                Dim num1 As UInt64 = (BitConverter.ToInt32(BitConverter.GetBytes(Number), 0) And &HFFFFFFFF)
                rndSeed = CInt(((num1 + (num1 >> &H18)) And CULng(&HFFFFFF)))
            End If
            rndSeed = CInt((((rndSeed * &H43FD43FD) + &HC39EC3) And &HFFFFFF))
        End If
        projectData.m_rndSeed = rndSeed
        Return (CSng(rndSeed) / 1.677722E+07!)
    End Function

End Class

While the Random CLASS is:

Public Class Random
    ' Methods
    <__DynamicallyInvokable> _
    Public Sub New()
        Me.New(Environment.TickCount)
    End Sub

    <__DynamicallyInvokable> _
    Public Sub New(ByVal Seed As Integer)
        Me.SeedArray = New Integer(&H38  - 1) {}
        Dim num4 As Integer = If((Seed = -2147483648), &H7FFFFFFF, Math.Abs(Seed))
        Dim num2 As Integer = (&H9A4EC86 - num4)
        Me.SeedArray(&H37) = num2
        Dim num3 As Integer = 1
        Dim i As Integer
        For i = 1 To &H37 - 1
            Dim index As Integer = ((&H15 * i) Mod &H37)
            Me.SeedArray(index) = num3
            num3 = (num2 - num3)
            If (num3 < 0) Then
                num3 = (num3 + &H7FFFFFFF)
            End If
            num2 = Me.SeedArray(index)
        Next i
        Dim j As Integer
        For j = 1 To 5 - 1
            Dim k As Integer
            For k = 1 To &H38 - 1
                Me.SeedArray(k) = (Me.SeedArray(k) - Me.SeedArray((1 + ((k + 30) Mod &H37))))
                If (Me.SeedArray(k) < 0) Then
                    Me.SeedArray(k) = (Me.SeedArray(k) + &H7FFFFFFF)
                End If
            Next k
        Next j
        Me.inext = 0
        Me.inextp = &H15
        Seed = 1
    End Sub

    Private Function GetSampleForLargeRange() As Double
        Dim num As Integer = Me.InternalSample
        If ((Me.InternalSample Mod 2) = 0) Then
            num = -num
        End If
        Dim num2 As Double = num
        num2 = (num2 + 2147483646)
        Return (num2 / 4294967293)
    End Function

    Private Function InternalSample() As Integer
        Dim inext As Integer = Me.inext
        Dim inextp As Integer = Me.inextp
        If (++inext >= &H38) Then
            inext = 1
        End If
        If (++inextp >= &H38) Then
            inextp = 1
        End If
        Dim num As Integer = (Me.SeedArray(inext) - Me.SeedArray(inextp))
        If (num = &H7FFFFFFF) Then
            num -= 1
        End If
        If (num < 0) Then
            num = (num + &H7FFFFFFF)
        End If
        Me.SeedArray(inext) = num
        Me.inext = inext
        Me.inextp = inextp
        Return num
    End Function

    <__DynamicallyInvokable> _
    Public Overridable Function [Next]() As Integer
        Return Me.InternalSample
    End Function

    <__DynamicallyInvokable> _
    Public Overridable Function [Next](ByVal maxValue As Integer) As Integer
        If (maxValue < 0) Then
            Dim values As Object() = New Object() { "maxValue" }
            Throw New ArgumentOutOfRangeException("maxValue", Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", values))
        End If
        Return CInt((Me.Sample * maxValue))
    End Function

    <__DynamicallyInvokable> _
    Public Overridable Function [Next](ByVal minValue As Integer, ByVal maxValue As Integer) As Integer
        If (minValue > maxValue) Then
            Dim values As Object() = New Object() { "minValue", "maxValue" }
            Throw New ArgumentOutOfRangeException("minValue", Environment.GetResourceString("Argument_MinMaxValue", values))
        End If
        Dim num As Long = (maxValue - minValue)
        If (num <= &H7FFFFFFF) Then
            Return (CInt((Me.Sample * num)) + minValue)
        End If
        Return (CInt(CLng((Me.GetSampleForLargeRange * num))) + minValue)
    End Function

    <__DynamicallyInvokable> _
    Public Overridable Sub NextBytes(ByVal buffer As Byte())
        If (buffer Is Nothing) Then
            Throw New ArgumentNullException("buffer")
        End If
        Dim i As Integer
        For i = 0 To buffer.Length - 1
            buffer(i) = CByte((Me.InternalSample Mod &H100))
        Next i
    End Sub

    <__DynamicallyInvokable> _
    Public Overridable Function NextDouble() As Double
        Return Me.Sample
    End Function

    <__DynamicallyInvokable> _
    Protected Overridable Function Sample() As Double
        Return (Me.InternalSample * 4.6566128752457969E-10)
    End Function


    ' Fields
    Private inext As Integer
    Private inextp As Integer
    Private Const MBIG As Integer = &H7FFFFFFF
    Private Const MSEED As Integer = &H9A4EC86
    Private Const MZ As Integer = 0
    Private SeedArray As Integer()
End Class

Installing SciPy and NumPy using pip

Since the previous instructions for installing with yum are broken here are the updated instructions for installing on something like fedora. I've tested this on "Amazon Linux AMI 2016.03"

sudo yum install atlas-devel lapack-devel blas-devel libgfortran
pip install scipy

How can I get terminal output in python?

The recommended way in Python 3.5 and above is to use subprocess.run():

from subprocess import run
output = run("pwd", capture_output=True).stdout

Howto: Clean a mysql InnoDB storage engine?

The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.

You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.

Find duplicate records in MongoDB

db.getCollection('orders').aggregate([  
    {$group: { 
            _id: {name: "$name"},
            uniqueIds: {$addToSet: "$_id"},
            count: {$sum: 1}
        } 
    },
    {$match: { 
        count: {"$gt": 1}
        }
    }
])

First Group Query the group according to the fields.

Then we check the unique Id and count it, If count is greater then 1 then the field is duplicate in the entire collection so that thing is to be handle by $match query.

SQL Server: Error converting data type nvarchar to numeric

I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT function on the nvarchar field.

Example: Left(Field,4)

Basically, the query will look like:

Select convert(float,left(Field,4)) from TABLE

Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.

Convert string to decimal, keeping fractions

The use of CultureInfo class worked for me, I hope help you.

    string value = "1200.00";
    CultureInfo culture = new CultureInfo("en-US");
    decimal result = Convert.ToDecimal(value, culture);

What are metaclasses in Python?

Role of a metaclass' __call__() method when creating a class instance

If you've done Python programming for more than a few months you'll eventually stumble upon code that looks like this:

# define a class
class SomeClass(object):
    # ...
    # some definition here ...
    # ...

# create an instance of it
instance = SomeClass()

# then call the object as if it's a function
result = instance('foo', 'bar')

The latter is possible when you implement the __call__() magic method on the class.

class SomeClass(object):
    # ...
    # some definition here ...
    # ...

    def __call__(self, foo, bar):
        return bar + foo

The __call__() method is invoked when an instance of a class is used as a callable. But as we've seen from previous answers a class itself is an instance of a metaclass, so when we use the class as a callable (i.e. when we create an instance of it) we're actually calling its metaclass' __call__() method. At this point most Python programmers are a bit confused because they've been told that when creating an instance like this instance = SomeClass() you're calling its __init__() method. Some who've dug a bit deeper know that before __init__() there's __new__(). Well, today another layer of truth is being revealed, before __new__() there's the metaclass' __call__().

Let's study the method call chain from specifically the perspective of creating an instance of a class.

This is a metaclass that logs exactly the moment before an instance is created and the moment it's about to return it.

class Meta_1(type):
    def __call__(cls):
        print "Meta_1.__call__() before creating an instance of ", cls
        instance = super(Meta_1, cls).__call__()
        print "Meta_1.__call__() about to return instance."
        return instance

This is a class that uses that metaclass

class Class_1(object):

    __metaclass__ = Meta_1

    def __new__(cls):
        print "Class_1.__new__() before creating an instance."
        instance = super(Class_1, cls).__new__(cls)
        print "Class_1.__new__() about to return instance."
        return instance

    def __init__(self):
        print "entering Class_1.__init__() for instance initialization."
        super(Class_1,self).__init__()
        print "exiting Class_1.__init__()."

And now let's create an instance of Class_1

instance = Class_1()
# Meta_1.__call__() before creating an instance of <class '__main__.Class_1'>.
# Class_1.__new__() before creating an instance.
# Class_1.__new__() about to return instance.
# entering Class_1.__init__() for instance initialization.
# exiting Class_1.__init__().
# Meta_1.__call__() about to return instance.

Observe that the code above doesn't actually do anything more than logging the tasks. Each method delegates the actual work to its parent's implementation, thus keeping the default behavior. Since type is Meta_1's parent class (type being the default parent metaclass) and considering the ordering sequence of the output above, we now have a clue as to what would be the pseudo implementation of type.__call__():

class type:
    def __call__(cls, *args, **kwarg):

        # ... maybe a few things done to cls here

        # then we call __new__() on the class to create an instance
        instance = cls.__new__(cls, *args, **kwargs)

        # ... maybe a few things done to the instance here

        # then we initialize the instance with its __init__() method
        instance.__init__(*args, **kwargs)

        # ... maybe a few more things done to instance here

        # then we return it
        return instance

We can see that the metaclass' __call__() method is the one that's called first. It then delegates creation of the instance to the class's __new__() method and initialization to the instance's __init__(). It's also the one that ultimately returns the instance.

From the above it stems that the metaclass' __call__() is also given the opportunity to decide whether or not a call to Class_1.__new__() or Class_1.__init__() will eventually be made. Over the course of its execution it could actually return an object that hasn't been touched by either of these methods. Take for example this approach to the singleton pattern:

class Meta_2(type):
    singletons = {}

    def __call__(cls, *args, **kwargs):
        if cls in Meta_2.singletons:
            # we return the only instance and skip a call to __new__()
            # and __init__()
            print ("{} singleton returning from Meta_2.__call__(), "
                   "skipping creation of new instance.".format(cls))
            return Meta_2.singletons[cls]

        # else if the singleton isn't present we proceed as usual
        print "Meta_2.__call__() before creating an instance."
        instance = super(Meta_2, cls).__call__(*args, **kwargs)
        Meta_2.singletons[cls] = instance
        print "Meta_2.__call__() returning new instance."
        return instance

class Class_2(object):

    __metaclass__ = Meta_2

    def __new__(cls, *args, **kwargs):
        print "Class_2.__new__() before creating instance."
        instance = super(Class_2, cls).__new__(cls)
        print "Class_2.__new__() returning instance."
        return instance

    def __init__(self, *args, **kwargs):
        print "entering Class_2.__init__() for initialization."
        super(Class_2, self).__init__()
        print "exiting Class_2.__init__()."

Let's observe what happens when repeatedly trying to create an object of type Class_2

a = Class_2()
# Meta_2.__call__() before creating an instance.
# Class_2.__new__() before creating instance.
# Class_2.__new__() returning instance.
# entering Class_2.__init__() for initialization.
# exiting Class_2.__init__().
# Meta_2.__call__() returning new instance.

b = Class_2()
# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.

c = Class_2()
# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.

a is b is c # True

CGContextDrawImage draws image upside down when passed UIImage.CGImage

You can also solve this problem by doing this:

//Using an Image as a mask by directly inserting UIImageObject.CGImage causes
//the same inverted display problem. This is solved by saving it to a CGImageRef first.

//CGImageRef image = [UImageObject CGImage];

//CGContextDrawImage(context, boundsRect, image);

Nevermind... Stupid caching.

How to get the latest record in each group using GROUP BY?

This is a standard problem.

Note that MySQL allows you to omit columns from the GROUP BY clause, which Standard SQL does not, but you do not get deterministic results in general when you use the MySQL facility.

SELECT *
  FROM Messages AS M
  JOIN (SELECT To_ID, From_ID, MAX(TimeStamp) AS Most_Recent
          FROM Messages
         WHERE To_ID = 12345678
         GROUP BY From_ID
       ) AS R
    ON R.To_ID = M.To_ID AND R.From_ID = M.From_ID AND R.Most_Recent = M.TimeStamp
 WHERE M.To_ID = 12345678

I've added a filter on the To_ID to match what you're likely to have. The query will work without it, but will return a lot more data in general. The condition should not need to be stated in both the nested query and the outer query (the optimizer should push the condition down automatically), but it can do no harm to repeat the condition as shown.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

The simple solution is download and extract the following file which contains mips64el-linux-android-4.9 and mipsel-linux-android-4.9 folders,to your toolchains folder inside sdk "android-sdk\ndk-bundle\toolchains".

Downlod this file and extraxt to toolchains foolder

Using lodash to compare jagged arrays (items existence without order)

PURE JS (works also when arrays and subarrays has more than 2 elements with arbitrary order). If strings contains , use as join('-') parametr character (can be utf) which is not used in strings

array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join()

_x000D_
_x000D_
var array1 = [['a', 'b'], ['b', 'c']];_x000D_
var array2 = [['b', 'c'], ['b', 'a']];_x000D_
_x000D_
var r = array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join();_x000D_
_x000D_
console.log(r);
_x000D_
_x000D_
_x000D_

"Default Activity Not Found" on Android Studio upgrade

Well, I don't understand Android Studio sometimes...

I encountered the same problem and tried the what the answers here told, but to no avail. And then I changed one thing: the action in my intent-filter was having the action name all in caps and I changed it to small and left only the word MAIN in caps, and it solved the problem! How absurd! I hope this can help someone.

Inserting created_at data with Laravel

In my case, I wanted to unit test that users weren't able to verify their email addresses after 1 hour had passed, so I didn't want to do any of the other answers since they would also persist when not unit testing, so I ended up just manually updating the row after insert:

// Create new user
$user = factory(User::class)->create();

// Add an email verification token to the 
// email_verification_tokens table
$token = $user->generateNewEmailVerificationToken();

// Get the time 61 minutes ago
$created_at = (new Carbon())->subMinutes(61);

// Do the update
\DB::update(
    'UPDATE email_verification_tokens SET created_at = ?',
    [$created_at]
);

Note: For anything other than unit testing, I would look at the other answers here.

Click in OK button inside an Alert (Selenium IDE)

about Selenium IDE, I am not an expert but you have to add the line "choose ok on next confirmation" before the event which trigger the alert/confirm dialog box as you can see into this screenshot:

Selenium IDE order matter

NodeJS / Express: what is "app.use"?

app.use() handles all the middleware functions.
What is middleware?
Middlewares are the functions which work like a door between two all the routes.

For instance:

app.use((req, res, next) => {
    console.log("middleware ran");
    next();
});

app.get("/", (req, res) => {
    console.log("Home route");
});

When you visit / route in your console the two message will be printed. The first message will be from middleware function. If there is no next() function passed then only middleware function runs and other routes are blocked.

A Java collection of value pairs? (tuples?)

First Thing on my mind when talking about key/value pairs is the Properties Class where you can save and load items to a stream/file.

How to declare a inline object with inline variables without a parent class

You can also do this:

var x = new object[] {
    new { firstName = "john", lastName = "walter" },
    new { brand = "BMW" }
};

And if they are the same anonymous type (firstName and lastName), you won't need to cast as object.

var y = new [] {
    new { firstName = "john", lastName = "walter" },
    new { firstName = "jill", lastName = "white" }
};

Removing items from a ListBox in VB.net

I think your ListBox already clear with ListBox2.Items.Clear(). The problem is that you also need to clear your dataset from previous results with ds6.Tables.Clear().

Add this in your code:

da6 = New SqlDataAdapter("select distinct(component_type) from component where   component_name='" & ListBox1.SelectedItem() & "'", con)
    ListBox1.Items.Clear()    ' clears ListBox1
    ListBox2.Items.Clear()    ' clears ListBox2
    ds6.Tables.Clear()        ' clears DataSet  <======= DON'T FORGET TO DO THIS
da6.Fill(ds6, "component")
For Each row As DataRow In ds6.Tables(0).Rows
    ListBox2.Items.Add(row.Field(Of String)("component_type"))
Next

Best way to do multi-row insert in Oracle?

you can insert using loop if you want to insert some random values.

BEGIN 
    FOR x IN 1 .. 1000 LOOP
         INSERT INTO MULTI_INSERT_DEMO (ID, NAME)
         SELECT x, 'anyName' FROM dual;
    END LOOP;
END;

Convert List<T> to ObservableCollection<T> in WP7

I made an extension so now I can just load a collection with a list by doing:

MyObservableCollection.Load(MyList);

The extension is:

public static class ObservableCollectionExtension
{
  public static ObservableCollection<T> Load<T>(this ObservableCollection<T> Collection, List<T> Source)
  {
          Collection.Clear();    
          Source.ForEach(x => Collection.Add(x));    
          return Collection;
   }
}

Authorize attribute in ASP.NET MVC

Using [Authorize] attributes can help prevent security holes in your application. The way that MVC handles URL's (i.e. routing them to a controller rather than to an actual file) makes it difficult to actually secure everything via the web.config file.

Read more here: http://blogs.msdn.com/b/rickandy/archive/2012/03/23/securing-your-asp-net-mvc-4-app-and-the-new-allowanonymous-attribute.aspx (via archive.org)

How to use Typescript with native ES6 Promises

A. If using "target": "es5" and TypeScript version below 2.0:

typings install es6-promise --save --global --source dt

B. If using "target": "es5" and TypeScript version 2.0 or higer:

"compilerOptions": {
    "lib": ["es5", "es2015.promise"]
}

C. If using "target": "es6", there's no need to do anything.

Open Facebook page from Android app?

In Facebook version 11.0.0.11.23 (3002850) fb://profile/ and fb://page/ no longer work. I decompiled the Facebook app and found that you can use fb://facewebmodal/f?href=[YOUR_FACEBOOK_PAGE]. Here is the method I have been using in production:

/**
 * <p>Intent to open the official Facebook app. If the Facebook app is not installed then the
 * default web browser will be used.</p>
 *
 * <p>Example usage:</p>
 *
 * {@code newFacebookIntent(ctx.getPackageManager(), "https://www.facebook.com/JRummyApps");}
 *
 * @param pm
 *     The {@link PackageManager}. You can find this class through {@link
 *     Context#getPackageManager()}.
 * @param url
 *     The full URL to the Facebook page or profile.
 * @return An intent that will open the Facebook page/profile.
 */
public static Intent newFacebookIntent(PackageManager pm, String url) {
  Uri uri = Uri.parse(url);
  try {
    ApplicationInfo applicationInfo = pm.getApplicationInfo("com.facebook.katana", 0);
    if (applicationInfo.enabled) {
      // http://stackoverflow.com/a/24547437/1048340
      uri = Uri.parse("fb://facewebmodal/f?href=" + url);
    }
  } catch (PackageManager.NameNotFoundException ignored) {
  }
  return new Intent(Intent.ACTION_VIEW, uri);
}

SQL Server datetime LIKE select?

Unfortunately, It is not possible to compare datetime towards varchar using 'LIKE' But the desired output is possible in another way.

    select * from record where datediff(dd,[record].[register_date],'2009-10-10')=0

Java constant examples (Create a java file having only constants)

You can also use the Properties class

Here's the constants file called

# this will hold all of the constants
frameWidth = 1600
frameHeight = 900

Here is the code that uses the constants

public class SimpleGuiAnimation {

    int frameWidth;
    int frameHeight;


    public SimpleGuiAnimation() {
        Properties properties = new Properties();

        try {
            File file = new File("src/main/resources/dataDirectory/gui_constants.properties");
            FileInputStream fileInputStream = new FileInputStream(file);
            properties.load(fileInputStream);
        }
        catch (FileNotFoundException fileNotFoundException) {
            System.out.println("Could not find the properties file" + fileNotFoundException);
        }
        catch (Exception exception) {
            System.out.println("Could not load properties file" + exception.toString());
        }


        this.frameWidth = Integer.parseInt(properties.getProperty("frameWidth"));
        this.frameHeight = Integer.parseInt(properties.getProperty("frameHeight"));
    }

How to know what the 'errno' means?

Instead of running perror on any error code you get, you can retrieve a complete listing of errno values on your system with the following one-liner:

cpp -dM /usr/include/errno.h | grep 'define E' | sort -n -k 3

Force encode from US-ASCII to UTF-8 (iconv)

Here's a script that will find all files matching a pattern you pass it, and then converting them from their current file encoding to UTF-8. If the encoding is US ASCII, then it will still show as US ASCII, since that is a subset of UTF-8.

#!/usr/bin/env bash
find . -name "${1}" |
    while read line;
    do
        echo "***************************"
        echo "Converting ${line}"

        encoding=$(file -b --mime-encoding ${line})
        echo "Found Encoding: ${encoding}"

        iconv -f "${encoding}" -t "utf-8" ${line} -o ${line}.tmp
        mv ${line}.tmp ${line}
    done

Show a div with Fancybox

I use approach with appending "singleton" link for element you want to show in fancybox. This is code, what I use with some minor edits:

function showElementInPopUp(elementId) {
    var fancyboxAnchorElementId = "fancyboxTriggerFor_" + elementId;
    if ($("#"+fancyboxAnchorElementId).length == 0) {
        $("body").append("<a id='" + fancyboxAnchorElementId + "' href='#" + elementId+ "' style='display:none;'></a>");
        $("#"+fancyboxAnchorElementId).fancybox();
    }

    $("#" + fancyboxAnchorElementId).click();
}

Additional explanation: If you show fancybox with "content" option, it will duplicate DOM, which is inside elements. Sometimes this is not OK. In my case I needed to have the same elements, because they were used in form.

What's the difference between an element and a node in XML?

As described in the various XML specifications, an element is that which consists of a start tag, and end tag, and the content in between, or alternately an empty element tag (which has no content or end tag). In other words, these are all elements:

<foo> stuff </foo>
<foo bar="baz"></foo>
<foo baz="qux" />

Though you hear "node" used with roughly the same meaning, it has no precise definition per XML specs. It's usually used to refer to nodes of things like DOMs, which may be closely related to XML or use XML for their representation.

Difference between two dates in Python

Try this:

data=pd.read_csv('C:\Users\Desktop\Data Exploration.csv')
data.head(5)
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']
l_1=np.mean(first)-3*np.std(first)
u_1=np.mean(first)+3*np.std(first)


m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
pd.value_counts(m)
l=first[m]
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()




m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
pd.value_counts(m)
l=last[m]
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()

How to search a list of tuples in Python

tl;dr

A generator expression is probably the most performant and simple solution to your problem:

l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

result = next((i for i, v in enumerate(l) if v[0] == 53), None)
# 2

Explanation

There are several answers that provide a simple solution to this question with list comprehensions. While these answers are perfectly correct, they are not optimal. Depending on your use case, there may be significant benefits to making a few simple modifications.

The main problem I see with using a list comprehension for this use case is that the entire list will be processed, although you only want to find 1 element.

Python provides a simple construct which is ideal here. It is called the generator expression. Here is an example:

# Our input list, same as before
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

# Call next on our generator expression.
next((i for i, v in enumerate(l) if v[0] == 53), None)

We can expect this method to perform basically the same as list comprehensions in our trivial example, but what if we're working with a larger data set? That's where the advantage of using the generator method comes into play. Rather than constructing a new list, we'll use your existing list as our iterable, and use next() to get the first item from our generator.

Lets look at how these methods perform differently on some larger data sets. These are large lists, made of 10000000 + 1 elements, with our target at the beginning (best) or end (worst). We can verify that both of these lists will perform equally using the following list comprehension:

List comprehensions

"Worst case"

worst_case = ([(False, 'F')] * 10000000) + [(True, 'T')]
print [i for i, v in enumerate(worst_case) if v[0] is True]

# [10000000]
#          2 function calls in 3.885 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    3.885    3.885    3.885    3.885 so_lc.py:1(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

"Best case"

best_case = [(True, 'T')] + ([(False, 'F')] * 10000000)
print [i for i, v in enumerate(best_case) if v[0] is True]

# [0]
#          2 function calls in 3.864 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    3.864    3.864    3.864    3.864 so_lc.py:1(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Generator expressions

Here's my hypothesis for generators: we'll see that generators will significantly perform better in the best case, but similarly in the worst case. This performance gain is mostly due to the fact that the generator is evaluated lazily, meaning it will only compute what is required to yield a value.

Worst case

# 10000000
#          5 function calls in 1.733 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         2    1.455    0.727    1.455    0.727 so_lc.py:10(<genexpr>)
#         1    0.278    0.278    1.733    1.733 so_lc.py:9(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
#         1    0.000    0.000    1.455    1.455 {next}

Best case

best_case  = [(True, 'T')] + ([(False, 'F')] * 10000000)
print next((i for i, v in enumerate(best_case) if v[0] == True), None)

# 0
#          5 function calls in 0.316 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    0.316    0.316    0.316    0.316 so_lc.py:6(<module>)
#         2    0.000    0.000    0.000    0.000 so_lc.py:7(<genexpr>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
#         1    0.000    0.000    0.000    0.000 {next}

WHAT?! The best case blows away the list comprehensions, but I wasn't expecting the our worst case to outperform the list comprehensions to such an extent. How is that? Frankly, I could only speculate without further research.

Take all of this with a grain of salt, I have not run any robust profiling here, just some very basic testing. This should be sufficient to appreciate that a generator expression is more performant for this type of list searching.

Note that this is all basic, built-in python. We don't need to import anything or use any libraries.

I first saw this technique for searching in the Udacity cs212 course with Peter Norvig.

iPhone 6 and 6 Plus Media Queries

This is what is working for me right now:

iPhone 6

@media only screen and (max-device-width: 667px) 
    and (-webkit-device-pixel-ratio: 2) {

iPhone 6+

@media screen and (min-device-width : 414px) 
    and (-webkit-device-pixel-ratio: 3)

How to check if cursor exists (open status)

This happened to me when a stored procedure running in SSMS encountered an error during the loop, while the cursor was in use to iterate over records and before the it was closed. To fix it I added extra code in the CATCH block to close the cursor if it is still open (using CURSOR_STATUS as other answers here suggest).

Ways to save enums in database

I have faced the same issue where my objective is to persist Enum String value into database instead of Ordinal value.

To over come this issue, I have used @Enumerated(EnumType.STRING) and my objective got resolved.

For Example, you have an Enum Class:

public enum FurthitMethod {

    Apple,
    Orange,
    Lemon
}

In the entity class, define @Enumerated(EnumType.STRING):

@Enumerated(EnumType.STRING)
@Column(name = "Fruits")
public FurthitMethod getFuritMethod() {
    return fruitMethod;
}

public void setFruitMethod(FurthitMethod authenticationMethod) {
    this.fruitMethod= fruitMethod;
}

While you try to set your value to Database, String value will be persisted into Database as "APPLE", "ORANGE" or "LEMON".

How do I temporarily disable triggers in PostgreSQL?

Alternatively, if you are wanting to disable all triggers, not just those on the USER table, you can use:

SET session_replication_role = replica;

This disables triggers for the current session.

To re-enable for the same session:

SET session_replication_role = DEFAULT;

Source: http://koo.fi/blog/2013/01/08/disable-postgresql-triggers-temporarily/

Html.Textbox VS Html.TextboxFor

Html.TextBox amd Html.DropDownList are not strongly typed and hence they doesn't require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor and Html.DropDownListFor are strongly typed and requires a strongly typed view, and the name is inferred from the lambda expression.

Strongly typed HTML helpers also provide compile time checking.

Since, in real time, we mostly use strongly typed views, prefer to use Html.TextBoxFor and Html.DropDownListFor over their counterparts.

Whether, we use Html.TextBox & Html.DropDownList OR Html.TextBoxFor & Html.DropDownListFor, the end result is the same, that is they produce the same HTML.

Strongly typed HTML helpers are added in MVC2.

How to start jenkins on different port rather than 8080 using command prompt in Windows?

With Ubuntu 14.4 I had to change the file /etc/default/jenkins

E.g.

   #HTTP_PORT=8080
   HTTP_PORT=8083

and restart the service

service jenkins restart

How do I update a Mongo document after inserting it?

According to the latest documentation about PyMongo titled Insert a Document (insert is deprecated) and following defensive approach, you should insert and update as follows:

result = mycollection.insert_one(post)
post = mycollection.find_one({'_id': result.inserted_id})

if post is not None:
    post['newfield'] = "abc"
    mycollection.save(post)

Executing periodic actions in Python

Here's a simple single threaded sleep based version that drifts, but tries to auto-correct when it detects drift.

NOTE: This will only work if the following 3 reasonable assumptions are met:

  1. The time period is much larger than the execution time of the function being executed
  2. The function being executed takes approximately the same amount of time on each call
  3. The amount of drift between calls is less than a second

-

from datetime import timedelta
from datetime import datetime

def exec_every_n_seconds(n,f):
    first_called=datetime.now()
    f()
    num_calls=1
    drift=timedelta()
    time_period=timedelta(seconds=n)
    while 1:
        time.sleep(n-drift.microseconds/1000000.0)
        current_time = datetime.now()
        f()
        num_calls += 1
        difference = current_time - first_called
        drift = difference - time_period* num_calls
        print "drift=",drift

How to find sum of several integers input by user using do/while, While statement or For statement

The FOR loop worked well, I modified it a tiny bit:

#include<iostream>
using namespace std;
int main ()
{

    int sum = 0;
    int number;
    int numberitems;


    cout << "Enter number of items: \n";
    cin >> numberitems;

    for(int i=0;i<numberitems;i++)
    {
        cout << "Enter number: \n";
        cin >> number; 

        sum=sum+number;

    }
    cout<<"sum is: "<< sum<<endl;
}

HOWEVER, the WHILE loop has got some errors on line 11 (Count was not declared in this scope). What could be the issue? Also, if you would have a solution using DO,WHILE loop it would be wonderful. Thanks

How to open .SQLite files

If you just want to see what's in the database without installing anything extra, you might already have SQLite CLI on your system. To check, open a command prompt and try:

sqlite3 database.sqlite

Replace database.sqlite with your database file. Then, if the database is small enough, you can view the entire contents with:

sqlite> .dump

Or you can list the tables:

sqlite> .tables

Regular SQL works here as well:

sqlite> select * from some_table;

Replace some_table as appropriate.

Is there any way to wait for AJAX response and halt execution?

Method 1:

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        },
        complete: function(){
              // do the job here
         }
    });
}

var response = functABC();

Method 2

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        async: false,
        success: function(data) {
            return data;
        }        
    });

   // do the job here
}

No server in Eclipse; trying to install Tomcat

You have probably installed Eclipse for Java Developers instead of Eclipse IDE for Enterprise Java Developers, server tab and some other are not available.

You don't have to uninstall. Just rerun eclipse-inst-win64.exe and choose Java EE IDE

JAVA EE IDE Installation

Duplicate line in Visual Studio Code

Update that may help Ubuntu users if they still want to use the ? and ? instead of another set of keys.

I just installed a fresh version of VSCode on Ubuntu 18.04 LTS and I had duplicate commands for Add Cursor Above and Add Cursor Below

Original Keybindings

I just removed the bindings that used Ctrl and added my own with the following

Copy Line Up

Ctrl + Shift + ?

Copy Line Down

Ctrl + Shift + ?

New Keybindings

Dynamically Add Variable Name Value Pairs to JSON Object

if my understanding of your initial JSON is correct, either of these solutions might help you loop through all ip ids & assign each one, a new object.

// initial JSON
var ips = {ipId1: {}, ipId2: {}};

// Solution1
Object.keys(ips).forEach(function(key) {
  ips[key] = {name: 'value', anotherName: 'another value'};
});

// Solution 2
Object.keys(ips).forEach(function(key) {
  Object.assign(ips[key],{name: 'value', anotherName: 'another value'});
});

To confirm:

console.log(JSON.stringify(ips, null, 2));

The above statement spits:

{
  "ipId1": {
    "name":"value",
    "anotherName":"another value"
  },
  "ipId2": {
    "name":"value",
    "anotherName":"another value"
  }
}

How to display string that contains HTML in twig template?

You can also use:

{{ word|striptags('<b>')|raw }}

so that only <b> tag will be allowed.

How do I show/hide a UIBarButtonItem?

You can use text attributes to hide a bar button:

barButton.enabled = false
barButton.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.clearColor()], forState: .Normal)

Also see my solution with UIBarButtonItem extension for the similar question: Make a UIBarButtonItem disapear using swift IOS

How to overlay density plots in R?

ggplot2 is another graphics package that handles things like the range issue Gavin mentions in a pretty slick way. It also handles auto generating appropriate legends and just generally has a more polished feel in my opinion out of the box with less manual manipulation.

library(ggplot2)

#Sample data
dat <- data.frame(dens = c(rnorm(100), rnorm(100, 10, 5))
                   , lines = rep(c("a", "b"), each = 100))
#Plot.
ggplot(dat, aes(x = dens, fill = lines)) + geom_density(alpha = 0.5)

enter image description here

jQuery replace one class with another

In jquery to replace a class with another you can use jqueryUI SwitchClass option

 $("#YourID").switchClass("old-class-here", "new-class-here"); 

Get battery level and state in Android

To check battery percentage we use BatteryManager, the following method will return battery percentage.

Source Link

public static float getBatteryLevel(Context context, Intent intent) {
    Intent batteryStatus = context.registerReceiver(null,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int batteryLevel = -1;
    int batteryScale = 1;
    if (batteryStatus != null) {
        batteryLevel = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, batteryLevel);
        batteryScale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, batteryScale);
    }
    return batteryLevel / (float) batteryScale * 100;
}

How can I create a UIColor from a hex string?

I like to ensure the alpha besides the color, so i write my own category

+ (UIColor *) colorWithHex:(int)color {

    float red = (color & 0xff000000) >> 24;
    float green = (color & 0x00ff0000) >> 16;
    float blue = (color & 0x0000ff00) >> 8;
    float alpha = (color & 0x000000ff);

    return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha/255.0];
}

easy to use like this

[UIColor colorWithHex:0xFF0000FF]; //Red
[UIColor colorWithHex:0x00FF00FF]; //Green
[UIColor colorWithHex:0x00FF00FF]; //Blue
[UIColor colorWithHex:0x0000007F]; //transparent black

JTable - Selected Row click event

Here's how I did it:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent event) {
            // do some actions here, for example
            // print first column value from selected row
            System.out.println(table.getValueAt(table.getSelectedRow(), 0).toString());
        }
    });

This code reacts on mouse click and item selection from keyboard.

Move SQL Server 2008 database files to a new folder location

To add the privileges needed to the files add and grant right to the following local user: SQLServerMSSQLUser$COMPUTERNAME$INSTANCENAME, where COMPUTERNAME and INSTANCENAME has to be replaced with name of computer and MSSQL instance respectively.

'negative' pattern matching in python

If the OK line is the first line and the last line is the dot you could consider slice them off like this:

TestString = '''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
.
'''
print('\n'.join(TestString.split()[1:-1]))

However if this is a very large string you may run into memory problems.

change background image in body

You would need to use Javascript for this. You can set the style of the background-image for the body like so.

var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';

Just make sure you replace the URL with the actual URL.

How to fix nginx throws 400 bad request headers on any header testing tools?

Just to clearify, in /etc/nginx/nginx.conf, you can put at the beginning of the file the line

error_log /var/log/nginx/error.log debug;

And then restart nginx:

sudo service nginx restart

That way you can detail what nginx is doing and why it is returning the status code 400.

Swift: Display HTML data in a label or textView

Add this extension to convert your html code to a regular string:

    extension String {

        var html2AttributedString: NSAttributedString? {
            guard
                let data = dataUsingEncoding(NSUTF8StringEncoding)
            else { return nil }
            do {
                return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
            } catch let error as NSError {
                print(error.localizedDescription)
                return  nil
            }
        }
        var html2String: String {
            return html2AttributedString?.string ?? ""
        }
}

And then you show your String inside an UITextView Or UILabel

textView.text = yourString.html2String or

label.text = yourString.html2String

JAVA_HOME is set to an invalid directory:

You should set it with C:\Program Files\Java\jdk1.8.0_12.

\bin is not required.

What are SP (stack) and LR in ARM?

SP is the stack register a shortcut for typing r13. LR is the link register a shortcut for r14. And PC is the program counter a shortcut for typing r15.

When you perform a call, called a branch link instruction, bl, the return address is placed in r14, the link register. the program counter pc is changed to the address you are branching to.

There are a few stack pointers in the traditional ARM cores (the cortex-m series being an exception) when you hit an interrupt for example you are using a different stack than when running in the foreground, you dont have to change your code just use sp or r13 as normal the hardware has done the switch for you and uses the correct one when it decodes the instructions.

The traditional ARM instruction set (not thumb) gives you the freedom to use the stack in a grows up from lower addresses to higher addresses or grows down from high address to low addresses. the compilers and most folks set the stack pointer high and have it grow down from high addresses to lower addresses. For example maybe you have ram from 0x20000000 to 0x20008000 you set your linker script to build your program to run/use 0x20000000 and set your stack pointer to 0x20008000 in your startup code, at least the system/user stack pointer, you have to divide up the memory for other stacks if you need/use them.

Stack is just memory. Processors normally have special memory read/write instructions that are PC based and some that are stack based. The stack ones at a minimum are usually named push and pop but dont have to be (as with the traditional arm instructions).

If you go to http://github.com/lsasim I created a teaching processor and have an assembly language tutorial. Somewhere in there I go through a discussion about stacks. It is NOT an arm processor but the story is the same it should translate directly to what you are trying to understand on the arm or most other processors.

Say for example you have 20 variables you need in your program but only 16 registers minus at least three of them (sp, lr, pc) that are special purpose. You are going to have to keep some of your variables in ram. Lets say that r5 holds a variable that you use often enough that you dont want to keep it in ram, but there is one section of code where you really need another register to do something and r5 is not being used, you can save r5 on the stack with minimal effort while you reuse r5 for something else, then later, easily, restore it.

Traditional (well not all the way back to the beginning) arm syntax:

...
stmdb r13!,{r5}
...temporarily use r5 for something else...
ldmia r13!,{r5}
...

stm is store multiple you can save more than one register at a time, up to all of them in one instruction.

db means decrement before, this is a downward moving stack from high addresses to lower addresses.

You can use r13 or sp here to indicate the stack pointer. This particular instruction is not limited to stack operations, can be used for other things.

The ! means update the r13 register with the new address after it completes, here again stm can be used for non-stack operations so you might not want to change the base address register, leave the ! off in that case.

Then in the brackets { } list the registers you want to save, comma separated.

ldmia is the reverse, ldm means load multiple. ia means increment after and the rest is the same as stm

So if your stack pointer were at 0x20008000 when you hit the stmdb instruction seeing as there is one 32 bit register in the list it will decrement before it uses it the value in r13 so 0x20007FFC then it writes r5 to 0x20007FFC in memory and saves the value 0x20007FFC in r13. Later, assuming you have no bugs when you get to the ldmia instruction r13 has 0x20007FFC in it there is a single register in the list r5. So it reads memory at 0x20007FFC puts that value in r5, ia means increment after so 0x20007FFC increments one register size to 0x20008000 and the ! means write that number to r13 to complete the instruction.

Why would you use the stack instead of just a fixed memory location? Well the beauty of the above is that r13 can be anywhere it could be 0x20007654 when you run that code or 0x20002000 or whatever and the code still functions, even better if you use that code in a loop or with recursion it works and for each level of recursion you go you save a new copy of r5, you might have 30 saved copies depending on where you are in that loop. and as it unrolls it puts all the copies back as desired. with a single fixed memory location that doesnt work. This translates directly to C code as an example:

void myfun ( void )
{
   int somedata;
}

In a C program like that the variable somedata lives on the stack, if you called myfun recursively you would have multiple copies of the value for somedata depending on how deep in the recursion. Also since that variable is only used within the function and is not needed elsewhere then you perhaps dont want to burn an amount of system memory for that variable for the life of the program you only want those bytes when in that function and free that memory when not in that function. that is what a stack is used for.

A global variable would not be found on the stack.

Going back...

Say you wanted to implement and call that function you would have some code/function you are in when you call the myfun function. The myfun function wants to use r5 and r6 when it is operating on something but it doesnt want to trash whatever someone called it was using r5 and r6 for so for the duration of myfun() you would want to save those registers on the stack. Likewise if you look into the branch link instruction (bl) and the link register lr (r14) there is only one link register, if you call a function from a function you will need to save the link register on each call otherwise you cant return.

...
bl myfun
    <--- the return from my fun returns here
...


myfun:
stmdb sp!,{r5,r6,lr}
sub sp,#4 <--- make room for the somedata variable
...
some code here that uses r5 and r6
bl more_fun <-- this modifies lr, if we didnt save lr we wouldnt be able to return from myfun
   <---- more_fun() returns here
...
add sp,#4 <-- take back the stack memory we allocated for the somedata variable
ldmia sp!,{r5,r6,lr}
mov pc,lr <---- return to whomever called myfun.

So hopefully you can see both the stack usage and link register. Other processors do the same kinds of things in a different way. for example some will put the return value on the stack and when you execute the return function it knows where to return to by pulling a value off of the stack. Compilers C/C++, etc will normally have a "calling convention" or application interface (ABI and EABI are names for the ones ARM has defined). if every function follows the calling convention, puts parameters it is passing to functions being called in the right registers or on the stack per the convention. And each function follows the rules as to what registers it does not have to preserve the contents of and what registers it has to preserve the contents of then you can have functions call functions call functions and do recursion and all kinds of things, so long as the stack does not go so deep that it runs into the memory used for globals and the heap and such, you can call functions and return from them all day long. The above implementation of myfun is very similar to what you would see a compiler produce.

ARM has many cores now and a few instruction sets the cortex-m series works a little differently as far as not having a bunch of modes and different stack pointers. And when executing thumb instructions in thumb mode you use the push and pop instructions which do not give you the freedom to use any register like stm it only uses r13 (sp) and you cannot save all the registers only a specific subset of them. the popular arm assemblers allow you to use

push {r5,r6}
...
pop {r5,r6}

in arm code as well as thumb code. For the arm code it encodes the proper stmdb and ldmia. (in thumb mode you also dont have the choice as to when and where you use db, decrement before, and ia, increment after).

No you absolutly do not have to use the same registers and you dont have to pair up the same number of registers.

push {r5,r6,r7}
...
pop {r2,r3}
...
pop {r1}

assuming there is no other stack pointer modifications in between those instructions if you remember the sp is going to be decremented 12 bytes for the push lets say from 0x1000 to 0x0FF4, r5 will be written to 0xFF4, r6 to 0xFF8 and r7 to 0xFFC the stack pointer will change to 0x0FF4. the first pop will take the value at 0x0FF4 and put that in r2 then the value at 0x0FF8 and put that in r3 the stack pointer gets the value 0x0FFC. later the last pop, the sp is 0x0FFC that is read and the value placed in r1, the stack pointer then gets the value 0x1000, where it started.

The ARM ARM, ARM Architectural Reference Manual (infocenter.arm.com, reference manuals, find the one for ARMv5 and download it, this is the traditional ARM ARM with ARM and thumb instructions) contains pseudo code for the ldm and stm ARM istructions for the complete picture as to how these are used. Likewise well the whole book is about the arm and how to program it. Up front the programmers model chapter walks you through all of the registers in all of the modes, etc.

If you are programming an ARM processor you should start by determining (the chip vendor should tell you, ARM does not make chips it makes cores that chip vendors put in their chips) exactly which core you have. Then go to the arm website and find the ARM ARM for that family and find the TRM (technical reference manual) for the specific core including revision if the vendor has supplied that (r2p0 means revision 2.0 (two point zero, 2p0)), even if there is a newer rev, use the manual that goes with the one the vendor used in their design. Not every core supports every instruction or mode the TRM tells you the modes and instructions supported the ARM ARM throws a blanket over the features for the whole family of processors that that core lives in. Note that the ARM7TDMI is an ARMv4 NOT an ARMv7 likewise the ARM9 is not an ARMv9. ARMvNUMBER is the family name ARM7, ARM11 without a v is the core name. The newer cores have names like Cortex and mpcore instead of the ARMNUMBER thing, which reduces confusion. Of course they had to add the confusion back by making an ARMv7-m (cortex-MNUMBER) and the ARMv7-a (Cortex-ANUMBER) which are very different families, one is for heavy loads, desktops, laptops, etc the other is for microcontrollers, clocks and blinking lights on a coffee maker and things like that. google beagleboard (Cortex-A) and the stm32 value line discovery board (Cortex-M) to get a feel for the differences. Or even the open-rd.org board which uses multiple cores at more than a gigahertz or the newer tegra 2 from nvidia, same deal super scaler, muti core, multi gigahertz. A cortex-m barely brakes the 100MHz barrier and has memory measured in kbytes although it probably runs of a battery for months if you wanted it to where a cortex-a not so much.

sorry for the very long post, hope it is useful.

How to query for today's date and 7 days before data?

Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):

select * from tab
where DateCol between adddate(now(),-7) and now() 

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

First I tried

lsof -wni tcp:5432 but it doesn't show any PID number.

Second I tried

Postgres -D /usr/local/var/postgres and it showed that server is listening.

So I just restarted my mac to restore all ports back and it worked for me.

Save range to variable

My use case was to save range to variable and then select it later on

Dim targetRange As Range
Set targetRange = Sheets("Sheet").Range("Name")
Application.Goto targetRange
Set targetRangeQ = Nothing ' reset

How to access at request attributes in JSP?

Using JSTL:

<c:set var="message" value='${requestScope["Error_Message"]}' />

Here var sets the variable name and request.getAttribute is equal to requestScope. But it's not essential. ${Error_Message} will give you the same outcome. It'll search every scope. If you want to do some operation with content you take from Error_Message you have to do it using message. like below one.

<c:out value="${message}"/>

Git - Ignore files during merge

I got over this issue by using git merge command with the --no-commit option and then explicitly removed the staged file and ignore the changes to the file. E.g.: say I want to ignore any changes to myfile.txt I proceed as follows:

git merge --no-ff --no-commit <merge-branch>
git reset HEAD myfile.txt
git checkout -- myfile.txt
git commit -m "merged <merge-branch>"

You can put statements 2 & 3 in a for loop, if you have a list of files to skip.

How to Pass data from child to parent component Angular

Hello you can make use of input and output. Input let you to pass variable form parent to child. Output the same but from child to parent.

The easiest way is to pass "startdate" and "endDate" as input

<calendar [startDateInCalendar]="startDateInSearch" [endDateInCalendar]="endDateInSearch" ></calendar>

In this way you have your startdate and enddate directly in search page. Let me know if it works, or think another way. Thanks

Extracting first n columns of a numpy matrix

If a is your array:

In [11]: a[:,:2]
Out[11]: 
array([[-0.57098887, -0.4274751 ],
       [-0.22279713, -0.51723555],
       [ 0.67492385, -0.69294472],
       [ 0.41086611,  0.26374238]])

MongoDB: Combine data from multiple collections into one..how?

use multiple $lookup for multiple collections in aggregation

query:

db.getCollection('servicelocations').aggregate([
  {
    $match: {
      serviceLocationId: {
        $in: ["36728"]
      }
    }
  },
  {
    $lookup: {
      from: "orders",
      localField: "serviceLocationId",
      foreignField: "serviceLocationId",
      as: "orders"
    }
  },
  {
    $lookup: {
      from: "timewindowtypes",
      localField: "timeWindow.timeWindowTypeId",
      foreignField: "timeWindowTypeId",
      as: "timeWindow"
    }
  },
  {
    $lookup: {
      from: "servicetimetypes",
      localField: "serviceTimeTypeId",
      foreignField: "serviceTimeTypeId",
      as: "serviceTime"
    }
  },
  {
    $unwind: "$orders"
  },
  {
    $unwind: "$serviceTime"
  },
  {
    $limit: 14
  }
])

result:

{
    "_id" : ObjectId("59c3ac4bb7799c90ebb3279b"),
    "serviceLocationId" : "36728",
    "regionId" : 1.0,
    "zoneId" : "DXBZONE1",
    "description" : "AL HALLAB REST EMIRATES MALL",
    "locationPriority" : 1.0,
    "accountTypeId" : 1.0,
    "locationType" : "SERVICELOCATION",
    "location" : {
        "makani" : "",
        "lat" : 25.119035,
        "lng" : 55.198694
    },
    "deliveryDays" : "MTWRFSU",
    "timeWindow" : [ 
        {
            "_id" : ObjectId("59c3b0a3b7799c90ebb32cde"),
            "timeWindowTypeId" : "1",
            "Description" : "MORNING",
            "timeWindow" : {
                "openTime" : "06:00",
                "closeTime" : "08:00"
            },
            "accountId" : 1.0
        }, 
        {
            "_id" : ObjectId("59c3b0a3b7799c90ebb32cdf"),
            "timeWindowTypeId" : "1",
            "Description" : "MORNING",
            "timeWindow" : {
                "openTime" : "09:00",
                "closeTime" : "10:00"
            },
            "accountId" : 1.0
        }, 
        {
            "_id" : ObjectId("59c3b0a3b7799c90ebb32ce0"),
            "timeWindowTypeId" : "1",
            "Description" : "MORNING",
            "timeWindow" : {
                "openTime" : "10:30",
                "closeTime" : "11:30"
            },
            "accountId" : 1.0
        }
    ],
    "address1" : "",
    "address2" : "",
    "phone" : "",
    "city" : "",
    "county" : "",
    "state" : "",
    "country" : "",
    "zipcode" : "",
    "imageUrl" : "",
    "contact" : {
        "name" : "",
        "email" : ""
    },
    "status" : "ACTIVE",
    "createdBy" : "",
    "updatedBy" : "",
    "updateDate" : "",
    "accountId" : 1.0,
    "serviceTimeTypeId" : "1",
    "orders" : [ 
        {
            "_id" : ObjectId("59c3b291f251c77f15790f92"),
            "orderId" : "AQ18O1704264",
            "serviceLocationId" : "36728",
            "orderNo" : "AQ18O1704264",
            "orderDate" : "18-Sep-17",
            "description" : "AQ18O1704264",
            "serviceType" : "Delivery",
            "orderSource" : "Import",
            "takenBy" : "KARIM",
            "plannedDeliveryDate" : ISODate("2017-08-26T00:00:00.000Z"),
            "plannedDeliveryTime" : "",
            "actualDeliveryDate" : "",
            "actualDeliveryTime" : "",
            "deliveredBy" : "",
            "size1" : 296.0,
            "size2" : 3573.355,
            "size3" : 240.811,
            "jobPriority" : 1.0,
            "cancelReason" : "",
            "cancelDate" : "",
            "cancelBy" : "",
            "reasonCode" : "",
            "reasonText" : "",
            "status" : "",
            "lineItems" : [ 
                {
                    "ItemId" : "BNWB020",
                    "size1" : 15.0,
                    "size2" : 78.6,
                    "size3" : 6.0
                }, 
                {
                    "ItemId" : "BNWB021",
                    "size1" : 20.0,
                    "size2" : 252.0,
                    "size3" : 11.538
                }, 
                {
                    "ItemId" : "BNWB023",
                    "size1" : 15.0,
                    "size2" : 285.0,
                    "size3" : 16.071
                }, 
                {
                    "ItemId" : "CPMW112",
                    "size1" : 3.0,
                    "size2" : 25.38,
                    "size3" : 1.731
                }, 
                {
                    "ItemId" : "MMGW001",
                    "size1" : 25.0,
                    "size2" : 464.375,
                    "size3" : 46.875
                }, 
                {
                    "ItemId" : "MMNB218",
                    "size1" : 50.0,
                    "size2" : 920.0,
                    "size3" : 60.0
                }, 
                {
                    "ItemId" : "MMNB219",
                    "size1" : 50.0,
                    "size2" : 630.0,
                    "size3" : 40.0
                }, 
                {
                    "ItemId" : "MMNB220",
                    "size1" : 50.0,
                    "size2" : 416.0,
                    "size3" : 28.846
                }, 
                {
                    "ItemId" : "MMNB270",
                    "size1" : 50.0,
                    "size2" : 262.0,
                    "size3" : 20.0
                }, 
                {
                    "ItemId" : "MMNB302",
                    "size1" : 15.0,
                    "size2" : 195.0,
                    "size3" : 6.0
                }, 
                {
                    "ItemId" : "MMNB373",
                    "size1" : 3.0,
                    "size2" : 45.0,
                    "size3" : 3.75
                }
            ],
            "accountId" : 1.0
        }, 
        {
            "_id" : ObjectId("59c3b291f251c77f15790f9d"),
            "orderId" : "AQ137O1701240",
            "serviceLocationId" : "36728",
            "orderNo" : "AQ137O1701240",
            "orderDate" : "18-Sep-17",
            "description" : "AQ137O1701240",
            "serviceType" : "Delivery",
            "orderSource" : "Import",
            "takenBy" : "KARIM",
            "plannedDeliveryDate" : ISODate("2017-08-26T00:00:00.000Z"),
            "plannedDeliveryTime" : "",
            "actualDeliveryDate" : "",
            "actualDeliveryTime" : "",
            "deliveredBy" : "",
            "size1" : 28.0,
            "size2" : 520.11,
            "size3" : 52.5,
            "jobPriority" : 1.0,
            "cancelReason" : "",
            "cancelDate" : "",
            "cancelBy" : "",
            "reasonCode" : "",
            "reasonText" : "",
            "status" : "",
            "lineItems" : [ 
                {
                    "ItemId" : "MMGW001",
                    "size1" : 25.0,
                    "size2" : 464.38,
                    "size3" : 46.875
                }, 
                {
                    "ItemId" : "MMGW001-F1",
                    "size1" : 3.0,
                    "size2" : 55.73,
                    "size3" : 5.625
                }
            ],
            "accountId" : 1.0
        }, 
        {
            "_id" : ObjectId("59c3b291f251c77f15790fd8"),
            "orderId" : "AQ110O1705036",
            "serviceLocationId" : "36728",
            "orderNo" : "AQ110O1705036",
            "orderDate" : "18-Sep-17",
            "description" : "AQ110O1705036",
            "serviceType" : "Delivery",
            "orderSource" : "Import",
            "takenBy" : "KARIM",
            "plannedDeliveryDate" : ISODate("2017-08-26T00:00:00.000Z"),
            "plannedDeliveryTime" : "",
            "actualDeliveryDate" : "",
            "actualDeliveryTime" : "",
            "deliveredBy" : "",
            "size1" : 60.0,
            "size2" : 1046.0,
            "size3" : 68.0,
            "jobPriority" : 1.0,
            "cancelReason" : "",
            "cancelDate" : "",
            "cancelBy" : "",
            "reasonCode" : "",
            "reasonText" : "",
            "status" : "",
            "lineItems" : [ 
                {
                    "ItemId" : "MMNB218",
                    "size1" : 50.0,
                    "size2" : 920.0,
                    "size3" : 60.0
                }, 
                {
                    "ItemId" : "MMNB219",
                    "size1" : 10.0,
                    "size2" : 126.0,
                    "size3" : 8.0
                }
            ],
            "accountId" : 1.0
        }
    ],
    "serviceTime" : {
        "_id" : ObjectId("59c3b07cb7799c90ebb32cdc"),
        "serviceTimeTypeId" : "1",
        "serviceTimeType" : "nohelper",
        "description" : "",
        "fixedTime" : 30.0,
        "variableTime" : 0.0,
        "accountId" : 1.0
    }
}

How to get the current URL within a Django template?

You can fetch the URL in your template like this:

<p>URL of this page: {{ request.get_full_path }}</p>

or by

{{ request.path }} if you don't need the extra parameters.

Some precisions and corrections should be brought to hypete's and Igancio's answers, I'll just summarize the whole idea here, for future reference.

If you need the request variable in the template, you must add the 'django.core.context_processors.request' to the TEMPLATE_CONTEXT_PROCESSORS settings, it's not by default (Django 1.4).

You must also not forget the other context processors used by your applications. So, to add the request to the other default processors, you could add this in your settings, to avoid hard-coding the default processor list (that may very well change in later versions):

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP

TEMPLATE_CONTEXT_PROCESSORS = TCP + (
    'django.core.context_processors.request',
)

Then, provided you send the request contents in your response, for example as this:

from django.shortcuts import render_to_response
from django.template import RequestContext

def index(request):
    return render_to_response(
        'user/profile.html',
        { 'title': 'User profile' },
        context_instance=RequestContext(request)
    )

How to make div appear in front of another?

You can set the z-index in css

<div style="z-index: -1"></div>

How do you round UP a number in Python?

I'm basically a beginner at Python, but if you're just trying to round up instead of down why not do:

round(integer) + 1

Matplotlib: Specify format of floats for tick labels

The answer above is probably the correct way to do it, but didn't work for me.

The hacky way that solved it for me was the following:

ax = <whatever your plot is> 
# get the current labels 
labels = [item.get_text() for item in ax.get_xticklabels()]
# Beat them into submission and set them back again
ax.set_xticklabels([str(round(float(label), 2)) for label in labels])
# Show the plot, and go home to family 
plt.show()

How to append multiple items in one line in Python

You could also:

newlist += mylist[i:i+22]

Opening a new tab to read a PDF file

Try this, it worked for me.

<td><a href="Docs/Chapter 1_ORG.pdf" target="pdf-frame">Chapter-1 Organizational</a></td>

How to correctly get image from 'Resources' folder in NetBeans

Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use

    String pathToImageSortBy = "resources/testDataIcons/filling.png";
    ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

But correct way was use name of my project in path to resource

String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

Negative weights using Dijkstra's Algorithm

The algorithm you have suggested will indeed find the shortest path in this graph, but not all graphs in general. For example, consider this graph:

A directed graph with four nodes, A, B, C, and D. Node A has an edge to B of cost 1, an edge to C of cost 0, and an edge to D of cost 99. Node B has an edge to cost 1 to node C. Node D has an edge of cost -300 to node B.

Let's trace through the execution of your algorithm.

  1. First, you set d(A) to 0 and the other distances to 8.
  2. You then expand out node A, setting d(B) to 1, d(C) to 0, and d(D) to 99.
  3. Next, you expand out C, with no net changes.
  4. You then expand out B, which has no effect.
  5. Finally, you expand D, which changes d(B) to -201.

Notice that at the end of this, though, that d(C) is still 0, even though the shortest path to C has length -200. This means that your algorithm doesn't compute the correct distances to all the nodes. Moreover, even if you were to store back pointers saying how to get from each node to the start node A, you'd end taking the wrong path back from C to A.

The reason for this is that Dijkstra's algorithm (and your algorithm) are greedy algorithms that assume that once they've computed the distance to some node, the distance found must be the optimal distance. In other words, the algorithm doesn't allow itself to take the distance of a node it has expanded and change what that distance is. In the case of negative edges, your algorithm, and Dijkstra's algorithm, can be "surprised" by seeing a negative-cost edge that would indeed decrease the cost of the best path from the starting node to some other node.

Hope this helps!

How to apply shell command to each line of a command output?

You can use a for loop:

for file in * ; do
   echo "$file"
done

Note that if the command in question accepts multiple arguments, then using xargs is almost always more efficient as it only has to spawn the utility in question once instead of multiple times.

How do I write a "tab" in Python?

The Python reference manual includes several string literals that can be used in a string. These special sequences of characters are replaced by the intended meaning of the escape sequence.

Here is a table of some of the more useful escape sequences and a description of the output from them.

Escape Sequence       Meaning
\t                    Tab
\\                    Inserts a back slash (\)
\'                    Inserts a single quote (')
\"                    Inserts a double quote (")
\n                    Inserts a ASCII Linefeed (a new line)

Basic Example

If i wanted to print some data points separated by a tab space I could print this string.

DataString = "0\t12\t24"
print (DataString)

Returns

0    12    24

Example for Lists

Here is another example where we are printing the items of list and we want to sperate the items by a TAB.

DataPoints = [0,12,24]
print (str(DataPoints[0]) + "\t" + str(DataPoints[1]) + "\t" + str(DataPoints[2]))

Returns

0    12    24

Raw Strings

Note that raw strings (a string which include a prefix "r"), string literals will be ignored. This allows these special sequences of characters to be included in strings without being changed.

DataString = r"0\t12\t24"
print (DataString)

Returns

0\t12\t24

Which maybe an undesired output

String Lengths

It should also be noted that string literals are only one character in length.

DataString = "0\t12\t24"
print (len(DataString))

Returns

7

The raw string has a length of 9.

How to detect if a browser is Chrome using jQuery?

As a quick addition, and I'm surprised nobody has thought of this, you could use the in operator:

"chrome" in window

Obviously this isn't using JQuery, but I figured I'd put it since it's handy for times when you aren't using any external libraries.

How to get start and end of day in Javascript?

In MomentJs We can declare it like :

   const start = moment().format('YYYY-MM-DD 00:00:01');
   const end = moment().format('YYYY-MM-DD 23:59:59');

How to fix Python Numpy/Pandas installation?

I work with the guys that created Anaconda Python. You can install multiple versions of python and numpy without corrupting your system python. It's free and open source (OSX, linux, Windows). The paid packages are enhancements on top of the free version. Pandas is included.

conda create --name np17py27 anaconda=1.4 numpy=1.7 python=2.7
export PATH=~/anaconda/envs/np17py27/bin:$PATH

If you want numpy 1.6:

conda create --name np16py27 anaconda=1.4 numpy=1.6 python=2.7

Setting your PATH sets up where to find python and ipython. The environments (np17py27) can be named whatever you would like.

Any way of using frames in HTML5?

I have used frames at my continuing education commercial site for over 15 years. Frames allow the navigation frame to load material into the main frame using the target feature while leaving the navigator frame untouched. Furthermore, Perl scripts operate quite well from a frame form returning the output to the same frame. I love frames and will continue using them. CSS is far too complicated for practical use. I have had no problems using frames with HTML5 with IE, Safari, Chrome, or Firefox.

How to get the clicked link's href with jquery?

You're looking for $(this).attr("href");

Renaming the current file in Vim

There's a sightly larger plugin called vim-eunuch by Tim Pope that includes a rename function as well as some other goodies (delete, find, save all, chmod, sudo edit, ...).

To rename a file in vim-eunuch:

:Move filename.ext

Compared to rename.vim:

:rename[!] filename.ext

Saves a few keystrokes :)

JFrame background image

I used a very similar method to @bott, but I modified it a little bit to make there be no need to resize the image:

BufferedImage img = null;
try {
    img = ImageIO.read(new File("image.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}
Image dimg = img.getScaledInstance(800, 508, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(dimg);
setContentPane(new JLabel(imageIcon));

Works every time. You can also get the width and height of the jFrame and use that in place of the 800 and 508 respectively.

PHP salt and hash SHA256 for login password

According to php.net the Salt option has been deprecated as of PHP 7.0.0, so you should use the salt that is generated by default and is far more simpler

Example for store the password:

$hashPassword = password_hash("password", PASSWORD_BCRYPT);

Example to verify the password:

$passwordCorrect = password_verify("password", $hashPassword);

How to open the terminal in Atom?

There are a number of Atom packages which give you access to the terminal from within Atom. Try a few out to find the best option for you.

Some recommendations which work in Ubuntu (with their primary keyboard shortcuts):

Open a terminal in Atom:

Edit: recommended plugin changed as terminal-plus is no longer maintained. Thanks for the head's-up, @MorganRodgers.

If you want to open a terminal panel in Atom, try atom-ide-terminal. Use the keyboard shortcut ctrl-` to open a new terminal instance.

Open an external terminal from Atom:

If you just want a shortcut to open your external terminal from within Atom, try atom-terminal (this is what I use). You can use ctrl-shift-t to open your external terminal in the current file's directory, or alt-shift-t to open the terminal in the project's root directory.

How do I run msbuild from the command line using Windows SDK 7.1?

For Visual Studio 2019 (Preview, at least) it is now in:

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\Current\Bin\MSBuild.exe

I imagine the process will be similar for the official 2019 release.

Linux shell sort file according to the second column?

If this is UNIX:

sort -k 2 file.txt

You can use multiple -k flags to sort on more than one column. For example, to sort by family name then first name as a tie breaker:

sort -k 2,2 -k 1,1 file.txt

Relevant options from "man sort":

-k, --key=POS1[,POS2]

start a key at POS1, end it at POS2 (origin 1)

POS is F[.C][OPTS], where F is the field number and C the character position in the field. OPTS is one or more single-letter ordering options, which override global ordering options for that key. If no key is given, use the entire line as the key.

-t, --field-separator=SEP

use SEP instead of non-blank to blank transition

Sorting an IList in C#

try this  **USE ORDER BY** :

   public class Employee
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

 private static IList<Employee> GetItems()
        {
            List<Employee> lst = new List<Employee>();

            lst.Add(new Employee { Id = "1", Name = "Emp1" });
            lst.Add(new Employee { Id = "2", Name = "Emp2" });
            lst.Add(new Employee { Id = "7", Name = "Emp7" });
            lst.Add(new Employee { Id = "4", Name = "Emp4" });
            lst.Add(new Employee { Id = "5", Name = "Emp5" });
            lst.Add(new Employee { Id = "6", Name = "Emp6" });
            lst.Add(new Employee { Id = "3", Name = "Emp3" });

            return lst;
        }

**var lst = GetItems().AsEnumerable();

            var orderedLst = lst.OrderBy(t => t.Id).ToList();

            orderedLst.ForEach(emp => Console.WriteLine("Id - {0} Name -{1}", emp.Id, emp.Name));**

Printing all global variables/local variables?

Type info variables to list "All global and static variable names".

Type info locals to list "Local variables of current stack frame" (names and values), including static variables in that function.

Type info args to list "Arguments of the current stack frame" (names and values).

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

This Exception

org.springframework.http.converter.HttpMessageNotWritableException

getting because, I hope so, your are sending response output as Serializable object.
This is problem occurring in spring. To over come this issue, send POJO object as response output.

Example :

    @Entity
    @Table(name="user_details")
    public class User implements Serializable{

        @Id
        @GeneratedValue(strategy= GenerationType.IDENTITY)
        @Column(name="id")
        private Integer id;

        @Column(name="user_name")
        private String userName;

        @Column(name="email_id")
        private String emailId;

        @Column(name="phone_no")
        private String phone;

//setter and getters

POJO class:

public class UserVO {

    private int Id;
    private String userName;
    private String emailId;
    private String phone;
    private Integer active;

//setter and getters

In controller convert the serilizable object fields to POJO class fields and return pojo class as output.

         User u= userService.getdetials(); // get data from database

        UserVO userVo= new UserVO();  // created pojo class object

        userVo.setId(u.getId());
        userVo.setEmailId(u.getEmailId());
        userVo.setActive(u.getActive());
        userVo.setPhone(u.getPhone());
        userVo.setUserName(u.getUserName());
       retunr userVo;  //finally send pojo object as output.

Remove empty elements from an array in Javascript

Nice ... very nice We can also replace all array values like this

Array.prototype.ReplaceAllValues = function(OldValue,newValue)
{
    for( var i = 0; i < this.length; i++ )  
    {
        if( this[i] == OldValue )       
        {
            this[i] = newValue;
        }
    }
};

Django Template Variables and Javascript

The {{variable}} is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text.

Having said that, you can put this kind of substitution into your JavaScript.

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}";
</script>

This gives you "dynamic" javascript.

Save byte array to file

You can use:

File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO

If you have an enumerable and not an array, you can use:

File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq

PHP class: Global variable as property in class

Try to avoid globals, instead you can use something like this

class myClass() {
 private $myNumber;

 public function setNumber($number) {
  $this->myNumber = $number;
 }
}

Now you can call

$class = new myClass();
$class->setNumber('1234');

How do I set up Android Studio to work completely offline?

On Android 0.5.1 you can find the offline option in the File / Settings / Gradle (in the Project Settings section)/ Offline work

Do you have to put Task.Run in a method to make it async?

When you use Task.Run to run a method, Task gets a thread from threadpool to run that method. So from the UI thread's perspective, it is "asynchronous" as it doesn't block UI thread.This is fine for desktop application as you usually don't need many threads to take care of user interactions.

However, for web application each request is serviced by a thread-pool thread and thus the number of active requests can be increased by saving such threads. Frequently using threadpool threads to simulate async operation is not scalable for web applications.

True Async doesn't necessarily involving using a thread for I/O operations, such as file / DB access etc. You can read this to understand why I/O operation doesn't need threads. http://blog.stephencleary.com/2013/11/there-is-no-thread.html

In your simple example,it is a pure CPU-bound calculation, so using Task.Run is fine.

C# Base64 String to JPEG Image

public Image Base64ToImage(string base64String)
{
   // Convert Base64 String to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

    // Convert byte[] to Image
    ms.Write(imageBytes, 0, imageBytes.Length);
    Image image = Image.FromStream(ms, true);

    return image;
}

Example use of "continue" statement in Python?

Here is very good visual representation about continue and break statements

Chart

source

A potentially dangerous Request.Form value was detected from the client

As indicated in my comment to Sel's answer, this is our extension to a custom request validator.

public class SkippableRequestValidator : RequestValidator
{
    protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
    {
        if (collectionKey != null && collectionKey.EndsWith("_NoValidation"))
        {
            validationFailureIndex = 0;
            return true;
        }

        return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);
    }
}

vertical alignment of text element in SVG

If you're testing this in IE, dominant-baseline and alignment-baseline are not supported.

The most effective way to center text in IE is to use something like this with "dy":

<text font-size="ANY SIZE" text-anchor="middle" "dy"="-.4em"> Ya Text </text>

The negative value will shift it up and a positive value of dy will shift it down. I've found using -.4em seems a bit more centered vertically to me than -.5em, but you'll be the judge of that.

How do you delete an ActiveRecord object?

  1. User.destroy

User.destroy(1) will delete user with id == 1 and :before_destroy and :after_destroy callbacks occur. For example if you have associated records

has_many :addresses, :dependent => :destroy

After user is destroyed his addresses will be destroyed too. If you use delete action instead, callbacks will not occur.

  1. User.destroy, User.delete

  2. User.destroy_all(<conditions>) or User.delete_all(<conditions>)

Notice: User is a class and user is an instance object

Beginner Python: AttributeError: 'list' object has no attribute

Consider:

class Bike(object):
    def __init__(self, name, weight, cost):
        self.name = name
        self.weight = weight
        self.cost = cost

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),      # <--
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165),    # <--
    }

# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
    profit = bike.cost * margin
    print(profit)

Output:

33.0
20.0

The difference is that in your bikes dictionary, you're initializing the values as lists [...]. Instead, it looks like the rest of your code wants Bike instances. So create Bike instances: Bike(...).

As for your error

AttributeError: 'list' object has no attribute 'cost'

this will occur when you try to call .cost on a list object. Pretty straightforward, but we can figure out what happened by looking at where you call .cost -- in this line:

profit = bike.cost * margin

This indicates that at least one bike (that is, a member of bikes.values() is a list). If you look at where you defined bikes you can see that the values were, in fact, lists. So this error makes sense.

But since your class has a cost attribute, it looked like you were trying to use Bike instances as values, so I made that little change:

[...] -> Bike(...)

and you're all set.

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

The problem has been well-identified. But there's a solution; make doSomething generic:

<T extends Animal> void doSomething<List<T> animals) {
}

now you can call doSomething with either List<Dog> or List<Cat> or List<Animal>.

How do you print in Sublime Text 2

  1. Install the Package Control first and restart your editor. See: How to install plugins to Sublime Text 2 editor?
  2. Install Highlight plugin.
    1. Open the pallete, press ctrl+shift+p (Win, Linux) or cmd+shift+p (OS X).
    2. Type and confirm: Install Package
    3. Type and confirm: Highlight or Print

Also see related printing forum topic: Printing from sublime

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

In my case I'm calling an API hosted by AWS (API Gateway). The error happened when I tried to call the API from a domain other than the API own domain. Since I'm the API owner I enabled CORS for the test environment, as described in the Amazon Documentation.

In production this error will not happen, since the request and the api will be in the same domain.

I hope it helps!

css label width not taking effect

Do display: inline-block:

#report-upload-form label {
    padding-left:26px;
    width:125px;
    text-transform: uppercase;
    display:inline-block
}

http://jsfiddle.net/aqMN4/

How to close the current fragment by using Button like the back button?

From Fragment A, to go to B, replace A with B and use addToBackstack() before commit().

Now From Fragment B, to go to C, first use popBackStackImmediate(), this will bring back A. Now replace A with C, just like the first transaction.

Checking if element exists with Python Selenium

you could use is_displayed() like below

res = driver.find_element_by_id("some_id").is_displayed()
assert res, 'element not displayed!'

How to convert Excel values into buckets?

I use this trick for equal data bucketing. Instead of text result you get the number. Here is example for four buckets. Suppose you have data in A1:A100 range. Put this formula in B1:

=MAX(ROUNDUP(PERCENTRANK($A$1:$A$100,A1) *4,0),1)

Fill down the formula all across B column and you are done. The formula divides the range into 4 equal buckets and it returns the bucket number which the cell A1 falls into. The first bucket contains the lowest 25% of values.

Adjust the number of buckets according to thy wish:

=MAX(ROUNDUP(PERCENTRANK([Range],[OneCellOfTheRangeToTest]) *[NumberOfBuckets],0),1)

The number of observation in each bucket will be equal or almost equal. For example if you have a 100 observations and you want to split it into 3 buckets (like in your example) then the buckets will contain 33, 33, 34 observations. So almost equal. You do not have to worry about that - the formula works that out for you.

How to disable a link using only CSS?

Bootstrap Disabled Link

<a href="#" class="btn btn-primary btn-lg disabled" role="button">Primary link</a>

<a href="#" class="btn btn-default btn-lg disabled" role="button">Link</a>

Bootstrap Disabled Button but it looks like link

<button type="button" class="btn btn-link">Link</button>

How can I pass a parameter to a Java Thread?

This answer comes very late, but maybe someone will find it useful. It is about how to pass a parameter(s) to a Runnable without even declaring named class (handy for inliners):

    String someValue = "Just a demo, really...";

    new Thread(new Runnable() {
        private String myParam;

        public Runnable init(String myParam) {
            this.myParam = myParam;
            return this;
        }

        @Override
        public void run() {
            System.out.println("This is called from another thread.");
            System.out.println(this.myParam);
        }
    }.init(someValue)).start();

Of course you can postpone execution of start to some more convenient or appropriate moment. And it is up to you what will be the signature of init method (so it may take more and/or different arguments) and of course even its name, but basically you get an idea.

In fact there is also another way of passing a parameter to an anonymous class, with the use of the initializer blocks. Consider this:

    String someValue = "Another demo, no serious thing...";
    int anotherValue = 42;

    new Thread(new Runnable() {
        private String myParam;
        private int myOtherParam;
        // instance initializer
        {
            this.myParam = someValue;
            this.myOtherParam = anotherValue;
        }

        @Override
        public void run() {
            System.out.println("This comes from another thread.");
            System.out.println(this.myParam + ", " + this.myOtherParam);
        }
    }).start();

So all happens inside of the initializer block.