Programs & Examples On #Actor

Programming model distinguished by ubiquitous asynchronous communication.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I solved the same issue by following steps:

Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10

After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap

In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",

Now after updating package.json, use the command npm update

After this use command ng serve and my error got resolved

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

// bad
const _getKeyValue = (key: string) => (obj: object) => obj[key];

// better
const _getKeyValue_ = (key: string) => (obj: Record<string, any>) => obj[key];

// best
const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T) =>
  obj[key];

Bad - the reason for the error is the object type is just an empty object by default. Therefore it isn't possible to use a string type to index {}.

Better - the reason the error disappears is because now we are telling the compiler the obj argument will be a collection of string/value (string/any) pairs. However, we are using the any type, so we can do better.

Best - T extends empty object. U extends the keys of T. Therefore U will always exist on T, therefore it can be used as a look up value.

Here is a full example:

I have switched the order of the generics (U extends keyof T now comes before T extends object) to highlight that order of generics is not important and you should select an order that makes the most sense for your function.

const getKeyValue = <U extends keyof T, T extends object>(key: U) => (obj: T) =>
  obj[key];

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "John Smith",
  age: 20
};

const getUserName = getKeyValue<keyof User, User>("name")(user);

// => 'John Smith'

Alternative Syntax

const getKeyValue = <T, K extends keyof T>(obj: T, key: K): T[K] => obj[key];

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I upgraded my IntelliJ Version from 2018.1 to 2018.3.6. It works !

Android Material and appcompat Manifest merger failed

Reason of Fail

You are using material library which is part of AndroidX. If you are not aware of AndroidX, please go through this answer.

One app should use either AndroidX or old Android Support libraries. That's why you faced this issue.

For example -

In your gradle, you are using

  • com.android.support:appcompat-v7 (Part of old --Android Support Library--)
  • com.google.android.material:material (Part of AndroidX) (AndroidX build artifact of com.android.support:design)

Solution

So the solution is to use either AndroidX or old Support Library. I recommend to use AndroidX, because Android will not update support libraries after version 28.0.0. See release notes of Support Library.

Just migrate to AndroidX.Here is my detailed answer to migrate to AndroidX. I am putting here the needful steps from that answer.

Before you migrate, it is strongly recommended to backup your project.

Existing project

  • Android Studio > Refactor Menu > Migrate to AndroidX...
  • It will analysis and will open Refractor window in bottom. Accept changes to be done.

image

New project

Put these flags in your gradle.properties

android.enableJetifier=true
android.useAndroidX=true

Check @Library mappings for equal AndroidX package.

Check @Official page of Migrate to AndroidX

What is Jetifier?

What is AndroidX?

AndroidX - Android Extension Library

From AndroidX documentation

We are rolling out a new package structure to make it clearer which packages are bundled with the Android operating system, and which are packaged with your app's APK. Going forward, the android.* package hierarchy will be reserved for Android packages that ship with the operating system. Other packages will be issued in the new androidx.* package hierarchy as part of the AndroidX library.

Need of AndroidX

AndroidX is a redesigned library to make package names more clear. So from now on android hierarchy will be for only android default classes, which comes with android operating system and other library/dependencies will be part of androidx (makes more sense). So from now on all the new development will be updated in androidx.

com.android.support.** : androidx.
com.android.support:appcompat-v7 : androidx.appcompat:appcompat com.android.support:recyclerview-v7 : androidx.recyclerview:recyclerview com.android.support:design : com.google.android.material:material

Complete Artifact mappings for AndroidX packages

AndroidX uses Semantic-version

Previously, support library used the SDK version but AndroidX uses the Semantic-version. It’s going to re-version from 28.0.0 ? 1.0.0.

How to migrate current project

In Android Studio 3.2 (September 2018), there is a direct option to migrate existing project to AndroidX. This refactor all packages automatically.

Before you migrate, it is strongly recommended to backup your project.

Existing project

  • Android Studio > Refactor Menu > Migrate to AndroidX...
  • It will analyze and will open Refractor window in bottom. Accept changes to be done.

image

New project

Put these flags in your gradle.properties

android.enableJetifier=true
android.useAndroidX=true

Check @Library mappings for equal AndroidX package.

Check @Official page of Migrate to AndroidX

What is Jetifier?

Bugs of migrating

  • If you build app, and find some errors after migrating, then you need to fix those minor errors. You will not get stuck there, because that can be easily fixed.
  • 3rd party libraries are not converted to AndroidX in directory, but they get converted at run time by Jetifier, so don't worry about compile time errors, your app will run perfectly.

Support 28.0.0 is last release?

From Android Support Revision 28.0.0

This will be the last feature release under the android.support packaging, and developers are encouraged to migrate to AndroidX 1.0.0

So go with AndroidX, because Android will update only androidx package from now.

Further Reading

https://developer.android.com/topic/libraries/support-library/androidx-overview

https://android-developers.googleblog.com/2018/05/hello-world-androidx.html

Android design support library for API 28 (P) not working

Important Update

Android will not update support libraries after 28.0.0.

This will be the last feature release under the android.support packaging, and developers are encouraged to migrate to AndroidX 1.0.0.

So use library AndroidX.

  • Don't use both Support and AndroidX in project.
  • Your library module or dependencies can still have support libraries. Androidx Jetifier will handle it.
  • Use stable version of androidx or any library, because alpha, beta, rc can have bugs which you dont want to ship with your app.

In your case

dependencies {
    implementation 'androidx.appcompat:appcompat:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.1'

    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.cardview:cardview:1.0.0'
}

Can not find module “@angular-devkit/build-angular”

I had the same problem, as it did not installed

@angular-devkit/build-angular

The answer which has worked for me was this:

npm i --only=dev

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

May be you are using wrong mysql_connector.

Use connector of same mysql version

Could not find module "@angular-devkit/build-angular"

That's works for me, commit and then:

ng update @angular/cli @angular/core
npm install --save-dev @angular/cli@latest

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

I was trying to create a web application with spring boot and I got the same error. After inspecting I found that I was missing a dependency. So, be sure to add following dependency to your pom.xml file.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency> 

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

It might be related to corruption in Angular Packages or incompatibility of packages.

Please follow the below steps to solve the issue.

Update

ASP.NET Boilerplate suggests here to use yarn because npm has some problems. It is slow and can not consistently resolve dependencies, yarn solves those problems and it is compatible to npm as well.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

This happened to me because I was using:

app.datasource.url=jdbc:mysql://localhost/test

When I replaced url by jdbc-url then it worked:

app.datasource.jdbc-url=jdbc:mysql://localhost/test

'mat-form-field' is not a known element - Angular 5 & Material2

Check the namespace from where we are importing

import { MatDialogModule } from **"@angular/material/dialog";**
import { MatCardModule } from **"@angular/material/card";**
import { MatButtonModule } from **"@angular/material/button";**

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

I found the solution as Its problem with Android Studio 3.1 Canary 6

My backup of Android Studio 3.1 Canary 5 is useful to me and saved my half day.

Now My build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.2'
    defaultConfig {
        applicationId "com.example.demo"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    dataBinding {
        enabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:cardview-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.squareup.retrofit2:retrofit:2.3.0"
    implementation "com.google.code.gson:gson:2.8.2"
    implementation "com.android.support.constraint:constraint-layout:1.0.2"
    implementation "com.squareup.retrofit2:converter-gson:2.3.0"
    implementation "com.squareup.okhttp3:logging-interceptor:3.6.0"
    implementation "com.squareup.picasso:picasso:2.5.2"
    implementation "com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3"
    compile 'com.github.elevenetc:badgeview:v1.0.0'
    annotationProcessor 'com.github.elevenetc:badgeview:v1.0.0'
    testImplementation "junit:junit:4.12"
    androidTestImplementation("com.android.support.test.espresso:espresso-core:3.0.1", {
        exclude group: "com.android.support", module: "support-annotations"
    })
}

and My gradle is:

classpath 'com.android.tools.build:gradle:3.1.0-alpha06'

and its working finally.

I think there problem in Android Studio 3.1 Canary 6

Thank you all for your time.

How to start up spring-boot application via command line?

Spring Boot provide the plugin with maven.

So you can go to your project directory and run

mvn spring-boot:run

This command line run will be easily when you're using spring-boot-devs-tool with auto reload/restart when you have changed you application.

Exception : AAPT2 error: check logs for details

I made a stupid mistake. In my case, I made the project path too deep. Like this: C:\Users\Administrator\Desktop\Intsig_Android_BCRSDK_AndAS_V1.11.18_20180719\Intsig_Android_BCRScanSDK_AndAS_V1.10.1.20180711\project\as\AS_BcrScanCallerSvn2

Please migrate the project to the correct workspace. Hope this helps someone in future.

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

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    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'
        }
    }
}

And clean the project.

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

In this section, you must enter the component that is used as a child in addition to declarations: [CityModalComponent](modal components) in the following section in the app.module.ts file:

 entryComponents: [
CityModalComponent
],

Angular: Cannot Get /

See this answer here. You need to redirect all routes that Node is not using to Angular:

app.get('*', function(req, res) {
  res.sendfile('./server/views/index.html')
})

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

I got the same problem after creating a new TestCase: Eclipse -> New -> JUnit Test Case. It creates a class without access level modifier. I could solve the problem by just putting a public before the class keyword.

No converter found capable of converting from type to type

Return ABDeadlineType from repository:

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<ABDeadlineType> findAllSummarizedBy();
}

and then convert to DeadlineType. Manually or use mapstruct.

Or call constructor from @Query annotation:

public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {

    @Query("select new package.DeadlineType(a.id, a.code) from ABDeadlineType a ")
    List<DeadlineType> findAllSummarizedBy();
}

Or use @Projection:

@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {

    @Value("#{target.id}")
    String getId();

    @Value("#{target.code}")
    String getText();

}

Update: Spring can work without @Projection annotation:

public interface DeadlineType {
    String getId();    
    String getText();
}

VSCode cannot find module '@angular/core' or any other modules

I was facing the same issue , there could be two reasons for this-

  1. Your src base folder might not been declared, to resolve this go to tsconfig.json and add the baseUrl as "src"
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "src",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}
  1. you might have problem in npm , To resolve this , open your command window and run-npm install

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Spring Boot 2.2.2 / Gradle:

Gradle (build.gradle):

implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")

Entity (User.class):

LocalDate dateOfBirth;

Code:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
User user = mapper.readValue(json, User.class);

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

In ASPNET Core you do it in Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}

where your connection is defined in appsettings.json

{
  "ConnectionStrings": {
    "BloggingDatabase": "..."
  },
}

Example from MS docs

Unable to create migrations after upgrading to ASP.NET Core 2.0

I ran into same problem. I have two projects in the solution. which

  1. API
  2. Services and repo, which hold context models

Initially, API project was set as Startup project.

I changed the Startup project to the one which holds context classes. if you are using Visual Studio you can set a project as Startup project by:

open solution explorer >> right-click on context project >> select Set as Startup project

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

For me I put my dependencies in the wrong spot.

buildscript {
  dependencies {
    //Don't put dependencies here.
  }
}

dependencies {
 //Put them here
}

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

Two Solutions:

  1. Make Sure if you have some binding variables then move that code to settimeout( { }, 0);
  2. Move your related code to ngAfterViewInit method

No String-argument constructor/factory method to deserialize from String value ('')

This exception says that you are trying to deserialize the object "Address" from string "\"\"" instead of an object description like "{…}". The deserializer can't find a constructor of Address with String argument. You have to replace "" by {} to avoid this error.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

I also have the same error. I have updated the jackson library version and error has gone.

<!-- Jackson to convert Java object to Json -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.4</version>
        </dependency>
    </dependencies>

and also check your data classes that have you created getters and setters for all the properties.

How to run shell script file using nodejs?

you can go:

var cp = require('child_process');

and then:

cp.exec('./myScript.sh', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a command in your $SHELL.
Or go

cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a file WITHOUT a shell.
Or go

cp.execFile();

which is the same as cp.exec() but doesn't look in the $PATH.

You can also go

cp.fork('myJS.js', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a javascript file with node.js, but in a child process (for big programs).

EDIT

You might also have to access stdin and stdout with event listeners. e.g.:

var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
  // handle stdout as `data`
});

How to enable CORS in ASP.net Core WebAPI

Just to add to answer here, if you are using app.UseHttpsRedirection(), and you are hitting not SSL port consider commenting out this.

RestClientException: Could not extract response. no suitable HttpMessageConverter found

I was trying to use Feign, while I encounter same issue, As I understood HTTP message converter will help but wanted to understand how to achieve this.

@FeignClient(name = "mobilesearch", url = "${mobile.search.uri}" ,
        fallbackFactory = MobileSearchFallbackFactory.class,
        configuration = MobileSearchFeignConfig.class)
public interface MobileSearchClient {

    @RequestMapping(method = RequestMethod.GET)
    List<MobileSearchResponse> getPhones();
}

You have to use Customer Configuration for the decoder, MobileSearchFeignConfig,

public class MobileSearchFeignConfig {

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }


    @Bean
    public Decoder feignDecoder() {
        return new ResponseEntityDecoder(new SpringDecoder(feignHttpMessageConverter()));
    }

    public ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
        final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(new MappingJackson2HttpMessageConverter());
        return new ObjectFactory<HttpMessageConverters>() {
            @Override
            public HttpMessageConverters getObject() throws BeansException {
                return httpMessageConverters;
            }
        };
    }

    public class MappingJackson2HttpMessageConverter extends org.springframework.http.converter.json.MappingJackson2HttpMessageConverter {
        MappingJackson2HttpMessageConverter() {
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.valueOf(MediaType.TEXT_HTML_VALUE + ";charset=UTF-8"));
            setSupportedMediaTypes(mediaTypes);
        }
    }

}

Android Studio - Failed to notify project evaluation listener error

I enabled "Offline-Work" under File -> Settings ->Build,Deploy, Exec -> Gradle And this finally resolved the issue for me.

Jersey stopped working with InjectionManagerFactory not found

As far as I can see dependencies have changed between 2.26-b03 and 2.26-b04 (HK2 was moved to from compile to testCompile)... there might be some change in the jersey dependencies that has not been completed yet (or which lead to a bug).

However, right now the simple solution is to stick to an older version :-)

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I Had the same issue and finally discovered the reason. In my case it was a badly written Java method:

@FormUrlEncoded
@POST("register-user/")
Call<RegisterUserApiResponse> registerUser(
        @Field("email") String email,
        @Field("password") String password,            
        @Field("date") String birthDate,
);

Note the illegal comma after the "date" field. For some reason the compiler could not reveal this exact error, and came with the ':app:compileDebugKotlin'. > Compilation error thing.

Error: the entity type requires a primary key

I came here with similar error:

System.InvalidOperationException: 'The entity type 'MyType' requires a primary key to be defined.'

After reading answer by hvd, realized I had simply forgotten to make my key property 'public'. This..

namespace MyApp.Models.Schedule
{
    public class MyType
    {
        [Key]
        int Id { get; set; }

        // ...

Should be this..

namespace MyApp.Models.Schedule
{
    public class MyType
    {
        [Key]
        public int Id { get; set; }  // must be public!

        // ...

How to re-render flatlist?

I have replaced FlatList with SectionList and it is updates properly on state change.

<SectionList
  keyExtractor={(item) => item.entry.entryId} 
  sections={section}
  renderItem={this.renderEntries.bind(this)}
  renderSectionHeader={() => null}
/>

The only thing need to keep in mind is that section have diff structure:

const section = [{
  id: 0,
  data: this.state.data,
}]

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

I had the same problem and I solved the problem in another way, without import ReactiveFormsModule. You may be but this block in

ngOnInt(){

    userForm = new FormGroup({
        name: new FormControl(),
        email: new FormControl(),
        adresse: new FormGroup({
            rue: new FormControl(),
            ville: new FormControl(),
            cp: new FormControl(),
        })
     });
)

App.settings - the Angular way?

Poor man's configuration file:

Add to your index.html as first líne in the body tag:

<script lang="javascript" src="assets/config.js"></script>

Add assets/config.js:

var config = {
    apiBaseUrl: "http://localhost:8080"
}

Add config.ts:

export const config: AppConfig = window['config']

export interface AppConfig {
    apiBaseUrl: string
}

Hibernate Error executing DDL via JDBC Statement

I got this same error when i was trying to make a table with name "admin". Then I used @Table annotation and gave table a different name like @Table(name = "admins"). I think some words are reserved (like :- keywords in java) and you can not use them.

@Entity
@Table(name = "admins")
public class Admin extends TrackedEntity {

}

'Field required a bean of type that could not be found.' error spring restful API using mongodb

Normally we can solve this problem in two aspects:

  1. proper annotation should be used for Spring Boot scanning the bean, like @Component;
  2. the scanning path will include the classes just as all others mentioned above.

By the way, there is a very good explanation for the difference among @Component, @Repository, @Service, and @Controller.

CORS: credentials mode is 'include'

If it helps, I was using centrifuge with my reactjs app, and, after checking some comments below, I looked at the centrifuge.js library file, which in my version, had the following code snippet:

if ('withCredentials' in xhr) {
 xhr.withCredentials = true;
}

After I removed these three lines, the app worked fine, as expected.

Hope it helps!

Cannot find module '@angular/compiler'

Try to delete that "angular/cli": "1.0.0-beta.28.3", in the devDependencies it is useless , and add instead of it "@angular/compiler-cli": "^2.3.1", (since it is the current version, else add it by npm i --save-dev @angular/compiler-cli ), then in your root app folder run those commands:

  1. rm -r node_modules (or delete your node_modules folder manually)
  2. npm cache clean (npm > v5 add --force so: npm cache clean --force)
  3. npm install

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment as you can see above).

Try checking to see if Hibernate core is put in as dependency:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.0.11.Final</version>
  <scope>compile</scope>
</dependency>

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

i solved this problem by removing space between quotes and command value inside of array ,this is happened because container exited after started and no executable command present which to be run inside of container.

['sh', '-c', 'echo Hello Kubernetes! && sleep 3600']

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

You need to add dynamically created components to entryComponents inside your @NgModule

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent,
    HomeComponent,
    DialogResultExampleDialog        
  ],
  entryComponents: [DialogResultExampleDialog]

Note: In some cases entryComponents under lazy loaded modules will not work, as a workaround put them in your app.module (root)

UnsatisfiedDependencyException: Error creating bean with name

That was the version incompatibility where their was the inclusion of lettuce. When i excluded , it worked for me.

<!--Spring-Boot 2.0.0 -->
    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <exclusions>
                    <exclusion>
                        <groupId>io.lettuce</groupId>
                        <artifactId>lettuce-core</artifactId>
                    </exclusion>
                </exclusions>    
            </dependency>
            <dependency>
                <groupId>redis.clients</groupId>
                <artifactId>jedis</artifactId>
            </dependency>

How to upgrade Angular CLI project?

JJB's answer got me on the right track, but the upgrade didn't go very smoothly. My process is detailed below. Hopefully the process becomes easier in the future and JJB's answer can be used or something even more straightforward.

Solution Details

I have followed the steps captured in JJB's answer to update the angular-cli precisely. However, after running npm install angular-cli was broken. Even trying to do ng version would produce an error. So I couldn't do the ng init command. See error below:

$ ng init
core_1.Version is not a constructor
TypeError: core_1.Version is not a constructor
    at Object.<anonymous> (C:\_git\my-project\code\src\main\frontend\node_modules\@angular\compiler-cli\src\version.js:18:19)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    ...

To be able to use any angular-cli commands, I had to update my package.json file by hand and bump the @angular dependencies to 2.4.1, then do another npm install.

After this I was able to do ng init. I updated my configuration files, but none of my app/* files. When this was done, I was still getting errors. The first one is detailed below, the second was the same type of error but in a different file.

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 62:9 in the original .ts file), resolving symbol AppModule in C:/_git/my-project/code/src/main/frontend/src/app/app.module.ts

This error is tied to the following factory provider in my AppModule

{ provide: Http, useFactory: 
    (backend: XHRBackend, options: RequestOptions, router: Router, navigationService: NavigationService, errorService: ErrorService) => {
    return new HttpRerouteProvider(backend, options, router, navigationService, errorService);  
  }, deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
}

To address this error, I had use an exported function and made the following change to the provider.

    { 
      provide: Http, 
      useFactory: httpFactory, 
      deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
    }

... // elsewhere in AppModule

export function httpFactory(backend: XHRBackend, 
                            options: RequestOptions, 
                            router: Router, 
                            navigationService: NavigationService, 
                            errorService: ErrorService) {
  return new HttpRerouteProvider(backend, options, router, navigationService, errorService);
}

Summary

To summarize what I understand to be the most important details, the following changes were required:

  1. Update angular-cli version using the steps detailed in JJB's answer (and on their github page).

  2. Updating @angular version by hand, 2.0.0 did not seem to be supported by angular-cli version 1.0.0-beta.24

  3. With the assistance of angular-cli and the ng init command, I updated my configuration files. I think the critical changes were to angular-cli.json and package.json. See configuration file changes at the bottom.

  4. Make code changes to export functions before I reference them, as captured in the solution details.

Key Configuration Changes

angular-cli.json changes

{
  "project": {
    "version": "1.0.0-beta.16",
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": "assets",
...

changed to...

{
  "project": {
    "version": "1.0.0-beta.24",
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
...

My package.json looks like this after a manual merge that considers the versions used by ng-init. Note my angular version is not 2.4.1, but the change I was after was component inheritance which was introduced in 2.3, so I was fine with these versions. The original package.json is in the question.

{
  "name": "frontend",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor",
    "build": "ng build",
    "buildProd": "ng build --env=prod"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.3.1",
    "@angular/compiler": "^2.3.1",
    "@angular/core": "^2.3.1",
    "@angular/forms": "^2.3.1",
    "@angular/http": "^2.3.1",
    "@angular/platform-browser": "^2.3.1",
    "@angular/platform-browser-dynamic": "^2.3.1",
    "@angular/router": "^3.3.1",
    "@angular/material": "^2.0.0-beta.1",
    "@types/google-libphonenumber": "^7.4.8",
    "angular2-datatable": "^0.4.2",
    "apollo-client": "^0.4.22",
    "core-js": "^2.4.1",
    "rxjs": "^5.0.1",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.7.2",
    "google-libphonenumber": "^2.0.4",
    "graphql-tag": "^0.1.15",
    "hammerjs": "^2.0.8",
    "ng2-bootstrap": "^1.1.16"
  },
  "devDependencies": {
    "@types/hammerjs": "^2.0.33",
    "@angular/compiler-cli": "^2.3.1",
    "@types/jasmine": "2.5.38",
    "@types/lodash": "^4.14.39",
    "@types/node": "^6.0.42",
    "angular-cli": "1.0.0-beta.24",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.0.2",
    "typescript": "~2.0.3",
    "typings": "1.4.0"
  }
}

How to import js-modules into TypeScript file?

I've been facing this problem for long but what this solves my problem Go inside the tsconfig.json and add the following under compilerOptions

{
  "compilerOptions": {
      ...
      "allowJs": true
      ...
  }
}

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

I would simply delete from schema_version the migration/s that deviates from migrations to be applied. This way you don't throw away any test data that you might have.

For example:

SELECT * from schema_version order by installed_on desc

V_005_five.sql
V_004_four.sql
V_003_three.sql
V_002_two.sql
V_001_one.sql

Migrations to be applied

V_005_five.sql
* V_004_addUserTable.sql *
V_003_three.sql
V_002_two.sql
V_001_one.sql

Solution here is to delete from schema_version

V_005_five.sql
V_004_four.sql

AND revert any database changes caused. for example if schema created new table then you must drop that table before you run you migrations.

when you run flyway it will only re apply

V_005_five.sql
* V_004_addUserTable.sql *

new schema_version will be

V_005_five.sql
* V_004_addUserTable.sql *
V_003_three.sql
V_002_two.sql
V_001_one.sql

Hope it helps

can not find module "@angular/material"

Follow these steps to begin using Angular Material.

Step 1: Install Angular Material

npm install --save @angular/material

Step 2: Animations

Some Material components depend on the Angular animations module in order to be able to do more advanced transitions. If you want these animations to work in your app, you have to install the @angular/animations module and include the BrowserAnimationsModule in your app.

npm install --save @angular/animations

Then

import {BrowserAnimationsModule} from '@angular/platform browser/animations';

@NgModule({
...
  imports: [BrowserAnimationsModule],
...
})
export class PizzaPartyAppModule { }

Step 3: Import the component modules

Import the NgModule for each component you want to use:

import {MdButtonModule, MdCheckboxModule} from '@angular/material';

@NgModule({
...
imports: [MdButtonModule, MdCheckboxModule],
...
 })
 export class PizzaPartyAppModule { }

be sure to import the Angular Material modules after Angular's BrowserModule, as the import order matters for NgModules

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

import {MdCardModule} from '@angular/material';
@NgModule({
    declarations: [
        AppComponent,
        HeaderComponent,
        HomeComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        MdCardModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

Step 4: Include a theme

Including a theme is required to apply all of the core and theme styles to your application.

To get started with a prebuilt theme, include the following in your app's index.html:

<link href="../node_modules/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">

How to use fetch in typescript

Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.

That being said, the following works...

 fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json())
      .then((res: Actor) => {
          // res is now an Actor
      });

I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...

callBack: (response: any) => void

But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...

fetch(`http://swapi.co/api/people/1/`)
  .then(res => res.json())
  .then(res => {
      if (callback) {
        callback(res);    // Client receives the response as desired type.  
      }
  });

So that a client can call it with a callback like...

(response: IApigeeResponse) => {
    // Process response as an IApigeeResponse
}

Retrofit 2: Get JSON from Response body

add dependency for retrofit2

compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

create class for base url

public class ApiClient     
{
public static final String BASE_URL = "base_url";

private static Retrofit retrofit = null;

public static Retrofit getClient() {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

}

after that create class model to get value

public class ApprovalModel {

@SerializedName("key_parameter")
private String approvalName;
public String getApprovalName() {
    return approvalName;
}
}

create interface class

public interface ApiInterface { 
@GET("append_url")
Call<CompanyDetailsResponse> getCompanyDetails();
}

after that in main class

 if(Connectivity.isConnected(mContext)){
            final ProgressDialog mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.show();

            ApiInterface apiService =
                    ApiClient.getClient().create(ApiInterface.class);

            Call<CompanyDetailsResponse> call = apiService.getCompanyDetails();
            call.enqueue(new Callback<CompanyDetailsResponse>() {
                @Override
                public void onResponse(Call<CompanyDetailsResponse>call, Response<CompanyDetailsResponse> response) {
                    mProgressDialog.dismiss();
                    if(response!=null && response.isSuccessful()) {
                        List<CompanyDetails> companyList = response.body().getCompanyDetailsList();

                        if (companyList != null&&companyList.size()>0) {
                            for (int i = 0; i < companyList.size(); i++) {
                                Log.d(TAG, "" + companyList.get(i));
                            }
                         //get values
                        }else{
                            //show alert not get value
                        }
                    }else{
                        //show error message

                    }
                }

                @Override
                public void onFailure(Call<CompanyDetailsResponse>call, Throwable t) {
                    // Log error here since request failed
                    Log.e(TAG, t.toString());
                    mProgressDialog.dismiss();
                }
            });
        }else{
            //network error alert box

        }

Center Plot title in ggplot2

As stated in the answer by Henrik, titles are left-aligned by default starting with ggplot 2.2.0. Titles can be centered by adding this to the plot:

theme(plot.title = element_text(hjust = 0.5))

However, if you create many plots, it may be tedious to add this line everywhere. One could then also change the default behaviour of ggplot with

theme_update(plot.title = element_text(hjust = 0.5))

Once you have run this line, all plots created afterwards will use the theme setting plot.title = element_text(hjust = 0.5) as their default:

theme_update(plot.title = element_text(hjust = 0.5))
ggplot() + ggtitle("Default is now set to centered")

enter image description here

To get back to the original ggplot2 default settings you can either restart the R session or choose the default theme with

theme_set(theme_gray())

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

If a bean is in the same package in which it is @Autowired, then it will never cause such an issue. However, beans are not accessible from different packages by default. To fix this issue follow these steps :

  1. Import following in your main class:
    import org.springframework.context.annotation.ComponentScan;
  2. add annotation over your main class :
@ComponentScan(basePackages = {"your.company.domain.package"})
public class SpringExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringExampleApplication.class, args);
    }
}

How to serve up images in Angular2?

Just put your images in the assets folder refer them in your html pages or ts files with that link.

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

The problem might be because of package conflicts. When you use @Id annotation in an entity, it might use the @Id of Spring framework; however, it must use @Id annotation of persistence API.

So use @javax.persistence.Id annotation in entities.

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

This issue started occurring for me all of a sudden, so I was sure, there could be some other reason. On digging deep, it was a simple issue where I used http in the BaseUrl of Retrofit instead of https. So changing it to https solved the issue for me.

Error: Unexpected value 'undefined' imported by the module

Just putting the provider inside the forRoot works: https://github.com/ocombe/ng2-translate

@NgModule({
  imports: [BrowserModule, HttpModule, RouterModule.forRoot(routes), /* AboutModule, HomeModule, SharedModule.forRoot()*/
          FormsModule,
          ReactiveFormsModule,
          //third-party
          TranslateModule.forRoot({
            provide: TranslateLoader,
            useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
            deps: [Http]
          })
          //third-party PRIMENG
          ,CalendarModule,DataTableModule,DialogModule,PanelModule
  ],
  declarations: [
    AppComponent,ThemeComponent, ToolbarComponent, RemoveHostTagDirective,
    HomeComponent,MessagesExampleComponent,PrimeNgHomeComponent,CalendarComponent,Ng2BootstrapExamplesComponent,DatepickerDemoComponent,UserListComponent,UserEditComponent,ContractListComponent,AboutComponent
  ],
  providers: [
    {
      provide: APP_BASE_HREF,
      useValue: '<%= APP_BASE %>'
    },
    // FormsModule,
    ReactiveFormsModule,
    { provide : MissingTranslationHandler, useClass: TranslationNotFoundHandler},
    AuthGuard,AppConfigService,AppConfig,
    DateHelper
  ],
  bootstrap: [AppComponent]
})

export class AppModule { }

How do I access Configuration in any class in ASP.NET Core?

Update

Using ASP.NET Core 2.0 will automatically add the IConfiguration instance of your application in the dependency injection container. This also works in conjunction with ConfigureAppConfiguration on the WebHostBuilder.

For example:

public static void Main(string[] args)
{
    var host = WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(builder =>
        {
            builder.AddIniFile("foo.ini");
        })
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

It's just as easy as adding the IConfiguration instance to the service collection as a singleton object in ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
   services.AddSingleton<IConfiguration>(Configuration);

   // ...
}

Where Configuration is the instance in your Startup class.

This allows you to inject IConfiguration in any controller or service:

public class HomeController
{
   public HomeController(IConfiguration configuration)
   {
      // Use IConfiguration instance
   }
}

How to register multiple implementations of the same interface in Asp.Net Core?

I've faced the same issue and want to share how I solved it and why.

As you mentioned there are two problems. The first:

In Asp.Net Core how do I register these services and resolve it at runtime based on some key?

So what options do we have? Folks suggest two:

  • Use a custom factory (like _myFactory.GetServiceByKey(key))

  • Use another DI engine (like _unityContainer.Resolve<IService>(key))

Is the Factory pattern the only option here?

In fact both options are factories because each IoC Container is also a factory (highly configurable and complicated though). And it seems to me that other options are also variations of the Factory pattern.

So what option is better then? Here I agree with @Sock who suggested using custom factory, and that is why.

First, I always try to avoid adding new dependencies when they are not really needed. So I agree with you in this point. Moreover, using two DI frameworks is worse than creating custom factory abstraction. In the second case you have to add new package dependency (like Unity) but depending on a new factory interface is less evil here. The main idea of ASP.NET Core DI, I believe, is simplicity. It maintains a minimal set of features following KISS principle. If you need some extra feature then DIY or use a corresponding Plungin that implements desired feature (Open Closed Principle).

Secondly, often we need to inject many named dependencies for single service. In case of Unity you may have to specify names for constructor parameters (using InjectionConstructor). This registration uses reflection and some smart logic to guess arguments for the constructor. This also may lead to runtime errors if registration does not match the constructor arguments. From the other hand, when using your own factory you have full control of how to provide the constructor parameters. It's more readable and it's resolved at compile-time. KISS principle again.

The second problem:

How can _serviceProvider.GetService() inject appropriate connection string?

First, I agree with you that depending on new things like IOptions (and therefore on package Microsoft.Extensions.Options.ConfigurationExtensions) is not a good idea. I've seen some discussing about IOptions where there were different opinions about its benifit. Again, I try to avoid adding new dependencies when they are not really needed. Is it really needed? I think no. Otherwise each implementation would have to depend on it without any clear need coming from that implementation (for me it looks like violation of ISP, where I agree with you too). This is also true about depending on the factory but in this case it can be avoided.

The ASP.NET Core DI provides a very nice overload for that purpose:

var mongoConnection = //...
var efConnection = //...
var otherConnection = //...
services.AddTransient<IMyFactory>(
             s => new MyFactoryImpl(
                 mongoConnection, efConnection, otherConnection, 
                 s.GetService<ISomeDependency1>(), s.GetService<ISomeDependency2>())));

How to enable TLS 1.2 in Java 7

You should probably be looking to the configuration that controls the underlying platform TLS implementation via -Djdk.tls.client.protocols=TLSv1.2.

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

Following up on Radmin's excellent answer, there is a little tweak needed for everyone who is using angular-cli version 1.0.0-beta.22 and above.

COMPILER_PROVIDERScan no longer be imported (for details see angular-cli GitHub).

So the workaround there is to not use COMPILER_PROVIDERS and JitCompiler in the providers section at all, but use JitCompilerFactory from '@angular/compiler' instead like this inside the type builder class:

private compiler: Compiler = new JitCompilerFactory([{useDebug: false, useJit: true}]).createCompiler();

As you can see, it is not injectable and thus has no dependencies with the DI. This solution should also work for projects not using angular-cli.

Node.js heap out of memory

In my case, I upgraded node.js version to latest (version 12.8.0) and it worked like a charm.

What is the difference between Task.Run() and Task.Factory.StartNew()

Apart from the similarities i.e. Task.Run() being a shorthand for Task.Factory.StartNew(), there is a minute difference between their behaviour in case of sync and async delegates.

Suppose there are following two methods:

public async Task<int> GetIntAsync()
{
    return Task.FromResult(1);
}

public int GetInt()
{
    return 1;
}

Now consider the following code.

var sync1 = Task.Run(() => GetInt());
var sync2 = Task.Factory.StartNew(() => GetInt());

Here both sync1 and sync2 are of type Task<int>

However, difference comes in case of async methods.

var async1 = Task.Run(() => GetIntAsync());
var async2 = Task.Factory.StartNew(() => GetIntAsync());

In this scenario, async1 is of type Task<int>, however async2 is of type Task<Task<int>>

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I could resolve it by overriding Configuration in MyContext through adding connection string to the DbContextOptionsBuilder:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json")
               .Build();
            var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
            optionsBuilder.UseSqlServer(connectionString);
        }
    }

What does 'Unsupported major.minor version 52.0' mean, and how do I fix it?

You don't need to change the compliance level here, or rather, you should but that's not the issue.

The code compliance ensures your code is compatible with a given Java version.

For instance, if you have a code compliance targeting Java 6, you can't use Java 7's or 8's new syntax features (e.g. the diamond, the lambdas, etc. etc.).

The actual issue here is that you are trying to compile something in a Java version that seems different from the project dependencies in the classpath.

Instead, you should check the JDK/JRE you're using to build.

In Eclipse, open the project properties and check the selected JRE in the Java build path.

If you're using custom Ant (etc.) scripts, you also want to take a look there, in case the above is not sufficient per se.

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

My Simple Answer is and only solution...

Please Check The layout files, which you added lastly there MUST be a error in the .xml file for sure.

We may simply copy and pasting .xml file from other project and something missing in the xml file..

Error in the .xml file would be some of the below....

  1. Something missing in Drawable folder or String.xml Or Dimen.xml...

After Placing all the available code in the respected folders do not forget to CLEAN The Project...

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

ReactJS: Warning: setState(...): Cannot update during an existing state transition

I got the same error when I was calling

this.handleClick = this.handleClick.bind(this);

in my constructor when handleClick didn't exist

(I had erased it and had accidentally left the "this" binding statement in my constructor).

Solution = remove the "this" binding statement.

Service located in another namespace

To access services in two different namespaces you can use url like this:

HTTP://<your-service-name>.<namespace-with-that-service>.svc.cluster.local

To list out all your namespaces you can use:

kubectl get namespace

And for service in that namespace you can simply use:

kubectl get services -n <namespace-name>

this will help you.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

How to run bootRun with spring profile via gradle task

For those folks using Spring Boot 2.0+, you can use the following to setup a task that will run the app with a given set of profiles.

task bootRunDev(type: org.springframework.boot.gradle.tasks.run.BootRun, dependsOn: 'build') {
    group = 'Application'

    doFirst() {
        main = bootJar.mainClassName
        classpath = sourceSets.main.runtimeClasspath
        systemProperty 'spring.profiles.active', 'dev'
    }
}

Then you can simply run ./gradlew bootRunDev or similar from your IDE.

SyntaxError: Use of const in strict mode?

Usually this error occurs when the version of node against which the code is being executed is older than expected. (i.e. 0.12 or older).

if you are using nvm than please ensure that you have the right version of node being used. You can check the compatibility on node.green for const under strict mode

I found a similar issue on another post and posted my answer there in detail

Failed to load ApplicationContext (with annotation)

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT

...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

There was conflict in java version. Resolved after using 1.8 for maven.

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Cause: The error occurred since hibernate is not able to connect to the database.
Solution:
1. Please ensure that you have a database present at the server referred to in the configuration file eg. "hibernatedb" in this case.
2. Please see if the username and password for connecting to the db are correct.
3. Check if relevant jars required for the connection are mapped to the project.

Could not autowire field:RestTemplate in Spring boot application

Please make sure two things:

1- Use @Bean annotation with the method.

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
    return builder.build();
}

2- Scope of this method should be public not private.

Complete Example -

@Service
public class MakeHttpsCallImpl implements MakeHttpsCall {

@Autowired
private RestTemplate restTemplate;

@Override
public String makeHttpsCall() {
    return restTemplate.getForObject("https://localhost:8085/onewayssl/v1/test",String.class);
}

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
    return builder.build();
}
}

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

I have just written this code into gradle.properties and it is ok now

org.gradle.jvmargs=-XX:MaxHeapSize\=2048m -Xmx2048m

Having services in React application

I needed some formatting logic to be shared across multiple components and as an Angular developer also naturally leaned towards a service.

I shared the logic by putting it in a separate file

function format(input) {
    //convert input to output
    return output;
}

module.exports = {
    format: format
};

and then imported it as a module

import formatter from '../services/formatter.service';

//then in component

    render() {

        return formatter.format(this.props.data);
    }

cannot redeclare block scoped variable (typescript)

For those coming here in this age, here is a simple solution to this issue. It at least worked for me in the backend. I haven't checked with the frontend code.

Just add:

export {};

at the top of your code.

Credit to EUGENE MURAVITSKY

Remove legend ggplot 2.2

If your chart uses both fill and color aesthetics, you can remove the legend with:

+ guides(fill=FALSE, color=FALSE)

Response to preflight request doesn't pass access control check

For those are using Lambda Integrated Proxy with API Gateway. You need configure your lambda function as if you are submitting your requests to it directly, meaning the function should set up the response headers properly. (If you are using custom lambda functions, this will be handled by the API Gateway.)

//In your lambda's index.handler():
exports.handler = (event, context, callback) => {
     //on success:
     callback(null, {
           statusCode: 200,
           headers: {
                "Access-Control-Allow-Origin" : "*"
           }
     }
}

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

this is a version problem change version > 2.4 to 1.9 solve it

<dependency>  
<groupId>com.fasterxml.jackson.jaxrs</groupId>  
<artifactId>jackson-jaxrs-xml-provider</artifactId>  
<version>2.4.1</version>  

to

<dependency>  
<groupId>org.codehaus.jackson</groupId>  
<artifactId>jackson-mapper-asl</artifactId>  
<version>1.9.4</version>  

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

This is probably due to its lack of connections to the Hive Meta Store,my hive Meta Store is stored in Mysql,so I need to visit Mysql,So I add a dependency in my build.sbt

libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.38"

and the problem is solved!

configuring project ':app' failed to find Build Tools revision

also try to increase gradle version in your project's build.gradle. It helped me

What is the difference between React Native and React?

React vs React Native

ReactJS

  • React is used for creating websites, web apps, SPAs etc.

  • React is a Javascript library used for creating UI hierarchy.

  • It is responsible for rendering of UI components, It is considered as V part Of MVC framework.

  • React’s virtual DOM is faster than the conventional full refresh model, since the virtual DOM refreshes only parts of the page, Thus decreasing the page refresh time.

  • React uses components as basic unit of UI which can be reused this saves coding time. Simple and easy to learn.

    React Native

  • React Native is a framework that is used to create cross-platform Native apps. It means you can create native apps and the same app will run on Android and ios.

  • React native have all the benefits of ReactJS

  • React native allows developers to create native apps in web-style approach.

How can I show current location on a Google Map on Android Marshmallow?

Sorry but that's just much too much overhead (above), short and quick, if you have the MapFragment, you also have to map, just do the following:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            googleMap.setMyLocationEnabled(true)
} else {
    // Show rationale and request permission.
}

Code is in Kotlin, hope you don't mind.

have fun

Btw I think this one is a duplicate of: Show Current Location inside Google Map Fragment

Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null]

Plus what @mlc-mlapis commented, you're mixing lettable operators and the prototype patching method. Use one or the other.

For your case it should be

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';

@Injectable()
export class SwPeopleService {
    people$ = this.http.get('https://swapi.co/api/people/')
      .map((res:any) => res.results);

    constructor(private http: HttpClient) {} 
}

https://stackblitz.com/edit/angular-http-observables-9nchvz?file=app%2Fsw-people.service.ts

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

From here:

Root Cause: Maximum connection has been exceeded on your SQL Server Instance.

How to fix it...!

  1. F8 or Object Explorer
  2. Right click on Instance --> Click Properties...
  3. Select "Connections" on "Select a page" area at left
  4. Chenge the value to 0 (Zero) for "Maximum number of concurrent connections(0 = Unlimited)"
  5. Restart the SQL Server Instance once.

Apart from that also ensure that below are enabled:

  • Shared Memory protocol is enabled
  • Named Pipes protocol is enabled
  • TCP/IP is enabled

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

The easiest way is to let NPM do everything for you,

npm --add-python-to-path='true' --debug install --global windows-build-tools

Spring Boot @autowired does not work, classes in different package

I had the same problem. It worked for me when i removed the private modifier from the Autowired objects.

android : Error converting byte to dex

I've noticed this can happen (sometimes) when editing java files while Android Studio is building.

I solved this by manually deleting the build folder and running agin.

Failed to authenticate on SMTP server error using gmail

Change the .env file as follow

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

And the go to the gmail security section ->Allow Less secure app access

Then run

php artisan config:clear

Refresh the site

There is no argument given that corresponds to the required formal parameter - .NET Error

In the constructor of

 public class ErrorEventArg : EventArgs

You have to add "base" as follows:

    public ErrorEventArg(string errorMsg, string lastQuery) : base (string errorMsg, string lastQuery)
    {
        ErrorMsg = errorMsg;
        LastQuery = lastQuery;
    }

That solved it for me

Angular and Typescript: Can't find names - Error: cannot find name

For Angular 2.0.0-rc.0 adding node_modules/angular2/typings/browser.d.ts won't work. First add typings.json file to your solution, with this content:

{
    "ambientDependencies": {
        "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd"
    }
}

And then update the package.json file to include this postinstall:

"scripts": {
    "postinstall": "typings install"
},

Now run npm install

Also now you should ignore typings folder in your tsconfig.json file as well:

 "exclude": [
        "node_modules",
        "typings/main",
        "typings/main.d.ts"
    ]

Update

Now AngularJS 2.0 is using core-js instead of es6-shim. Follow its quick start typings.json file for more info.

Coerce multiple columns to factors at once

Here is another tidyverse approach using the modify_at() function from the purrr package.

library(purrr)

# Data frame with only integer columns
data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))

# Modify specified columns to a factor class
data_with_factors <- data %>%
    purrr::modify_at(c("A", "C", "E"), factor)


# Check the results:
str(data_with_factors)
# 'data.frame':   4 obs. of  10 variables:
#  $ A: Factor w/ 4 levels "8","12","33",..: 1 3 4 2
#  $ B: int  25 32 2 19
#  $ C: Factor w/ 4 levels "5","15","35",..: 1 3 4 2
#  $ D: int  11 7 27 6
#  $ E: Factor w/ 4 levels "1","4","16","20": 2 3 1 4
#  $ F: int  21 23 39 18
#  $ G: int  31 14 38 26
#  $ H: int  17 24 34 10
#  $ I: int  13 28 30 29
#  $ J: int  3 22 37 9

Spring boot - configure EntityManager

Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample

@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = { 
    ServiceMarker.class,
    RepositoryMarker.class }
)
public class AppConfig {

}

PersistenceConfig

@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
    private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};

    @Autowired
    private Environment env;

     @Bean(destroyMethod = "close")
     public DataSource dataSource() {
         BasicDataSource dataSource = new BasicDataSource();
         dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
         dataSource.setUrl(env.getProperty("jdbc.url"));
         dataSource.setUsername(env.getProperty("jdbc.username"));
         dataSource.setPassword(env.getProperty("jdbc.password"));
         return dataSource;
     }

     @Bean
     public JpaTransactionManager jpaTransactionManager() {
         JpaTransactionManager transactionManager = new JpaTransactionManager();
         transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
         return transactionManager;
     }

    private HibernateJpaVendorAdapter vendorAdaptor() {
         HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
         vendorAdapter.setShowSql(true);
         return vendorAdapter;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {

         LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
         entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
         entityManagerFactoryBean.setDataSource(dataSource());
         entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
         entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);             
         entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());

         return entityManagerFactoryBean;
     }

     private Properties jpaHibernateProperties() {

         Properties properties = new Properties();

         properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
         properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));

         properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
         properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");      
         return properties;       
     }

}

Main

public static void main(String[] args) { 
    try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
        MyService myService = springContext.getBean(MyServiceImpl.class);
        try {
            myService.handleProcess(fromDate, toDate);
        } catch (Exception e) {
            logger.error("Exception occurs", e);
            myService.handleException(fromDate, toDate, e);
        }
    } catch (Exception e) {
        logger.error("Exception occurs in loading Spring context: ", e);
    }
}

MyService

@Service
public class MyServiceImpl implements MyService {

    @Inject
    private MyDao myDao;

    @Override
    public void handleProcess(String fromDate, String toDate) {
        List<Student> myList = myDao.select(fromDate, toDate);
    }
}

MyDaoImpl

@Repository
@Transactional
public class MyDaoImpl implements MyDao {

    @PersistenceContext
    private EntityManager entityManager;

    public Student select(String fromDate, String toDate){

        TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
        query.setParameter("fromDate", fromDate);
        query.setParameter("toDate", toDate);
        List<Student> list = query.getResultList();
        return CollectionUtils.isEmpty(list) ? null : list;
    }

}

Assuming maven project: Properties file should be in src/main/resources/database folder

jdbc.properties file

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password

hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true

ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.

Let's say you have package name a.b.c.service.impl. MyServiceImpl is in this package and so is ServiceMarker.

public interface ServiceMarker {

}

Same for repository marker. Let's say you have a.b.c.repository.impl or a.b.c.dao.impl package name. Then MyDaoImpl is in this this package and also Repositorymarker

public interface RepositoryMarker {

}

a.b.c.entities.Student

//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {

    private LocalDateTime fromDate;
    private LocalDateTime toDate;

    //getters setters

}

a.b.c.converters

@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {

    @Override
    public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {

        if (dateTime == null) {
            return null;
        }
        return Timestamp.valueOf(dateTime);
    }

    @Override
    public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {

        if (timestamp == null) {
            return null;
        }    
        return timestamp.toLocalDateTime();
    }
}

pom.xml

<properties>
    <java-version>1.8</java-version>
    <org.springframework-version>4.2.1.RELEASE</org.springframework-version>
    <hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
    <commons-dbcp2.version>2.1.1</commons-dbcp2.version>
    <mysql-connector-java.version>5.1.36</mysql-connector-java.version>
     <junit.version>4.12</junit.version> 
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${org.springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate-entitymanager.version}</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql-connector-java.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-dbcp2</artifactId>
        <version>${commons-dbcp2.version}</version>
    </dependency>
</dependencies>

<build>
     <finalName>${project.artifactId}</finalName>
     <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>${java-version}</source>
                <target>${java-version}</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
     </plugins>
</build>

Hope it helps. Thanks

HikariCP - connection is not available

I managed to fix it finally. The problem is not related to HikariCP. The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional or enveloping all the logic in a single call to transactional service method seem to solve the problem.

Error: Execution failed for task ':app:clean'. Unable to delete file

Another application that can be using the resources is apparently Android Studio's Kotlin REPL. I closed that, and then I could build again no problem.

Call to undefined function App\Http\Controllers\ [ function name ]

If they are in the same controller class, it would be:

foreach ( $characters as $character) {
    $num += $this->getFactorial($index) * $index;
    $index ++;
}

Otherwise you need to create a new instance of the class, and call the method, ie:

$controller = new MyController();
foreach ( $characters as $character) {
    $num += $controller->getFactorial($index) * $index;
    $index ++;
}

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

If you are not sure if local db is installed, or not sure which database name you should use to connect to it - try running 'sqllocaldb info' command - it will show you existing localdb databases.

Now, as far as I know, local db should be installed together with Visual Studio 2015. But probably it is not required feature, and if something goes wrong or it cannot be installed for some reason - Visual Studio installation continues still (note that is just my guess). So to be on the safe side don't rely on it will always be installed together with VS.

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

In my case I had created a SB app from the SB Initializer and had included a fair number of deps in it to other things. I went in and commented out the refs to them in the build.gradle file and so was left with:

implementation 'org.springframework.boot:spring-boot-starter-hateoas'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.hsqldb:hsqldb'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'

as deps. Then my bare-bones SB app was able to build and get running successfully. As I go to try to do things that may need those commented-out libs I will add them back and see what breaks.

Using DISTINCT along with GROUP BY in SQL Server

Perhaps not in the context that you have it, but you could use

SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA

You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.

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.

toBe(true) vs toBeTruthy() vs toBeTrue()

What I do when I wonder something like the question asked here is go to the source.

toBe()

expect().toBe() is defined as:

function toBe() {
  return {
    compare: function(actual, expected) {
      return {
        pass: actual === expected
      };
    }
  };
}

It performs its test with === which means that when used as expect(foo).toBe(true), it will pass only if foo actually has the value true. Truthy values won't make the test pass.

toBeTruthy()

expect().toBeTruthy() is defined as:

function toBeTruthy() {
  return {
    compare: function(actual) {
      return {
        pass: !!actual
      };
    }
  };
}

Type coercion

A value is truthy if the coercion of this value to a boolean yields the value true. The operation !! tests for truthiness by coercing the value passed to expect to a boolean. Note that contrarily to what the currently accepted answer implies, == true is not a correct test for truthiness. You'll get funny things like

> "hello" == true
false
> "" == true
false
> [] == true
false
> [1, 2, 3] == true
false

Whereas using !! yields:

> !!"hello"
true
> !!""
false
> !![1, 2, 3]
true
> !![] 
true

(Yes, empty or not, an array is truthy.)

toBeTrue()

expect().toBeTrue() is part of Jasmine-Matchers (which is registered on npm as jasmine-expect after a later project registered jasmine-matchers first).

expect().toBeTrue() is defined as:

function toBeTrue(actual) {
  return actual === true ||
    is(actual, 'Boolean') &&
    actual.valueOf();
}

The difference with expect().toBeTrue() and expect().toBe(true) is that expect().toBeTrue() tests whether it is dealing with a Boolean object. expect(new Boolean(true)).toBe(true) would fail whereas expect(new Boolean(true)).toBeTrue() would pass. This is because of this funny thing:

> new Boolean(true) === true
false
> new Boolean(true) === false
false

At least it is truthy:

> !!new Boolean(true)
true

Which is best suited for use with elem.isDisplayed()?

Ultimately Protractor hands off this request to Selenium. The documentation states that the value produced by .isDisplayed() is a promise that resolves to a boolean. I would take it at face value and use .toBeTrue() or .toBe(true). If I found a case where the implementation returns truthy/falsy values, I would file a bug report.

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

For me, the below helped

Find org.apache.http.legacy.jar which is in Android/Sdk/platforms/android-23/optional, add it to your dependency.

Source

Logging with Retrofit 2

for Retrofit 2.0.2 the code is like

   **HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient=new OkHttpClient.Builder();
        httpClient.addInterceptor(logging);**


        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    **.client(httpClient.build())**
                    .build();
        }

Open File in Another Directory (Python)

Its a very old question but I think it will help newbies line me who are learning python. If you have Python 3.4 or above, the pathlib library comes with the default distribution.

To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest. To indicate that the path is a raw string, put r in front of the string with your actual path.

For example,

from pathlib import Path

dataFolder = Path(r'D:\Desktop dump\example.txt')

Source: The easy way to deal with file paths on Windows, Mac and Linux

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

WARNING: Exception encountered during context initialization - cancelling refresh attempt

In my case, I'm using j-hipster and I had to do ./mvnw clean to overcome this warning.

CORS with spring-boot and angularjs not working

Step 1

By annotating the controller with @CrossOrigin annotation will allow the CORS configurations.

@CrossOrigin
@RestController
public class SampleController { 
  .....
}

Step 2

Spring already has a CorsFilter even though You can just register your own CorsFilter as a bean to provide your own configuration as follows.

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(Collections.singletonList("http://localhost:3000")); // Provide list of origins if you want multiple origins
    config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
    config.setAllowCredentials(true);
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

This helped us, maybe it can help others in the future. @Transaction was not working for us, but this did:

@ConditionalOnMissingClass("org.springframework.orm.jpa.JpaTransactionManager")

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

I have resolved this problem by resizing the image to lower size. I am using xamarin form. decreasing the size of the PNG image resolved the problem.

Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this

My simple solution is this

if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED &&
        ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED) {
    googleMap.setMyLocationEnabled(true);
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
    Toast.makeText(this, R.string.error_permission_map, Toast.LENGTH_LONG).show();
}

or you can open permission dialog in else like this

} else {
   ActivityCompat.requestPermissions(this, new String[] {
      Manifest.permission.ACCESS_FINE_LOCATION, 
      Manifest.permission.ACCESS_COARSE_LOCATION }, 
      TAG_CODE_PERMISSION_LOCATION);
}

pip install failing with: OSError: [Errno 13] Permission denied on directory

Option a) Create a virtualenv, activate it and install:

virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt

Option b) Install in your homedir:

pip install --user -r requirements.txt

My recommendation use safe (a) option, so that requirements of this project do not interfere with other projects requirements.

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

For me the issue is resolved by adding domain name in user name as follow:

string userName="yourUserName";
string password="passowrd";
string hostName="LdapServerHostName";
string domain="yourDomain";
System.DirectoryServices.AuthenticationTypes option = System.DirectoryServices.AuthenticationTypes.SecureSocketsLayer; 
string userNameWithDomain = string.Format("{0}@{1}",userName , domain);
DirectoryEntry directoryOU = new DirectoryEntry("LDAP://" + hostName, userNameWithDomain, password, option);

Spring Boot: Cannot access REST Controller on localhost (404)

Adding to MattR's answer:

As stated in here, @SpringBootApplication automatically inserts the needed annotations: @Configuration, @EnableAutoConfiguration, and also @ComponentScan; however, the @ComponentScan will only look for the components in the same package as the App, in this case your com.nice.application, whereas your controller resides in com.nice.controller. That's why you get 404 because the App didn't find the controller in the application package.

Git Clone from GitHub over https with two-factor authentication

Find out how to fix this here:

https://github.com/blog/1614-two-factor-authentication#how-does-it-work-for-command-line-git

How does it work for command-line Git?

If you are using SSH for Git authentication, rest easy: you don't need to do anything. If you are using HTTPS Git, instead of entering your password, enter a personal access token. These can be created by going to your personal access tokens page.

to call onChange event after pressing Enter key

According to React Doc, you could listen to keyboard events, like onKeyPress or onKeyUp, not onChange.

var Input = React.createClass({
  render: function () {
    return <input type="text" onKeyDown={this._handleKeyDown} />;
  },
  _handleKeyDown: function(e) {
    if (e.key === 'Enter') {
      console.log('do validate');
    }
  }
});

Update: Use React.Component

Here is the code using React.Component which does the same thing

class Input extends React.Component {
  _handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      console.log('do validate');
    }
  }

  render() {
    return <input type="text" onKeyDown={this._handleKeyDown} />
  }
}

Here is the jsfiddle.

Update 2: Use a functional component

const Input = () => {
  const handleKeyDown = (event) => {
    if (event.key === 'Enter') {
      console.log('do validate')
    }
  }

  return <input type="text" onKeyDown={handleKeyDown} />
}

How to convert an Instant to a date format?

If you want to convert an Instant to a Date:

Date myDate = Date.from(instant);

And then you can use SimpleDateFormat for the formatting part of your question:

SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);

What is this spring.jpa.open-in-view=true property in Spring Boot?

The OSIV Anti-Pattern

Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.

enter image description here

  • The OpenSessionInViewFilter calls the openSession method of the underlying SessionFactory and obtains a new Session.
  • The Session is bound to the TransactionSynchronizationManager.
  • The OpenSessionInViewFilter calls the doFilter of the javax.servlet.FilterChain object reference and the request is further processed
  • The DispatcherServlet is called, and it routes the HTTP request to the underlying PostController.
  • The PostController calls the PostService to get a list of Post entities.
  • The PostService opens a new transaction, and the HibernateTransactionManager reuses the same Session that was opened by the OpenSessionInViewFilter.
  • The PostDAO fetches the list of Post entities without initializing any lazy association.
  • The PostService commits the underlying transaction, but the Session is not closed because it was opened externally.
  • The DispatcherServlet starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.
  • The OpenSessionInViewFilter can close the Session, and the underlying database connection is released as well.

At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.

The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection as read-only which would allow the database server to avoid writing to the transaction log.

There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.

The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize for fetching associations in batches, and FetchMode.SUBSELECT to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.

Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.

Spring Boot and OSIV

Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.

So, make sure that in the application.properties configuration file, you have the following entry:

spring.jpa.open-in-view=false

This will disable OSIV so that you can handle the LazyInitializationException the right way.

Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

refering to Deepak Vishwakarma's answer, I tried with that and was facing same problem with the url-problem. I installed maven-3.6.3 and inside .m2 folder I found a

settings.xml.bak

file and from that copied that mirror link and just changed url what @Deepak did. It worked like charm! Mirror link I got from that .bak file

http://local.maven.repo:9081/nexus/content/groups/public

Then executed :

mvn clean 
mvn clean install

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

I had to set

Aws.config.update({
  credentials: Aws::Credentials.new(access_key_id, secret_access_key)
})

before with the ruby aws sdk v2 (there is probably something similiar to this in the other languages as well)

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

In my case I was getting this message due to a runtime error with Junit which wasn't at all visible from the output of the gradle test task execution. I've run into this for a couple reasons:

  1. Including the org.junit.platform:junit-platform-launcher dependency with a version that didn't match the junit version I was using
  2. Having an entry in META-INF/services for a Junit test listener which I had commented out

You can try re-running with --debug and search for FAILED or org.gradle.api.internal.tasks.testing.TestSuiteExecutionException. In my second case, the exception was:

2020-10-20T11:34:26.517-0700 [DEBUG] [TestEventLogger]
2020-10-20T11:34:26.517-0700 [DEBUG] [TestEventLogger] Gradle Test Executor 1 STARTED
2020-10-20T11:34:26.661-0700 [DEBUG] [TestEventLogger]
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] Gradle Test Executor 1 FAILED
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]     org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not complete execution for Gradle Test Executor 1.
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:63)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at java.lang.reflect.Method.invoke(Method.java:498)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at com.sun.proxy.$Proxy2.stop(Unknown Source)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger]         at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:132)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at java.lang.reflect.Method.invoke(Method.java:498)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:413)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]         at java.lang.Thread.run(Thread.java:748)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]         Caused by:
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]         java.util.ServiceConfigurationError: org.junit.platform.launcher.TestExecutionListener: Provider com.example.myproject.MyCommentedOutClass not found
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader.fail(ServiceLoader.java:239)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader.access$300(ServiceLoader.java:185)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:372)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at java.lang.Iterable.forEach(Iterable.java:74)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:94)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:67)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:97)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger]             ... 25 more

Notice that these are DEBUG logs. I didn't see anything helpful with just --info

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

The requested jar is probably not jackson-annotations-x.y.z.jar but jackson-core-x.y.z.jar which could be found here: http://www.java2s.com/Code/Jar/j/Downloadjacksoncore220rc1jar.htm

Where to put the gradle.properties file

Actually there are 3 places where gradle.properties can be placed:

  1. Under gradle user home directory defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle
  2. The sub-project directory (myProject2 in your case)
  3. The root project directory (under myProject)

Gradle looks for gradle.properties in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).

You can find more details about it in gradle documentation here.

Task.Run with Parameter(s)?

private void RunAsync()
{
    string param = "Hi";
    Task.Run(() => MethodWithParameter(param));
}

private void MethodWithParameter(string param)
{
    //Do stuff
}

Edit

Due to popular demand I must note that the Task launched will run in parallel with the calling thread. Assuming the default TaskScheduler this will use the .NET ThreadPool. Anyways, this means you need to account for whatever parameter(s) being passed to the Task as potentially being accessed by multiple threads at once, making them shared state. This includes accessing them on the calling thread.

In my above code that case is made entirely moot. Strings are immutable. That's why I used them as an example. But say you're not using a String...

One solution is to use async and await. This, by default, will capture the SynchronizationContext of the calling thread and will create a continuation for the rest of the method after the call to await and attach it to the created Task. If this method is running on the WinForms GUI thread it will be of type WindowsFormsSynchronizationContext.

The continuation will run after being posted back to the captured SynchronizationContext - again only by default. So you'll be back on the thread you started with after the await call. You can change this in a variety of ways, notably using ConfigureAwait. In short, the rest of that method will not continue until after the Task has completed on another thread. But the calling thread will continue to run in parallel, just not the rest of the method.

This waiting to complete running the rest of the method may or may not be desirable. If nothing in that method later accesses the parameters passed to the Task you may not want to use await at all.

Or maybe you use those parameters much later on in the method. No reason to await immediately as you could continue safely doing work. Remember, you can store the Task returned in a variable and await on it later - even in the same method. For instance, once you need to access the passed parameters safely after doing a bunch some other work. Again, you do not need to await on the Task right when you run it.

Anyways, a simple way to make this thread-safe with respect to the parameters passed to Task.Run is to do this:

You must first decorate RunAsync with async:

private async void RunAsync()

Important Note

Preferably the method marked async should not return void, as the linked documentation mentions. The common exception to this is event handlers such as button clicks and such. They must return void. Otherwise I always try to return a Task or Task<TResult> when using async. It's good practice for a quite a few reasons.

Now you can await running the Task like below. You cannot use await without async.

await Task.Run(() => MethodWithParameter(param));
//Code here and below in the same method will not run until AFTER the above task has completed in one fashion or another

So, in general, if you await the task you can avoid treating passed in parameters as a potentially shared resource with all the pitfalls of modifying something from multiple threads at once. Also, beware of closures. I won't cover those in depth but the linked article does a great job of it.

Side Note

A bit off topic, but be careful using any type of "blocking" on the WinForms GUI thread due to it being marked with [STAThread]. Using await won't block at all, but I do sometimes see it used in conjunction with some sort of blocking.

"Block" is in quotes because you technically cannot block the WinForms GUI thread. Yes, if you use lock on the WinForms GUI thread it will still pump messages, despite you thinking it's "blocked". It's not.

This can cause bizarre issues in very rare cases. One of the reasons you never want to use a lock when painting, for example. But that's a fringe and complex case; however I've seen it cause crazy issues. So I noted it for completeness sake.

How can I customize the tab-to-space conversion factor?

I had to do a lot of settings edits like the previous answers, so I don't know which made it work after a lot of modifications.

Nothing worked until I closed and openen my IDE, but the last three things I did was disable the lonefy.vscode-js-css-html-formatter, "html.format.enable": true, and restart Visual Studio.

{
    "editor.suggestSelection": "first",
    "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
    "workbench.colorTheme": "Default Light+",
    "[html]": {
        "editor.defaultFormatter": "vscode.html-language-features",
        "editor.tabSize": 2,
        "editor.detectIndentation": false,
        "editor.insertSpaces": true
    },
    "typescript.format.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces": true,
    "editor.tabSize": 2,
    "typescript.format.insertSpaceAfterConstructor": true,
    "files.autoSave": "afterDelay",
    "html.format.indentHandlebars": true,
    "html.format.indentInnerHtml": true,
    "html.format.enable": true,
    "editor.detectIndentation": false,
    "editor.insertSpaces": true,
}

How to get local server host and port in Spring Boot?

I have just found a way to get server ip and port easily by using Eureka client library. As I am using it anyway for service registration, it is not an additional lib for me just for this purpose.

You need to add the maven dependency first:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>

Then you can use the ApplicationInfoManager service in any of your Spring beans.

@Autowired
private ApplicationInfoManager applicationInfoManager;
...

InstanceInfo applicationInfo = applicationInfoManager.getInfo();

The InstanceInfo object contains all important information about your service, like IP address, port, hostname, etc.

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

I found the solution for it by analyzing the data packets using wireshark. What I found is that while making a secure connection, android was falling back to SSLv3 from TLSv1 . It is a bug in android versions < 4.4 , and it can be solved by removing the SSLv3 protocol from Enabled Protocols list. I made a custom socketFactory class called NoSSLv3SocketFactory.java. Use this to make a socketfactory.

/*Copyright 2015 Bhavit Singh Sengar
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;


public class NoSSLv3SocketFactory extends SSLSocketFactory{
    private final SSLSocketFactory delegate;

public NoSSLv3SocketFactory() {
    this.delegate = HttpsURLConnection.getDefaultSSLSocketFactory();
}

public NoSSLv3SocketFactory(SSLSocketFactory delegate) {
    this.delegate = delegate;
}

@Override
public String[] getDefaultCipherSuites() {
    return delegate.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
    return delegate.getSupportedCipherSuites();
}

private Socket makeSocketSafe(Socket socket) {
    if (socket instanceof SSLSocket) {
        socket = new NoSSLv3SSLSocket((SSLSocket) socket);
    }
    return socket;
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
    return makeSocketSafe(delegate.createSocket(s, host, port, autoClose));
}

@Override
public Socket createSocket(String host, int port) throws IOException {
    return makeSocketSafe(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
    return makeSocketSafe(delegate.createSocket(host, port, localHost, localPort));
}

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
    return makeSocketSafe(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
    return makeSocketSafe(delegate.createSocket(address, port, localAddress, localPort));
}

private class NoSSLv3SSLSocket extends DelegateSSLSocket {

    private NoSSLv3SSLSocket(SSLSocket delegate) {
        super(delegate);

    }

    @Override
    public void setEnabledProtocols(String[] protocols) {
        if (protocols != null && protocols.length == 1 && "SSLv3".equals(protocols[0])) {

            List<String> enabledProtocols = new ArrayList<String>(Arrays.asList(delegate.getEnabledProtocols()));
            if (enabledProtocols.size() > 1) {
                enabledProtocols.remove("SSLv3");
                System.out.println("Removed SSLv3 from enabled protocols");
            } else {
                System.out.println("SSL stuck with protocol available for " + String.valueOf(enabledProtocols));
            }
            protocols = enabledProtocols.toArray(new String[enabledProtocols.size()]);
        }

        super.setEnabledProtocols(protocols);
    }
}

public class DelegateSSLSocket extends SSLSocket {

    protected final SSLSocket delegate;

    DelegateSSLSocket(SSLSocket delegate) {
        this.delegate = delegate;
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    @Override
    public String[] getEnabledCipherSuites() {
        return delegate.getEnabledCipherSuites();
    }

    @Override
    public void setEnabledCipherSuites(String[] suites) {
        delegate.setEnabledCipherSuites(suites);
    }

    @Override
    public String[] getSupportedProtocols() {
        return delegate.getSupportedProtocols();
    }

    @Override
    public String[] getEnabledProtocols() {
        return delegate.getEnabledProtocols();
    }

    @Override
    public void setEnabledProtocols(String[] protocols) {
        delegate.setEnabledProtocols(protocols);
    }

    @Override
    public SSLSession getSession() {
        return delegate.getSession();
    }

    @Override
    public void addHandshakeCompletedListener(HandshakeCompletedListener listener) {
        delegate.addHandshakeCompletedListener(listener);
    }

    @Override
    public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) {
        delegate.removeHandshakeCompletedListener(listener);
    }

    @Override
    public void startHandshake() throws IOException {
        delegate.startHandshake();
    }

    @Override
    public void setUseClientMode(boolean mode) {
        delegate.setUseClientMode(mode);
    }

    @Override
    public boolean getUseClientMode() {
        return delegate.getUseClientMode();
    }

    @Override
    public void setNeedClientAuth(boolean need) {
        delegate.setNeedClientAuth(need);
    }

    @Override
    public void setWantClientAuth(boolean want) {
        delegate.setWantClientAuth(want);
    }

    @Override
    public boolean getNeedClientAuth() {
        return delegate.getNeedClientAuth();
    }

    @Override
    public boolean getWantClientAuth() {
        return delegate.getWantClientAuth();
    }

    @Override
    public void setEnableSessionCreation(boolean flag) {
        delegate.setEnableSessionCreation(flag);
    }

    @Override
    public boolean getEnableSessionCreation() {
        return delegate.getEnableSessionCreation();
    }

    @Override
    public void bind(SocketAddress localAddr) throws IOException {
        delegate.bind(localAddr);
    }

    @Override
    public synchronized void close() throws IOException {
        delegate.close();
    }

    @Override
    public void connect(SocketAddress remoteAddr) throws IOException {
        delegate.connect(remoteAddr);
    }

    @Override
    public void connect(SocketAddress remoteAddr, int timeout) throws IOException {
        delegate.connect(remoteAddr, timeout);
    }

    @Override
    public SocketChannel getChannel() {
        return delegate.getChannel();
    }

    @Override
    public InetAddress getInetAddress() {
        return delegate.getInetAddress();
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return delegate.getInputStream();
    }

    @Override
    public boolean getKeepAlive() throws SocketException {
        return delegate.getKeepAlive();
    }

    @Override
    public InetAddress getLocalAddress() {
        return delegate.getLocalAddress();
    }

    @Override
    public int getLocalPort() {
        return delegate.getLocalPort();
    }

    @Override
    public SocketAddress getLocalSocketAddress() {
        return delegate.getLocalSocketAddress();
    }

    @Override
    public boolean getOOBInline() throws SocketException {
        return delegate.getOOBInline();
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return delegate.getOutputStream();
    }

    @Override
    public int getPort() {
        return delegate.getPort();
    }

    @Override
    public synchronized int getReceiveBufferSize() throws SocketException {
        return delegate.getReceiveBufferSize();
    }

    @Override
    public SocketAddress getRemoteSocketAddress() {
        return delegate.getRemoteSocketAddress();
    }

    @Override
    public boolean getReuseAddress() throws SocketException {
        return delegate.getReuseAddress();
    }

    @Override
    public synchronized int getSendBufferSize() throws SocketException {
        return delegate.getSendBufferSize();
    }

    @Override
    public int getSoLinger() throws SocketException {
        return delegate.getSoLinger();
    }

    @Override
    public synchronized int getSoTimeout() throws SocketException {
        return delegate.getSoTimeout();
    }

    @Override
    public boolean getTcpNoDelay() throws SocketException {
        return delegate.getTcpNoDelay();
    }

    @Override
    public int getTrafficClass() throws SocketException {
        return delegate.getTrafficClass();
    }

    @Override
    public boolean isBound() {
        return delegate.isBound();
    }

    @Override
    public boolean isClosed() {
        return delegate.isClosed();
    }

    @Override
    public boolean isConnected() {
        return delegate.isConnected();
    }

    @Override
    public boolean isInputShutdown() {
        return delegate.isInputShutdown();
    }

    @Override
    public boolean isOutputShutdown() {
        return delegate.isOutputShutdown();
    }

    @Override
    public void sendUrgentData(int value) throws IOException {
        delegate.sendUrgentData(value);
    }

    @Override
    public void setKeepAlive(boolean keepAlive) throws SocketException {
        delegate.setKeepAlive(keepAlive);
    }

    @Override
    public void setOOBInline(boolean oobinline) throws SocketException {
        delegate.setOOBInline(oobinline);
    }

    @Override
    public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) {
        delegate.setPerformancePreferences(connectionTime, latency, bandwidth);
    }

    @Override
    public synchronized void setReceiveBufferSize(int size) throws SocketException {
        delegate.setReceiveBufferSize(size);
    }

    @Override
    public void setReuseAddress(boolean reuse) throws SocketException {
        delegate.setReuseAddress(reuse);
    }

    @Override
    public synchronized void setSendBufferSize(int size) throws SocketException {
        delegate.setSendBufferSize(size);
    }

    @Override
    public void setSoLinger(boolean on, int timeout) throws SocketException {
        delegate.setSoLinger(on, timeout);
    }

    @Override
    public synchronized void setSoTimeout(int timeout) throws SocketException {
        delegate.setSoTimeout(timeout);
    }

    @Override
    public void setTcpNoDelay(boolean on) throws SocketException {
        delegate.setTcpNoDelay(on);
    }

    @Override
    public void setTrafficClass(int value) throws SocketException {
        delegate.setTrafficClass(value);
    }

    @Override
    public void shutdownInput() throws IOException {
        delegate.shutdownInput();
    }

    @Override
    public void shutdownOutput() throws IOException {
        delegate.shutdownOutput();
    }

    @Override
    public String toString() {
        return delegate.toString();
    }

    @Override
    public boolean equals(Object o) {
        return delegate.equals(o);
    }
}
}

Use this class like this while connecting :

SSLContext sslcontext = SSLContext.getInstance("TLSv1");
sslcontext.init(null, null, null);
SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());

HttpsURLConnection.setDefaultSSLSocketFactory(NoSSLv3Factory);
l_connection = (HttpsURLConnection) l_url.openConnection();
l_connection.connect();

UPDATE :

Now, correct solution would be to install a newer security provider using Google Play Services:

    ProviderInstaller.installIfNeeded(getApplicationContext());

This effectively gives your app access to a newer version of OpenSSL and Java Security Provider, which includes support for TLSv1.2 in SSLEngine. Once the new provider is installed, you can create an SSLEngine which supports SSLv3, TLSv1, TLSv1.1 and TLSv1.2 the usual way:

    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(null, null, null);
    SSLEngine engine = sslContext.createSSLEngine();

Or you can restrict the enabled protocols using engine.setEnabledProtocols.

Don't forget to add the following dependency (check the latest version here):

implementation 'com.google.android.gms:play-services-auth:17.0.0'

For more info, checkout this link.

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

The MySQL dependency should be like the following syntax in the pom.xml file.

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>

Make sure the syntax, groupId, artifactId, Version has included in the dependancy.

Convert Map to JSON using Jackson

If you're using jackson, better to convert directly to ObjectNode.

//not including SerializationFeatures for brevity
static final ObjectMapper mapper = new ObjectMapper();

//pass it your payload
public static ObjectNode convObjToONode(Object o) {
    StringWriter stringify = new StringWriter();
    ObjectNode objToONode = null;

    try {
        mapper.writeValue(stringify, o);
        objToONode = (ObjectNode) mapper.readTree(stringify.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(objToONode);
    return objToONode;
}

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

DISCLAIMER: this answer is from Jul 2015 and uses Retrofit and OkHttp from that time.
Check this link for more info on Retrofit v2 and this one for the current OkHttp methods.

Okay, I got it working using Android Developers guide.

Just as OP, I'm trying to use Retrofit and OkHttp to connect to a self-signed SSL-enabled server.

Here's the code that got things working (I've removed the try/catch blocks):

public static RestAdapter createAdapter(Context context) {
  // loading CAs from an InputStream
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  InputStream cert = context.getResources().openRawResource(R.raw.my_cert);
  Certificate ca;
  try {
    ca = cf.generateCertificate(cert);
  } finally { cert.close(); }

  // creating a KeyStore containing our trusted CAs
  String keyStoreType = KeyStore.getDefaultType();
  KeyStore keyStore = KeyStore.getInstance(keyStoreType);
  keyStore.load(null, null);
  keyStore.setCertificateEntry("ca", ca);

  // creating a TrustManager that trusts the CAs in our KeyStore
  String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
  tmf.init(keyStore);

  // creating an SSLSocketFactory that uses our TrustManager
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, tmf.getTrustManagers(), null);

  // creating an OkHttpClient that uses our SSLSocketFactory
  OkHttpClient okHttpClient = new OkHttpClient();
  okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());

  // creating a RestAdapter that uses this custom client
  return new RestAdapter.Builder()
              .setEndpoint(UrlRepository.API_BASE)
              .setClient(new OkClient(okHttpClient))
              .build();
}

To help in debugging, I also added .setLogLevel(RestAdapter.LogLevel.FULL) to my RestAdapter creation commands and I could see it connecting and getting the response from the server.

All it took was my original .crt file saved in main/res/raw. The .crt file, aka the certificate, is one of the two files created when you create a certificate using openssl. Generally, it is a .crt or .cert file, while the other is a .key file.

Afaik, the .crt file is your public key and the .key file is your private key.

As I can see, you already have a .cert file, which is the same, so try to use it.


PS: For those that read it in the future and only have a .pem file, according to this answer, you only need this to convert one to the other:

openssl x509 -outform der -in your-cert.pem -out your-cert.crt

PS²: For those that don't have any file at all, you can use the following command (bash) to extract the public key (aka certificate) from any server:

echo -n | openssl s_client -connect your.server.com:443 | \
  sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/my_cert.crt

Just replace the your.server.com and the port (if it is not standard HTTPS) and choose a valid path for your output file to be created.

Can't Autowire @Repository annotated interface in Spring Boot

I had some problems with this topic too. You have to make sure you define the packages in Spring boot runner class like this example below:

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({"controller", "service"})
@EntityScan("entity")
@EnableJpaRepositories("repository")
public class Application {

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }

I hope this helps!

Android Studio Run/Debug configuration error: Module not specified

None of the existing answers worked in my case (Android studio 3.5.0). I had to

  1. close all android studio projects
  2. remove the project from the recent projects in android studio wizard
  3. restart android studio
  4. use import option (Import project- Gradle, Eclipse ADT, etc) instead of open an existing project AS project
  5. File -> Sync project with gradle files

Convert a object into JSON in REST service by Spring MVC

You can always add the @Produces("application/json") above your web method or specify produces="application/json" to return json. Then on top of the Student class you can add @XmlRootElement from javax.xml.bind.annotation package.

Please note, it might not be a good idea to directly return model classes. Just a suggestion.

HTH.

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

I faced the same error but i solved this by selecting invalidate caches/restart option.

Click

  1. file >> invalidate caches/restart

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

@Inherently Curious - thanks for posting this. You are almost there - you have to add two more params to SSLContext.init() method.

TrustManager[] trustManagers = new TrustManager[] { new TrustManagerManipulator() };
sc.init(null, trustManagers, new SecureRandom());

it will start working. Again thank you very much for posting this. I solved this/my issue with your code.

Spring boot - Not a managed type

I have the same probblem, in version spring boot v1.3.x what i did is upgrade spring boot to version 1.5.7.RELEASE. Then the probblem gone.

Calling async method on button click

You're the victim of the classic deadlock. task.Wait() or task.Result is a blocking call in UI thread which causes the deadlock.

Don't block in the UI thread. Never do it. Just await it.

private async void Button_Click(object sender, RoutedEventArgs 
{
      var task = GetResponseAsync<MyObject>("my url");
      var items = await task;
}

Btw, why are you catching the WebException and throwing it back? It would be better if you simply don't catch it. Both are same.

Also I can see you're mixing the asynchronous code with synchronous code inside the GetResponse method. StreamReader.ReadToEnd is a blocking call --you should be using StreamReader.ReadToEndAsync.

Also use "Async" suffix to methods which returns a Task or asynchronous to follow the TAP("Task based Asynchronous Pattern") convention as Jon says.

Your method should look something like the following when you've addressed all the above concerns.

public static async Task<List<T>> GetResponseAsync<T>(string url)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

    Stream stream = response.GetResponseStream();
    StreamReader strReader = new StreamReader(stream);
    string text = await strReader.ReadToEndAsync();

    return JsonConvert.DeserializeObject<List<T>>(text);
}

Base64: java.lang.IllegalArgumentException: Illegal character

Just use the below code to resolve this:

JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\\.")[1].
                        replace('-', '+').replace('_', '/')))).readObject();

In the above code replace('-', '+').replace('_', '/') did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:

function url_base64_decode(str) {
  var output = str.replace(/-/g, '+').replace(/_/g, '/');
  switch (output.length % 4) {
    case 0:
      break;
    case 2:
      output += '==';
      break;
    case 3:
      output += '=';
      break;
    default:
      throw 'Illegal base64url string!';
  }
  var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
  try{
    return decodeURIComponent(escape(result));
  } catch (err) {
    return result;
  }
}

@Autowired - No qualifying bean of type found for dependency at least 1 bean

Missing the 'implements' keyword in the impl classes might also be the issue

How to set TLS version on apache HttpClient

HttpClient-4.5,Use TLSv1.2 ,You must code like this:

 //Set the https use TLSv1.2
private static Registry<ConnectionSocketFactory> getRegistry() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext sslContext = SSLContexts.custom().build();
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[]{"TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory)
            .build();
}

public static void main(String... args) {
    try {
        //Set the https use TLSv1.2
        PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(getRegistry());
        clientConnectionManager.setMaxTotal(100);
        clientConnectionManager.setDefaultMaxPerRoute(20);
        HttpClient client = HttpClients.custom().setConnectionManager(clientConnectionManager).build();
        //Then you can do : client.execute(HttpGet or HttpPost);
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

How to create an empty file with Ansible?

Something like this (using the stat module first to gather data about it and then filtering using a conditional) should work:

- stat: path=/etc/nologin
  register: p

- name: create fake 'nologin' shell
  file: path=/etc/nologin state=touch owner=root group=sys mode=0555
  when: p.stat.exists is defined and not p.stat.exists

You might alternatively be able to leverage the changed_when functionality.

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

When I tried to make ObjectMapper primary in spring boot 2.0.6 I got errors So I modified the one that spring boot created for me

Also see https://stackoverflow.com/a/48519868/255139

@Lazy
@Autowired
ObjectMapper mapper;

@PostConstruct
public ObjectMapper configureMapper() {
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);

    mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, true);
    mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);

    SimpleModule module = new SimpleModule();
    module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
    module.addSerializer(LocalDate.class, new LocalDateSerializer());
    mapper.registerModule(module);

    return mapper;
}

Spring Could not Resolve placeholder

You are not reading the properties file correctly. The propertySource should pass the parameter as: file:appclient.properties or classpath:appclient.properties. Change the annotation to:

@PropertySource(value={"classpath:appclient.properties"})

However I don't know what your PropertiesConfig file contains, as you're importing that also. Ideally the @PropertySource annotation should have been kept there.

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

Changing factor levels with dplyr mutate

Maybe you are looking for this plyr::revalue function:

mutate(dat, x = revalue(x, c("A" = "B")))

You can see plyr::mapvalues too.

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

If you're using application.properties in spring boot app, then just put the below line into application.properties and it should work:
spring.datasource.url: jdbc:mysql://google/?cloudSqlInstance=&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=****&password=****

How to autowire RestTemplate using annotations

You can add the method below to your class for providing a default implementation of RestTemplate:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

How to use Spring Boot with MySQL database and JPA?

When moving classes into specific packages like repository, controller, domain just the generic @SpringBootApplication is not enough.

You will have to specify the base package for component scan

@ComponentScan("base_package")

For JPA

@EnableJpaRepositories(basePackages = "repository")

is also needed, so spring data will know where to look into for repository interfaces.

serialize/deserialize java 8 java.time with Jackson JSON mapper

This is just an example how to use it in a unit test that I hacked to debug this issue. The key ingredients are

  • mapper.registerModule(new JavaTimeModule());
  • maven dependency of <artifactId>jackson-datatype-jsr310</artifactId>

Code:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.IOException;
import java.io.Serializable;
import java.time.Instant;

class Mumu implements Serializable {
    private Instant from;
    private String text;

    Mumu(Instant from, String text) {
        this.from = from;
        this.text = text;
    }

    public Mumu() {
    }

    public Instant getFrom() {
        return from;
    }

    public String getText() {
        return text;
    }

    @Override
    public String toString() {
        return "Mumu{" +
                "from=" + from +
                ", text='" + text + '\'' +
                '}';
    }
}
public class Scratch {


    @Test
    public void JacksonInstant() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());

        Mumu before = new Mumu(Instant.now(), "before");
        String jsonInString = mapper.writeValueAsString(before);


        System.out.println("-- BEFORE --");
        System.out.println(before);
        System.out.println(jsonInString);

        Mumu after = mapper.readValue(jsonInString, Mumu.class);
        System.out.println("-- AFTER --");
        System.out.println(after);

        Assert.assertEquals(after.toString(), before.toString());
    }

}

How to stop INFO messages displaying on spark console?

Right after starting spark-shell type ;

sc.setLogLevel("ERROR")

In Spark 2.0 (Scala):

spark = SparkSession.builder.getOrCreate()
spark.sparkContext.setLogLevel("ERROR")

API Docs : https://spark.apache.org/docs/2.2.0/api/scala/index.html#org.apache.spark.sql.SparkSession

For Java:

spark = SparkSession.builder.getOrCreate();
spark.sparkContext().setLogLevel("ERROR");

dplyr change many data types

You can use the standard evaluation version of mutate_each (which is mutate_each_) to change the column classes:

dat %>% mutate_each_(funs(factor), l1) %>% mutate_each_(funs(as.numeric), l2)

Spring Boot Multiple Datasource

I solved the problem (How to connect multiple database using spring and Hibernate) in this way, I hope it will help :)

NOTE: I have added the relevant code, kindly make the dao with the help of impl I used in the below mentioned code.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>MultipleDatabaseConnectivityInSpring</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
     <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <load-on-startup>1</load-on-startup>
    </servlet>
     <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> 
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/dispatcher-servlet.xml
        </param-value>
    </context-param>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="localPersistenceUnitOne"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>in.india.entities.CustomerDetails</class>
        <exclude-unlisted-classes />
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
            <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
            <property name="hibernate.jdbc.batch_size" value="0" />
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/shankar?sslmode=require" />
            <property name="hibernate.connection.username" value="username" />
            <property name="hibernate.connection.password" value="password" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
        </properties>
    </persistence-unit>
    <persistence-unit name="localPersistenceUnitTwo"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>in.india.entities.CompanyDetails</class>
        <exclude-unlisted-classes />
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
            <property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
            <property name="hibernate.jdbc.batch_size" value="0" />
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/shankarTwo?sslmode=require" />
            <property name="hibernate.connection.username" value="username" />
            <property name="hibernate.connection.password" value="password" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
        </properties>
    </persistence-unit>
</persistence>

dispatcher-servlet

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:task="http://www.springframework.org/schema/task" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
    default-autowire="byName"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
      http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
      http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!-- Configure messageSource -->

    <mvc:annotation-driven />
    <context:component-scan base-package="in.india.*" />
    <bean id="messageResource"
        class="org.springframework.context.support.ResourceBundleMessageSource"
        autowire="byName">
        <property name="basename" value="messageResource"></property>
    </bean>

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>



    <bean id="entityManagerFactoryOne"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        autowire="constructor">
        <property name="persistenceUnitName" value="localPersistenceUnitOne" />
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource"
        autowire="byName">
        <property name="basename" value="messageResource" />
    </bean>

    <bean id="entityManagerFactoryTwo"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
        autowire="constructor">
        <property name="persistenceUnitName" value="localPersistenceUnitTwo" />
    </bean>

    <bean id="manager1" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactoryOne" />
    </bean>

    <bean id="manager2" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactoryTwo" />
    </bean>

    <tx:annotation-driven transaction-manager="manager1" />
    <tx:annotation-driven transaction-manager="manager2" />

    <!-- declare dependies here -->

    <bean class="in.india.service.dao.impl.CustomerServiceImpl" />
    <bean class="in.india.service.dao.impl.CompanyServiceImpl" />

    <!-- Configure MVC annotations -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
    <bean
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</beans>

java class to persist into one database

package in.india.service.dao.impl;

import in.india.entities.CompanyDetails;
import in.india.service.CompanyService;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

public class CompanyServiceImpl implements CompanyService {

    @PersistenceContext(unitName = "entityManagerFactoryTwo")
    EntityManager entityManager;

    @Transactional("manager2")
    @Override
    public boolean companyService(CompanyDetails companyDetails) {

        boolean flag = false;
        try 
        {
            entityManager.persist(companyDetails);
            flag = true;
        } 
        catch (Exception e)
        {
            flag = false;
        }

        return flag;
    }

}

java class to persist in another database

package in.india.service.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import in.india.entities.CustomerDetails;
import in.india.service.CustomerService;

public class CustomerServiceImpl implements CustomerService {

    @PersistenceContext(unitName = "localPersistenceUnitOne")
    EntityManager entityManager;

    @Override
    @Transactional(value = "manager1")
    public boolean customerService(CustomerDetails companyData) {

        boolean flag = false;
        entityManager.persist(companyData);
        return flag;
    }
}

customer.jsp

<%@page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <center>
        <h1>SpringWithMultipleDatabase's</h1>
    </center>
    <form:form method="GET" action="addCustomer.htm"  modelAttribute="customerBean" >
        <table>
            <tr>
                <td><form:label path="firstName">First Name</form:label></td>
                <td><form:input path="firstName" /></td>
            </tr>
            <tr>
                <td><form:label path="lastName">Last Name</form:label></td>
                <td><form:input path="lastName" /></td>
            </tr>
            <tr>
                <td><form:label path="emailId">Email Id</form:label></td>
                <td><form:input path="emailId" /></td>
            </tr>
            <tr>
                <td><form:label path="profession">Profession</form:label></td>
                <td><form:input path="profession" /></td>
            </tr>
            <tr>
                <td><form:label path="address">Address</form:label></td>
                <td><form:input path="address" /></td>
            </tr>
            <tr>
                <td><form:label path="age">Age</form:label></td>
                <td><form:input path="age" /></td>
            </tr>
            <tr>
                <td><input type="submit" value="Submit"/></td>
             </tr>
        </table>
    </form:form>
</body>
</html>

company.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>ScheduleJobs</title>
</head>
<body>
 <center><h1>SpringWithMultipleDatabase's</h1></center>
 <form:form method="GET" action="addCompany.htm"  modelAttribute="companyBean" >
 <table>
    <tr>
        <td><form:label path="companyName">Company Name</form:label></td>
        <td><form:input path="companyName" /></td>
    </tr>
    <tr>
        <td><form:label path="companyStrength">Company Strength</form:label></td>
        <td><form:input path="companyStrength" /></td>
    </tr>
    <tr>
        <td><form:label path="companyLocation">Company Location</form:label></td>
        <td><form:input path="companyLocation" /></td>
    </tr>
     <tr>
        <td>
            <input type="submit" value="Submit"/>
        </td>
    </tr>
 </table>
 </form:form>
</body>
</html>

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
 <center><h1>Multiple Database Connectivity In Spring sdfsdsd</h1></center>

<a href='customerRequest.htm'>Click here to go on Customer page</a>
<br>
<a href='companyRequest.htm'>Click here to go on Company page</a>
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>ScheduleJobs</title>
</head>
<body>
 <center><h1>SpringWithMultipleDatabase</h1></center>
    <b>Successfully Saved</b>
</body>
</html>

CompanyController

package in.india.controller;

import in.india.bean.CompanyBean;
import in.india.entities.CompanyDetails;
import in.india.service.CompanyService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CompanyController {

    @Autowired
    CompanyService companyService;

    @RequestMapping(value = "/companyRequest.htm", method = RequestMethod.GET)
    public ModelAndView addStudent(ModelMap model) {
        CompanyBean companyBean = new CompanyBean();
        model.addAttribute(companyBean);
        return new ModelAndView("company");
    }

    @RequestMapping(value = "/addCompany.htm", method = RequestMethod.GET)
    public ModelAndView companyController(@ModelAttribute("companyBean") CompanyBean companyBean, Model model) {
        CompanyDetails  companyDetails = new CompanyDetails();
        companyDetails.setCompanyLocation(companyBean.getCompanyLocation());
        companyDetails.setCompanyName(companyBean.getCompanyName());
        companyDetails.setCompanyStrength(companyBean.getCompanyStrength());
        companyService.companyService(companyDetails);
        return new ModelAndView("success");

    }
}

CustomerController

package in.india.controller;

import in.india.bean.CustomerBean;
import in.india.entities.CustomerDetails;
import in.india.service.CustomerService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CustomerController {

    @Autowired
    CustomerService customerService;

    @RequestMapping(value = "/customerRequest.htm", method = RequestMethod.GET)
    public ModelAndView addStudent(ModelMap model) {
        CustomerBean customerBean = new CustomerBean();
        model.addAttribute(customerBean);
        return new ModelAndView("customer");
    }

    @RequestMapping(value = "/addCustomer.htm", method = RequestMethod.GET)
    public ModelAndView customerController(@ModelAttribute("customerBean") CustomerBean customer, Model model) {
        CustomerDetails customerDetails = new CustomerDetails();
        customerDetails.setAddress(customer.getAddress());
        customerDetails.setAge(customer.getAge());
        customerDetails.setEmailId(customer.getEmailId());
        customerDetails.setFirstName(customer.getFirstName());
        customerDetails.setLastName(customer.getLastName());
        customerDetails.setProfession(customer.getProfession());
        customerService.customerService(customerDetails);
        return new ModelAndView("success");

    }
}

CompanyDetails Entity

package in.india.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name = "company_details")
public class CompanyDetails {

    @Id
    @SequenceGenerator(name = "company_details_seq", sequenceName = "company_details_seq", initialValue = 1, allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "company_details_seq")
    @Column(name = "company_details_id")
    private Long companyDetailsId;
    @Column(name = "company_name")
    private String companyName;
    @Column(name = "company_strength")
    private Long companyStrength;
    @Column(name = "company_location")
    private String companyLocation;

    public Long getCompanyDetailsId() {
        return companyDetailsId;
    }

    public void setCompanyDetailsId(Long companyDetailsId) {
        this.companyDetailsId = companyDetailsId;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public Long getCompanyStrength() {
        return companyStrength;
    }

    public void setCompanyStrength(Long companyStrength) {
        this.companyStrength = companyStrength;
    }

    public String getCompanyLocation() {
        return companyLocation;
    }

    public void setCompanyLocation(String companyLocation) {
        this.companyLocation = companyLocation;
    }
}

CustomerDetails Entity

package in.india.entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name = "customer_details")
public class CustomerDetails {

    @Id
    @SequenceGenerator(name = "customer_details_seq", sequenceName = "customer_details_seq", initialValue = 1, allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "customer_details_seq")
    @Column(name = "customer_details_id")
    private Long customerDetailsId;
    @Column(name = "first_name ")
    private String firstName;
    @Column(name = "last_name ")
    private String lastName;
    @Column(name = "email_id")
    private String emailId;
    @Column(name = "profession")
    private String profession;
    @Column(name = "address")
    private String address;
    @Column(name = "age")
    private int age;
    public Long getCustomerDetailsId() {
        return customerDetailsId;
    }

    public void setCustomerDetailsId(Long customerDetailsId) {
        this.customerDetailsId = customerDetailsId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    public String getProfession() {
        return profession;
    }

    public void setProfession(String profession) {
        this.profession = profession;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

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

How to convert data.frame column from Factor to numeric

This is FAQ 7.10. Others have shown how to apply this to a single column in a data frame, or to multiple columns in a data frame. But this is really treating the symptom, not curing the cause.

A better approach is to use the colClasses argument to read.table and related functions to tell R that the column should be numeric so that it never creates a factor and creates numeric. This will put in NA for any values that do not convert to numeric.

Another better option is to figure out why R does not recognize the column as numeric (usually a non numeric character somewhere in that column) and fix the original data so that it is read in properly without needing to create NAs.

Best is a combination of the last 2, make sure the data is correct before reading it in and specify colClasses so R does not need to guess (this can speed up reading as well).

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

https://services.gradle.org/distributions/gradle-2.1-all.zip

open this link in the browser and download the zip file and extract it to folder

Before extraction please delete the old folder whose name ends gradle-2.1-all and then you can start extracting

if you are window user extract it to this folder

C:\Users{Your-Name}.gradle\wrapper\dists

after that just restart your android studio. I hope it works it works for me .

Inline for loop

What you are using is called a list comprehension in Python, not an inline for-loop (even though it is similar to one). You would write your loop as a list comprehension like so:

p = [q.index(v) if v in q else 99999 for v in vm]

When using a list comprehension, you do not call list.append because the list is being constructed from the comprehension itself. Each item in the list will be what is returned by the expression on the left of the for keyword, which in this case is q.index(v) if v in q else 99999. Incidentially, if you do use list.append inside a comprehension, then you will get a list of None values because that is what the append method always returns.

List file using ls command in Linux with full path

You can use

  ls -lrt -d -1 "$PWD"/{*,.*}   

It will also catch hidden files.

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

You get this error because one of your variables is actually a factor variable . Execute

str(df) 

to check this. Then do this double variable change to keep the year numbers instead of transforming into "1,2,3,4" level numbers:

df$year <- as.numeric(as.character(df$year))

EDIT: it appears that your data.frame has a variable of class "array" which might cause the pb. Try then:

df <- data.frame(apply(df, 2, unclass))

and plot again?

Move seaborn plot legend to a different position?

Building on @user308827's answer: you can use legend=False in factorplot and specify the legend through matplotlib:

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot("class", "survived", "sex",
                   data=titanic, kind="bar",
                   size=6, palette="muted",
                   legend=False)
g.despine(left=True)
plt.legend(loc='upper left')
g.set_ylabels("survival probability")

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

The error

ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.

can occur if the credentials that your application is trying to use to connect to RabbitMQ are incorrect or missing.

I had this happen when the RabbitMQ credentials stored in my ASP.NET application's web.config file had a value of "" for the password instead of the actual password string value.

Efficiently getting all divisors of a given number

//DIVISORS IN TIME COMPLEXITY sqrt(n)

#include<bits/stdc++.h>
using namespace std;

#define ll long long

int main()
{
    ll int n;
    cin >> n;

    for(ll i = 2;  i <= sqrt(n); i++)
    {
        if (n%i==0)
        {
            if (n/i!=i)
                cout << i << endl << n/i<< endl;
            else
                cout << i << endl;
        }
    }
}

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.

return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);

Summarizing count and conditional aggregate functions on the same factor

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

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

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

data

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

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

How to get file name from file path in android

Old thread but thought I would update;

 File theFile = .......
 String theName = theFile.getName();  // Get the file name
 String thePath = theFile.getAbsolutePath(); // Get the full

More info can be found here; Android File Class

Python Binomial Coefficient

For everyone looking for the log of the binomial coefficient (Theano calls this binomln), this answer has it:

from numpy import log
from scipy.special import betaln

def binomln(n, k):
    "Log of scipy.special.binom calculated entirely in the log domain"
    return -betaln(1 + n - k, 1 + k) - log(n + 1)

(And if your language/library lacks betaln but has gammaln, like Go, have no fear, since betaln(a, b) is just gammaln(a) + gammaln(b) - gammaln(a + b), per MathWorld.)

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

Remove the redundant Hibernate Configuration

If you're using Spring Boot, you don't need to provide the JPA and Hibernate configuration explicitly, as Spring Boot can do that for you.

Add database configuration properties

In the application.properties Spring Boot configuration file, you have the add your database configuration properties:

spring.datasource.driverClassName = "org.postgresql.Driver
spring.datasource.url = jdbc:postgresql://localhost:5432/teste?charSet=LATIN1
spring.datasource.username = klebermo
spring.datasource.password = 123

Add Hibernate specific properties

And, in the same application.properties configuration file, you can also set custom Hibernate properties:

# Log SQL statements
spring.jpa.show-sql = false

# Hibernate ddl auto for generating the database schema
spring.jpa.hibernate.ddl-auto = create

# Hibernate database Dialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

That's it!

Rotate label text in seaborn factorplot

If anyone wonders how to this for clustermap CorrGrids (part of a given seaborn example):

import seaborn as sns
import matplotlib.pyplot as plt
sns.set(context="paper", font="monospace")

# Load the datset of correlations between cortical brain networks
df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
corrmat = df.corr()

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(12, 9))

# Draw the heatmap using seaborn
g=sns.clustermap(corrmat, vmax=.8, square=True)
rotation = 90 
for i, ax in enumerate(g.fig.axes):   ## getting all axes of the fig object
     ax.set_xticklabels(ax.get_xticklabels(), rotation = rotation)


g.fig.show()

How to use goto statement correctly

If you look up continue and break they accept a "Label". Experiment with that. Goto itself won't work.

public class BreakContinueWithLabel {

    public static void main(String args[]) {

        int[] numbers= new int[]{100,18,21,30};

        //Outer loop checks if number is multiple of 2
        OUTER:  //outer label
        for(int i = 0; i<numbers.length; i++){
            if(i % 2 == 0){
                System.out.println("Odd number: " + i +
                                   ", continue from OUTER label");
                continue OUTER;
            }

            INNER:
            for(int j = 0; j<numbers.length; j++){
                System.out.println("Even number: " + i +
                                   ", break  from INNER label");
                break INNER;
            }
        }      
    }
}

Read more

How to convert entire dataframe to numeric while preserving decimals?

You might need to do some checking. You cannot safely convert factors directly to numeric. as.character must be applied first. Otherwise, the factors will be converted to their numeric storage values. I would check each column with is.factor then coerce to numeric as necessary.

df1[] <- lapply(df1, function(x) {
    if(is.factor(x)) as.numeric(as.character(x)) else x
})
sapply(df1, class)
#         a         b 
# "numeric" "numeric" 

Unfinished Stubbing Detected in Mockito

You're nesting mocking inside of mocking. You're calling getSomeList(), which does some mocking, before you've finished the mocking for MyMainModel. Mockito doesn't like it when you do this.

Replace

@Test
public myTest(){
    MyMainModel mainModel =  Mockito.mock(MyMainModel.class);
    Mockito.when(mainModel.getList()).thenReturn(getSomeList()); --> Line 355
}

with

@Test
public myTest(){
    MyMainModel mainModel =  Mockito.mock(MyMainModel.class);
    List<SomeModel> someModelList = getSomeList();
    Mockito.when(mainModel.getList()).thenReturn(someModelList);
}

To understand why this causes a problem, you need to know a little about how Mockito works, and also be aware in what order expressions and statements are evaluated in Java.

Mockito can't read your source code, so in order to figure out what you are asking it to do, it relies a lot on static state. When you call a method on a mock object, Mockito records the details of the call in an internal list of invocations. The when method reads the last of these invocations off the list and records this invocation in the OngoingStubbing object it returns.

The line

Mockito.when(mainModel.getList()).thenReturn(someModelList);

causes the following interactions with Mockito:

  • Mock method mainModel.getList() is called,
  • Static method when is called,
  • Method thenReturn is called on the OngoingStubbing object returned by the when method.

The thenReturn method can then instruct the mock it received via the OngoingStubbing method to handle any suitable call to the getList method to return someModelList.

In fact, as Mockito can't see your code, you can also write your mocking as follows:

mainModel.getList();
Mockito.when((List<SomeModel>)null).thenReturn(someModelList);

This style is somewhat less clear to read, especially since in this case the null has to be casted, but it generates the same sequence of interactions with Mockito and will achieve the same result as the line above.

However, the line

Mockito.when(mainModel.getList()).thenReturn(getSomeList());

causes the following interactions with Mockito:

  1. Mock method mainModel.getList() is called,
  2. Static method when is called,
  3. A new mock of SomeModel is created (inside getSomeList()),
  4. Mock method model.getName() is called,

At this point Mockito gets confused. It thought you were mocking mainModel.getList(), but now you're telling it you want to mock the model.getName() method. To Mockito, it looks like you're doing the following:

when(mainModel.getList());
// ...
when(model.getName()).thenReturn(...);

This looks silly to Mockito as it can't be sure what you're doing with mainModel.getList().

Note that we did not get to the thenReturn method call, as the JVM needs to evaluate the parameters to this method before it can call the method. In this case, this means calling the getSomeList() method.

Generally it is a bad design decision to rely on static state, as Mockito does, because it can lead to cases where the Principle of Least Astonishment is violated. However, Mockito's design does make for clear and expressive mocking, even if it leads to astonishment sometimes.

Finally, recent versions of Mockito add an extra line to the error message above. This extra line indicates you may be in the same situation as this question:

3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

Spring Boot, Spring Data JPA with multiple DataSources

don't know why, but it works. Two configuration are the same, just change xxx to your name.

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef = "xxxEntityManager",
    transactionManagerRef = "xxxTransactionManager",
    basePackages = {"aaa.xxx"})
 public class RepositoryConfig {
@Autowired
private Environment env;

@Bean
@Primary
@ConfigurationProperties(prefix="datasource.xxx")
public DataSource xxxDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
public LocalContainerEntityManagerFactoryBean xxxEntityManager() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(xxxDataSource());
    em.setPackagesToScan(new String[] {"aaa.xxx"});

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    HashMap<String, Object> properties = new HashMap<String, Object>();
    properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
    properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
    properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
    em.setJpaPropertyMap(properties);

    return em;
}

@Bean(name = "xxxTransactionManager")
public PlatformTransactionManager xxxTransactionManager() {
    JpaTransactionManager tm = new JpaTransactionManager();
    tm.setEntityManagerFactory(xxxEntityManager().getObject());
    return tm;
}

}

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

Check your dao class. It must be like this:

Session session = getCurrentSession();
Query query = session.createQuery(GET_ALL);

And annotations:

@Transactional
@Repository

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"defer</script>

Add Defer to the end of your Script tag, it worked for me (;

Everything needs to be loaded in the correct order (:

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

I solved it by doing this:

  1. Copy the file content.
  2. Remove file.
  3. Run command: php artisan make:seeder .
  4. Copy the file content back in this file.

This happened because I made a change in the filename. I don't know why it didn't work after the change.

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

See my post here

How are you? I had the same problem while i was trying connect to MSSQL Server remotely using jdbc (dbeaver on debian).

After a while, i found out that my firewall configuration was not correctly. So maybe it could help you!

Configure the firewall to allow network traffic that is related to SQL Server and to the SQL Server Browser service.

Four exceptions must be configured in Windows Firewall to allow access to SQL Server:

A port exception for TCP Port 1433. In the New Inbound Rule Wizard dialog, use the following information to create a port exception: Select Port Select TCP and specify port 1433 Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule “SQL – TCP 1433" A port exception for UDP Port 1434. Click New Rule again and use the following information to create another port exception: Select Port Select UDP and specify port 1434 Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule “SQL – UDP 1434 A program exception for sqlservr.exe. Click New Rule again and use the following information to create a program exception: Select Program Click Browse to select ‘sqlservr.exe’ at this location: [C:\Program Files\Microsoft SQL Server\MSSQL11.\MSSQL\Binn\sqlservr.exe] where is the name of your SQL instance. Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule SQL – sqlservr.exe A program exception for sqlbrowser.exe Click New Rule again and use the following information to create another program exception: Select Program Click Browse to select sqlbrowser.exe at this location: [C:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe]. Allow the connection Choose all three profiles (Domain, Private & Public) Name the rule SQL - sqlbrowser.exe

Source: http://blog.citrix24.com/configure-sql-express-to-accept-remote-connections/

How to count how many values per level in a given factor?

Or using the dplyr library:

library(dplyr)
set.seed(1)
dat <- data.frame(ID = sample(letters,100,rep=TRUE))
dat %>% 
  group_by(ID) %>%
  summarise(no_rows = length(ID))

Note the use of %>%, which is similar to the use of pipes in bash. Effectively, the code above pipes dat into group_by, and the result of that operation is piped into summarise.

The result is:

Source: local data frame [26 x 2]

   ID no_rows
1   a       2
2   b       3
3   c       3
4   d       3
5   e       2
6   f       4
7   g       6
8   h       1
9   i       6
10  j       5
11  k       6
12  l       4
13  m       7
14  n       2
15  o       2
16  p       2
17  q       5
18  r       4
19  s       5
20  t       3
21  u       8
22  v       4
23  w       5
24  x       4
25  y       3
26  z       1

See the dplyr introduction for some more context, and the documentation for details regarding the individual functions.

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

In my case, the application context is not loaded because I add @DataJpaTest annotation. When I change it to @SpringBootTest it works.

@DataJpaTest only loads the JPA part of a Spring Boot application. In the JavaDoc:

Annotation that can be used in combination with @RunWith(SpringRunner.class) for a typical JPA test. Can be used when a test focuses only on JPA components. Using this annotation will disable full auto-configuration and instead apply only configuration relevant to JPA tests.

By default, tests annotated with @DataJpaTest will use an embedded in-memory database (replacing any explicit or usually auto-configured DataSource). The @AutoConfigureTestDatabase annotation can be used to override these settings. If you are looking to load your full application configuration, but use an embedded database, you should consider @SpringBootTest combined with @AutoConfigureTestDatabase rather than this annotation.

sum two columns in R

You can do this :

    df <- data.frame("a" = c(1,2,3,4), "b" = c(4,3,2,1), "x_ind" = c(1,0,1,1), "y_ind" = c(0,0,1,1), "z_ind" = c(0,1,1,1) )
df %>% mutate( bi  = ifelse((df$x_ind + df$y_ind +df$z_ind)== 3, 1,0 ))

Java ElasticSearch None of the configured nodes are available

Check the ES server logs

sudo tail -f /var/log/elasticsearch/elasticsearch.log

I was using an outdated client

Received message from unsupported version: [5.0.0] minimal compatible version is: [6.8.0]

Problems using Maven and SSL behind proxy

The answer above is a good working solution, but here's how to do it if you want to use the SSL repo:

  • Use a browser (I used IE) to go to https://repo.maven.apache.org/
    • Click on lock icon and choose "View Certificate"
    • Go to the "Details" tab and choose "Save to File"
    • Choose type "Base 64 X.509 (.CER)" and save it somewhere
  • Now open a command prompt and type (use your own paths):

    keytool -import -file C:\temp\mavenCert.cer -keystore C:\temp\mavenKeystore

  • Now you can run the command again with the parameter

    -Djavax.net.ssl.trustStore=C:\temp\mavenKeystore

  • Under linux use absolute path

    -Djavax.net.ssl.trustStore=/tmp/mavenKeystore

    otherwise this will happen

  • Like this:

    mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false -Djavax.net.ssl.trustStore=C:\temp\mavenKeystore

Optional:

You can use the MAVEN_OPTS environment variable so you don't have to worry about it again. See more info on the MAVEN_OPTS variable here:

How to change package name in android studio?

Another good method is: First create a new package with the desired name by right clicking on the java folder -> new -> package.

Then, select and drag all your classes to the new package. Android Studio will refactor the package name everywhere.

Finally, delete the old package.

or Look into this post

TransactionRequiredException Executing an update/delete query

Faced the same problem, I simply forgot to activate the transaction management with the @EnableTransactionManagement annotation.

Ref:

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/annotation/EnableTransactionManagement.html

Spring Boot application.properties value not populating

follow these steps. 1:- create your configuration class like below you can see

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;

@Configuration
public class YourConfiguration{

    // passing the key which you set in application.properties
    @Value("${some.pro}")
    private String somePro;

   // getting the value from that key which you set in application.properties
    @Bean
    public String getsomePro() {
        return somePro;
    }
}

2:- when you have a configuration class then inject in the variable from a configuration where you need.

@Component
public class YourService {

    @Autowired
    private String getsomePro;

    // now you have a value in getsomePro variable automatically.
}

How to solve java.lang.OutOfMemoryError trouble in Android

Few hints to handle such error/exception for Android Apps:

  1. Activities & Application have methods like:

    • onLowMemory
    • onTrimMemory Handle these methods to watch on memory usage.
  2. tag in Manifest can have attribute 'largeHeap' set to TRUE, which requests more heap for App sandbox.

  3. Managing in-memory caching & disk caching:

    • Images and other data could have been cached in-memory while app running, (locally in activities/fragment and globally); should be managed or removed.
  4. Use of WeakReference, SoftReference of Java instance creation , specifically to files.

  5. If so many images, use proper library/data structure which can manage memory, use samling of images loaded, handle disk-caching.

  6. Handle OutOfMemory exception

  7. Follow best practices for coding

    • Leaking of memory (Don't hold everything with strong reference)
  8. Minimize activity stack e.g. number of activities in stack (Don't hold everything on context/activty)

    • Context makes sense, those data/instances not required out of scope (activity and fragments), hold them into appropriate context instead global reference-holding.
  9. Minimize the use of statics, many more singletons.

  10. Take care of OS basic memory fundametals

    • Memory fragmentation issues
  11. Involk GC.Collect() manually sometimes when you are sure that in-memory caching no more needed.

Multipart File upload Spring Boot

@RequestBody MultipartFile[] submissions

should be

@RequestParam("file") MultipartFile[] submissions

The files are not the request body, they are part of it and there is no built-in HttpMessageConverter that can convert the request to an array of MultiPartFile.

You can also replace HttpServletRequest with MultipartHttpServletRequest, which gives you access to the headers of the individual parts.

Trusting all certificates with okHttp

Following method is deprecated

sslSocketFactory(SSLSocketFactory sslSocketFactory)

Consider updating it to

sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)

Spring Boot Remove Whitelabel Error Page

Spring Boot by default has a “whitelabel” error page which you can see in a browser if you encounter a server error. Whitelabel Error Page is a generic Spring Boot error page which is displayed when no custom error page is found.

Set “server.error.whitelabel.enabled=false” to switch of the default error page

How can I change the font size using seaborn FacetGrid?

I've made small modifications to @paul-H code, such that you can set the font size for the x/y axes and legend independently. Hope it helps:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)

# defaults                                                                                                         
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', fontsize=20,bbox_to_anchor=(0, 1.1))
ax.set_xlabel('X_axi',fontsize=20);
ax.set_ylabel('Y_axis',fontsize=20);

plt.show()

This is the output:

enter image description here

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

Have you tried passing -funroll-loops -fprefetch-loop-arrays to GCC?

I get the following results with these additional optimizations:

[1829] /tmp/so_25078285 $ cat /proc/cpuinfo |grep CPU|head -n1
model name      : Intel(R) Core(TM) i3-3225 CPU @ 3.30GHz
[1829] /tmp/so_25078285 $ g++ --version|head -n1
g++ (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3

[1829] /tmp/so_25078285 $ g++ -O3 -march=native -std=c++11 test.cpp -o test_o3
[1829] /tmp/so_25078285 $ g++ -O3 -march=native -funroll-loops -fprefetch-loop-arrays -std=c++11     test.cpp -o test_o3_unroll_loops__and__prefetch_loop_arrays

[1829] /tmp/so_25078285 $ ./test_o3 1
unsigned        41959360000     0.595 sec       17.6231 GB/s
uint64_t        41959360000     0.898626 sec    11.6687 GB/s

[1829] /tmp/so_25078285 $ ./test_o3_unroll_loops__and__prefetch_loop_arrays 1
unsigned        41959360000     0.618222 sec    16.9612 GB/s
uint64_t        41959360000     0.407304 sec    25.7443 GB/s

Spring Boot - Handle to Hibernate SessionFactory

It works with Spring Boot 2.1.0 and Hibernate 5

@PersistenceContext
private EntityManager entityManager;

Then you can create new Session by using entityManager.unwrap(Session.class)

Session session = null;
if (entityManager == null
    || (session = entityManager.unwrap(Session.class)) == null) {

    throw new NullPointerException();
}

example create query:

session.createQuery("FROM Student");

application.properties:

spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:db11g
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect

Can Linux apps be run in Android?

Android does not run X Windows, nor does it have many of the standard GNU libraries. So, since most native linux applications require one or both of these, most will not run.

In addition, even Java programs can be limited, because the version of Java that Android applications are written in is a subset of the standard Java library.

Django set default form values

Other solution: Set initial after creating the form:

form.fields['tank'].initial = 123

crudrepository findBy method signature with multiple in operators?

The following signature will do:

List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);

Spring Data JPA supports a large number of keywords to build a query. IN and AND are among them.

php: catch exception and continue execution, is it possible?

php > 7

use the new interface Throwable

    try {
        // Code that may throw an Exception or Error.
    } catch (Throwable $t) {
        // Handle exception
    }

echo "Script is still running..."; // this script will be executed.

XmlSerializer giving FileNotFoundException at constructor

I was getting the same error, and it was due to the type I was trying to deserialize not having a default parameterless constructor. I added a constructor, and it started working.

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

For OSX it's even easier. Your machine should come with a version of Apache already installed. All you need to do is locate the php lib for that version (which is likely 5.2.x) and swap it out.

This is the command you'd run from terminal*

cp /usr/libexec/apache2/libphp5.so /Applications/XAMPP/xamppfiles/modules/libphp5.so

I tested this on 10.5 (Leopard), so ymmv. * all the caveats about this might break your system, make a backup, blah blah blah.

Edit: On 10.4 (Tiger), Xampp 1.73, using the libphp5.so-files found at Mamp, this does not work at all.

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

I was facing the same issue. So, i created a stored Procedure and defined the size like @FromDate datetime, @ToDate datetime, @BL varchar(50)

After defining the size in @BL varchar(50), i did not face any problem. Now it is working fine

How exactly does __attribute__((constructor)) work?

Here is another concrete example.It is for a shared library. The shared library's main function is to communicate with a smart card reader. But it can also receive 'configuration information' at runtime over udp. The udp is handled by a thread which MUST be started at init time.

__attribute__((constructor))  static void startUdpReceiveThread (void) {
    pthread_create( &tid_udpthread, NULL, __feigh_udp_receive_loop, NULL );
    return;

  }

The library was written in c.

package javax.servlet.http does not exist

Try:

javac -cp .;"C:\Users\User Name\Tomcat\apache-tomcat-7.0.108\lib\servlet-api.jar" HelloServlet.java

using windows if there are spaces in your class path.

Attach the Java Source Code

Old question, be here's what I ended up using Java Source Attatcher plugin: http://marketplace.eclipse.org/content/java-source-attacher#.U85j4rF-N7s

It can provide source for different opensource projects. One weird thing thou, if you have libraries under libs folder, you cannot attach from there, but you need to attach source clicking on jar displayed under "Libraries from external".

How to open every file in a folder

You can actually just use os module to do both:

  1. list all files in a folder
  2. sort files by file type, file name etc.

Here's a simple example:

import os #os module imported here
location = os.getcwd() # get present working directory location here
counter = 0 #keep a count of all files found
csvfiles = [] #list to store all csv files found at location
filebeginwithhello = [] # list to keep all files that begin with 'hello'
otherfiles = [] #list to keep any other file that do not match the criteria

for file in os.listdir(location):
    try:
        if file.endswith(".csv"):
            print "csv file found:\t", file
            csvfiles.append(str(file))
            counter = counter+1

        elif file.startswith("hello") and file.endswith(".csv"): #because some files may start with hello and also be a csv file
            print "csv file found:\t", file
            csvfiles.append(str(file))
            counter = counter+1

        elif file.startswith("hello"):
            print "hello files found: \t", file
            filebeginwithhello.append(file)
            counter = counter+1

        else:
            otherfiles.append(file)
            counter = counter+1
    except Exception as e:
        raise e
        print "No files found here!"

print "Total files found:\t", counter

Now you have not only listed all the files in a folder but also have them (optionally) sorted by starting name, file type and others. Just now iterate over each list and do your stuff.

Disable scrolling on `<input type=number>`

@Semyon Perepelitsa

There is a better solution for this. Blur removes the focus from the input and that is a side affect that you do not want. You should use evt.preventDefault instead. This prevents the default behavior of the input when the user scrolls. Here is the code:

input = document.getElementById("the_number_input")
input.addEventListener("mousewheel", function(evt){ evt.preventDefault(); })

Disallow Twitter Bootstrap modal window from closing

Kind of like @AymKdn's answer, but this will allow you to change the options without re-initializing the modal.

$('#myModal').data('modal').options.keyboard = false;

Or if you need to do multiple options, JavaScript's with comes in handy here!

with ($('#myModal').data("modal").options) {
    backdrop = 'static';
    keyboard = false;
}

If the modal is already open, these options will only take effect the next time the modal is opened.

Difference between \b and \B in regex

The confusion stems from your thinking \b matches spaces (probably because "b" suggests "blank").

\b matches the empty string at the beginning or end of a word. \B matches the empty string not at the beginning or end of a word. The key here is that "-" is not a part of a word. So <left>-<right> matches \b-\b because there are word boundaries on either side of the -. On the other hand for <left> - <right> (note the spaces), there are not word boundaries on either side of the dash. The word boundaries are one space further left and right.

On the other hand, when searching for \bcat\b word boundaries behave more intuitively, and it matches " cat " as expected.

Microsoft Excel ActiveX Controls Disabled?

Here is the best answer that I have found on the Microsoft Excel Support Team Blog

For some users, Forms Controls (FM20.dll) are no longer working as expected after installing December 2014 updates. Issues are experienced at times such as when they open files with existing VBA projects using forms controls, try to insert a forms control in to a new worksheet or run third party software that may use these components.

You may received errors such as:

"Cannot insert object" "Object library invalid or contains references to object definitions that could not be found"

Additionally, you may be unable to use or change properties of an ActiveX control on a worksheet or receive an error when trying to refer to an ActiveX control as a member of a worksheet via code. Steps to follow after the update:

To resolve this issue, you must delete the cached versions of the control type libraries (extender files) on the client computer. To do this, you must search your hard disk for files that have the ".exd" file name extension and delete all the .exd files that you find. These .exd files will be re-created automatically when you use the new controls the next time that you use VBA. These extender files will be under the user's profile and may also be in other locations, such as the following:

%appdata%\Microsoft\forms

%temp%\Excel8.0

%temp%\VBE

Scripting solution:

Because this problem may affect more than one machine, it is also possible to create a scripting solution to delete the EXD files and run the script as part of the logon process using a policy. The script you would need should contain the following lines and would need to be run for each USER as the .exd files are USER specific.

del %temp%\vbe\*.exd

del %temp%\excel8.0\*.exd

del %appdata%\microsoft\forms\*.exd

del %appdata%\microsoft\local\*.exd

del %appdata%\Roaming\microsoft\forms\*.exd

del %temp%\word8.0\*.exd

del %temp%\PPT11.0\*.exd

Additional step:

If the steps above do not resolve your issue, another step that can be tested (see warning below):

  1. On a fully updated machine and after removing the .exd files, open the file in Excel with edit permissions.

    Open Visual Basic for Applications > modify the project by adding a comment or edit of some kind to any code module > Debug > Compile VBAProject.

    Save and reopen the file. Test for resolution. If resolved, provide this updated project to additional users.

    Warning: If this step resolves your issue, be aware that after deploying this updated project to the other users, these users will also need to have the updates applied on their systems and .exd files removed as well.

If this does not resolve your issue, it may be a different issue and further troubleshooting may be necessary.

Microsoft is currently working on this issue. Watch the blog for updates.

Source

How to add a custom right-click menu to a webpage?

A combination of some nice CSS and some non-standard html tags with no external libraries can give a nice result (JSFiddle)

HTML

<menu id="ctxMenu">
    <menu title="File">
        <menu title="Save"></menu>
        <menu title="Save As"></menu>
        <menu title="Open"></menu>
    </menu>
    <menu title="Edit">
        <menu title="Cut"></menu>
        <menu title="Copy"></menu>
        <menu title="Paste"></menu>
    </menu>
</menu>

Note: the menu tag does not exist, I'm making it up (you can use anything)

CSS

#ctxMenu{
    display:none;
    z-index:100;
}
menu {
    position:absolute;
    display:block;
    left:0px;
    top:0px;
    height:20px;
    width:20px;
    padding:0;
    margin:0;
    border:1px solid;
    background-color:white;
    font-weight:normal;
    white-space:nowrap;
}
menu:hover{
    background-color:#eef;
    font-weight:bold;
}
menu:hover > menu{
    display:block;
}
menu > menu{
    display:none;
    position:relative;
    top:-20px;
    left:100%;
    width:55px;
}
menu[title]:before{
    content:attr(title);
}
menu:not([title]):before{
    content:"\2630";
}

The JavaScript is just for this example, I personally remove it for persistent menus on windows

var notepad = document.getElementById("notepad");
notepad.addEventListener("contextmenu",function(event){
    event.preventDefault();
    var ctxMenu = document.getElementById("ctxMenu");
    ctxMenu.style.display = "block";
    ctxMenu.style.left = (event.pageX - 10)+"px";
    ctxMenu.style.top = (event.pageY - 10)+"px";
},false);
notepad.addEventListener("click",function(event){
    var ctxMenu = document.getElementById("ctxMenu");
    ctxMenu.style.display = "";
    ctxMenu.style.left = "";
    ctxMenu.style.top = "";
},false);

Also note, you can potentially modify menu > menu{left:100%;} to menu > menu{right:100%;} for a menu that expands from right to left. You would need to add a margin or something somewhere though

Jupyter notebook not running code. Stuck on In [*]

Based on you kernel status (upper right beside "Python 3", the one that is a circle). It seems that it is still busy. It might be trapped in an endless loop or maybe you've run/display something that is not closed.

How to install a package inside virtualenv?

I had the same issue and the --no-site-packages did not work for me. I discovered on this older mailing list archive that you are able to force an installation in the virtualenv using the -U flag for pip, eg pip -U ipython. You may verify this works using the bash command which ipython while in the virtualenv.

source: https://mail.python.org/pipermail/python-list/2010-March/571663.html

Index all *except* one item in python

If you want to cut out the last or the first do this:

list = ["This", "is", "a", "list"]
listnolast = list[:-1]
listnofirst = list[1:]

If you change 1 to 2 the first 2 characters will be removed not the second. Hope this still helps!

How do you read CSS rule values with JavaScript?

I created a version that searches all stylesheets and returns matches as a key/value object. You can also specify startsWith to match child styles.

getStylesBySelector('.pure-form-html', true);

returns:

{
    ".pure-form-html body": "padding: 0; margin: 0; font-size: 14px; font-family: tahoma;",
    ".pure-form-html h1": "margin: 0; font-size: 18px; font-family: tahoma;"
}

from:

.pure-form-html body {
    padding: 0;
    margin: 0;
    font-size: 14px;
    font-family: tahoma;
}

.pure-form-html h1 {
    margin: 0;
    font-size: 18px;
    font-family: tahoma;
}

The code:

/**
 * Get all CSS style blocks matching a CSS selector from stylesheets
 * @param {string} className - class name to match
 * @param {boolean} startingWith - if true matches all items starting with selector, default = false (exact match only)
 * @example getStylesBySelector('pure-form .pure-form-html ')
 * @returns {object} key/value object containing matching styles otherwise null
 */
function getStylesBySelector(className, startingWith) {

    if (!className || className === '') throw new Error('Please provide a css class name');

    var styleSheets = window.document.styleSheets;
    var result = {};

    // go through all stylesheets in the DOM
    for (var i = 0, l = styleSheets.length; i < l; i++) {

        var classes = styleSheets[i].rules || styleSheets[i].cssRules || [];

        // go through all classes in each document
        for (var x = 0, ll = classes.length; x < ll; x++) {

            var selector = classes[x].selectorText || '';
            var content = classes[x].cssText || classes[x].style.cssText || '';

            // if the selector matches
            if ((startingWith && selector.indexOf(className) === 0) || selector === className) {

                // create an object entry with selector as key and value as content
                result[selector] = content.split(/(?:{|})/)[1].trim();
            }
        }
    }

    // only return object if we have values, otherwise null
    return Object.keys(result).length > 0 ? result : null;
}

I'm using this in production as part of the pure-form project. Hope it helps.

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

format statement in a string resource file

You do not need to use formatted="false" in your XML. You just need to use fully qualified string format markers - %[POSITION]$[TYPE] (where [POSITION] is the attribute position and [TYPE] is the variable type), rather than the short versions, for example %s or %d.

Quote from Android Docs: String Formatting and Styling:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal integer. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = res.getString(R.string.welcome_messages, username, mailCount);

See :hover state in Chrome Developer Tools

I wanted to see the hover state on my Bootstrap tooltips. Forcing the the :hover state in Chrome dev Tools did not create the required output, yet triggering the mouseenter event via console did the trick in Chrome. If jQuery exists on the page you can run:

$('.YOUR-TOOL-TIP-CLASS').trigger('mouseenter');

Forcing hover or mouseenter for Bootstrap Tooltips

json_encode sparse PHP array as JSON array, not JSON object

Try this,

<?php
$arr1=array('result1'=>'abcd','result2'=>'efg'); 
$arr2=array('result1'=>'hijk','result2'=>'lmn'); 
$arr3=array($arr1,$arr2); 
print (json_encode($arr3)); 
?>

Excel: Search for a list of strings within a particular string using array formulas?

  1. Arange your word list with delimiter which never occures in the words, f.e. |
  2. swap arguments in find call - we want search if cell value is matching one of the words in pattern string {=FIND("cell I want to search","list of words I want to search for")}
  3. if the patterns are similar, there is a risk of getting more results than wanted, we restrict just correct results via adding &"|" to the cell value tested (works well with array formulas) cell G3 could contain: {=SUM(FIND($A$1:$A$100&"|";A3))} this ensures spreadsheet will compare strings like "cellvlaue|" againts "pattern1|", "pattern2|" etc. which sorts out conflicts like pattern1="newly added", pattern2="added" (sum of all cells matching "added" would be too high, including the target values for cells matching "newly added", which would be a logical error)

How to convert any date format to yyyy-MM-dd

Try this code:

 lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");

Fully change package name including company domain

You can do this:

Change the package name manually in the manifest file. Click on your R.java class and the press F6 (Refactor->Move...). It will allow you to move the class to other package, and all references to that class will be updated.

reference: How do I rename the android package name?

Escaping Strings in JavaScript

You can also use this

_x000D_
_x000D_
let str = "hello single ' double \" and slash \\ yippie";

let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));
_x000D_
_x000D_
_x000D_

Why use argparse rather than optparse?

At first I was as reluctant as @fmark to switch from optparse to argparse, because:

  1. I thought the difference was not that huge.
  2. Quite some VPS still provides Python 2.6 by default.

Then I saw this doc, argparse outperforms optparse, especially when talking about generating meaningful help message: http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html

And then I saw "argparse vs. optparse" by @Nicholas, saying we can have argparse available in python <2.7 (Yep, I didn't know that before.)

Now my two concerns are well addressed. I wrote this hoping it will help others with a similar mindset.

cell format round and display 2 decimal places

I use format, Number, 2 decimal places & tick ' use 1000 separater ', then go to 'File', 'Options', 'Advanced', scroll down to 'When calculating this workbook' and tick 'set precision as displayed'. You get an error message about losing accuracy, that's good as it means it is rounding to 2 decimal places. So much better than bothering with adding a needless ROUND function.

Open an image using URI in Android's default gallery image viewer

My solution using File Provider

    private void viewGallery(File file) {

 Uri mImageCaptureUri = FileProvider.getUriForFile(
  mContext,
  mContext.getApplicationContext()
  .getPackageName() + ".provider", file);

 Intent view = new Intent();
 view.setAction(Intent.ACTION_VIEW);
 view.setData(mImageCaptureUri);
 List < ResolveInfo > resInfoList =
  mContext.getPackageManager()
  .queryIntentActivities(view, PackageManager.MATCH_DEFAULT_ONLY);
 for (ResolveInfo resolveInfo: resInfoList) {
  String packageName = resolveInfo.activityInfo.packageName;
  mContext.grantUriPermission(packageName, mImageCaptureUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
 }
 view.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 Intent intent = new Intent();
 intent.setAction(Intent.ACTION_VIEW);
 intent.setDataAndType(mImageCaptureUri, "image/*");
 mContext.startActivity(intent);
}

How to create an Oracle sequence starting with max value from a table?

You can't use a subselect inside a CREATE SEQUENCE statement. You'll have to select the value beforehand.

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

Re-entering credentials will help to start the services:

  1. Start > Services
  2. Right click on SQL Sever > Properties
  3. Log On
  4. Re-enter credentials and apply
  5. Start the services now

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");

How to return the output of stored procedure into a variable in sql server

Use this code, Working properly

CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT

AS
Begin
 DECLARE @cnt int;
 DECLARE @status int =0;
 SET NOCOUNT OFF
 SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
 if(@cnt = 1)
   Begin
     return @status;
   End
 else
  Begin
   SET @status =1;
    return @status;
 End
END

Execute SP

DECLARE @statuss bit;
EXECUTE  [dbo].[sp_delete_item] 6, @statuss output;
PRINT @statuss;

How to center an unordered list?

To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element.

Now, add the style to the div class and use the text-align property with center as its value.

See the below example.

<style>
.myDivElement{
    text-align:center;
}
.myDivElement ul li{
   display:inline;

 }
</style>
<div class="myDivElement">
<ul>
    <li>Home</li>
    <li>About</li>
    <li>Gallery</li>
    <li>Contact</li>
</ul>
</div>

Here is the reference website Center Align Unordered List

Unknown SSL protocol error in connection

According to bitbucket knowledgebase it may also be caused by the owner of the repository being over the plan limit.

If you look further down the page it seems to also be possible to trig this error by using a too old git version (1.7 is needed at the moment).

How to move div vertically down using CSS

Give margin-top

div{margin-top:10px;}

How to find difference between two columns data?

IF the table is alias t

SELECT t.Present , t.previous, t.previous- t.Present AS Difference
FROM   temp1 as t

Vertical Align Center in Bootstrap 4

use .my-auto (bootsrap4) css class on yor div

JAX-WS client : what's the correct path to access the local WSDL?

For those who are still coming for solution here, the easiest solution would be to use <wsdlLocation>, without changing any code. Working steps are given below:

  1. Put your wsdl to resource directory like : src/main/resource
  2. In pom file, add both wsdlDirectory and wsdlLocation(don't miss / at the beginning of wsdlLocation), like below. While wsdlDirectory is used to generate code and wsdlLocation is used at runtime to create dynamic proxy.

    <wsdlDirectory>src/main/resources/mydir</wsdlDirectory>
    <wsdlLocation>/mydir/my.wsdl</wsdlLocation>
    
  3. Then in your java code(with no-arg constructor):

    MyPort myPort = new MyPortService().getMyPort();
    
  4. For completeness, I am providing here full code generation part, with fluent api in generated code.

    <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxws-maven-plugin</artifactId>
    <version>2.5</version>
    
    <dependencies>
        <dependency>
            <groupId>org.jvnet.jaxb2_commons</groupId>
            <artifactId>jaxb2-fluent-api</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>jaxws-tools</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>
    
    <executions>
        <execution>
            <id>wsdl-to-java-generator</id>
            <goals>
                <goal>wsimport</goal>
            </goals>
            <configuration>
                <xjcArgs>
                    <xjcArg>-Xfluent-api</xjcArg>
                </xjcArgs>
                <keep>true</keep>
                <wsdlDirectory>src/main/resources/package</wsdlDirectory>
                <wsdlLocation>/package/my.wsdl</wsdlLocation>
                <sourceDestDir>${project.build.directory}/generated-sources/annotations/jaxb</sourceDestDir>
                <packageName>full.package.here</packageName>
            </configuration>
        </execution>
    </executions>
    

How do I get the RootViewController from a pushed controller?

Use the viewControllers property of the UINavigationController. Example code:

// Inside another ViewController
NSArray *viewControllers = self.navigationController.viewControllers;
UIViewController *rootViewController = [viewControllers objectAtIndex:viewControllers.count - 2];

This is the standard way of getting the "back" view controller. The reason objectAtIndex:0 works is because the view controller you're trying to access is also the root one, if you were deeper in the navigation, the back view would not be the same as the root view.

Toggle input disabled attribute using jQuery

$('#el').prop('disabled', function(i, v) { return !v; });

The .prop() method accepts two arguments:

  • Property name (disabled, checked, selected) anything that is either true or false
  • Property value, can be:
    • (empty) - returns the current value.
    • boolean (true/false) - sets the property value.
    • function - Is executed for each found element, the returned value is used to set the property. There are two arguments passed; the first argument is the index (0, 1, 2, increases for each found element). The second argument is the current value of the element (true/false).

So in this case, I used a function that supplied me the index (i) and the current value (v), then I returned the opposite of the current value, so the property state is reversed.

How to set a dropdownlist item as selected in ASP.NET?

dropdownlist.ClearSelection(); //making sure the previous selection has been cleared
dropdownlist.Items.FindByValue(value).Selected = true;

iframe refuses to display

The reason for the error is that the host server for https://cw.na1.hgncloud.com has provided some HTTP headers to protect the document. One of which is that the frame ancestors must be from the same domain as the original content. It seems you are attempting to put the iframe at a domain location that is not the same as the content of the iframe - thus violating the Content Security Policy that the host has set.

Check out this link on Content Security Policy for more details.

How to pass objects to functions in C++?

Since no one mentioned I am adding on it, When you pass a object to a function in c++ the default copy constructor of the object is called if you dont have one which creates a clone of the object and then pass it to the method, so when you change the object values that will reflect on the copy of the object instead of the original object, that is the problem in c++, So if you make all the class attributes to be pointers, then the copy constructors will copy the addresses of the pointer attributes , so when the method invocations on the object which manipulates the values stored in pointer attributes addresses, the changes also reflect in the original object which is passed as a parameter, so this can behave same a Java but dont forget that all your class attributes must be pointers, also you should change the values of pointers, will be much clear with code explanation.

Class CPlusPlusJavaFunctionality {
    public:
       CPlusPlusJavaFunctionality(){
         attribute = new int;
         *attribute = value;
       }

       void setValue(int value){
           *attribute = value;
       }

       void getValue(){
          return *attribute;
       }

       ~ CPlusPlusJavaFuncitonality(){
          delete(attribute);
       }

    private:
       int *attribute;
}

void changeObjectAttribute(CPlusPlusJavaFunctionality obj, int value){
   int* prt = obj.attribute;
   *ptr = value;
}

int main(){

   CPlusPlusJavaFunctionality obj;

   obj.setValue(10);

   cout<< obj.getValue();  //output: 10

   changeObjectAttribute(obj, 15);

   cout<< obj.getValue();  //output: 15
}

But this is not good idea as you will be ending up writing lot of code involving with pointers, which are prone for memory leaks and do not forget to call destructors. And to avoid this c++ have copy constructors where you will create new memory when the objects containing pointers are passed to function arguments which will stop manipulating other objects data, Java does pass by value and value is reference, so it do not require copy constructors.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

As an alternative you may want to check out BridgeIt at bridgeit.mobi. Open source, it has resolved the browser performance / consistency issue discussed above in that it leverages the standard browser on the device vs. the web-view browser. It also allows you to access the native features without having to worry about app store deployments and/or native containers.

I've used if for simple camera based access and scanner access and it works well for simple apps. Documentation is a bit light. Not sure how it would do on more complex apps.

Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

You can check for the Installed value to be 1 in this registry location: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\11.0\VC\Runtimes\x86 on 64-bit systems. In code that would result in accessing registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\11.0\VC\Runtimes\x86. Notice the absence of Wow6432Node.

On a 32-bit system the registry is the same without Wow6432Node: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\11.0\VC\Runtimes\x86

req.query and req.param in ExpressJS

req.query is the query string sent to the server, example /page?test=1, req.param is the parameters passed to the handler.

app.get('/user/:id', handler);, going to /user/blah, req.param.id would return blah;

How do I import a Swift file from another Swift file?

Check your PrimeNumberModelTests Target Settings.

If you can't see PrimeNumberModel.swift file in Build Phases/Compile Sources, add it.

ImportError: Cannot import name X

You have circular dependent imports. physics.py is imported from entity before class Ent is defined and physics tries to import entity that is already initializing. Remove the dependency to physics from entity module.

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

You could use Microsoft.AspNetCore.Mvc.ControllerBase.StatusCode and Microsoft.AspNetCore.Http.StatusCodes to form your response, if you don't wish to hardcode specific numbers.

return  StatusCode(StatusCodes.Status500InternalServerError);

UPDATE: Aug 2019

Perhaps not directly related to the original question but when trying to achieve the same result with Microsoft Azure Functions I found that I had to construct a new StatusCodeResult object found in the Microsoft.AspNetCore.Mvc.Core assembly. My code now looks like this;

return new StatusCodeResult(StatusCodes.Status500InternalServerError);

Use LINQ to get items in one List<>, that are not in another List<>

Bit late to the party but a good solution which is also Linq to SQL compatible is:

List<string> list1 = new List<string>() { "1", "2", "3" };
List<string> list2 = new List<string>() { "2", "4" };

List<string> inList1ButNotList2 = (from o in list1
                                   join p in list2 on o equals p into t
                                   from od in t.DefaultIfEmpty()
                                   where od == null
                                   select o).ToList<string>();

List<string> inList2ButNotList1 = (from o in list2
                                   join p in list1 on o equals p into t
                                   from od in t.DefaultIfEmpty()
                                   where od == null
                                   select o).ToList<string>();

List<string> inBoth = (from o in list1
                       join p in list2 on o equals p into t
                       from od in t.DefaultIfEmpty()
                       where od != null
                       select od).ToList<string>();

Kudos to http://www.dotnet-tricks.com/Tutorial/linq/UXPF181012-SQL-Joins-with-C

How does createOrReplaceTempView work in Spark?

SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.

In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.

In order to create the view, developer need an utility called createOrReplaceTempView

JavaScript alert box with timer

setTimeout( function ( ) { alert( "moo" ); }, 10000 ); //displays msg in 10 seconds

Understanding the results of Execute Explain Plan in Oracle SQL Developer

In recent Oracle versions the COST represent the amount of time that the optimiser expects the query to take, expressed in units of the amount of time required for a single block read.

So if a single block read takes 2ms and the cost is expressed as "250", the query could be expected to take 500ms to complete.

The optimiser calculates the cost based on the estimated number of single block and multiblock reads, and the CPU consumption of the plan. the latter can be very useful in minimising the cost by performing certain operations before others to try and avoid high CPU cost operations.

This raises the question of how the optimiser knows how long operations take. recent Oracle versions allow the collections of "system statistics", which are definitely not to be confused with statistics on tables or indexes. The system statistics are measurements of the performance of the hardware, mostly importantly:

  1. How long a single block read takes
  2. How long a multiblock read takes
  3. How large a multiblock read is (often different to the maximum possible due to table extents being smaller than the maximum, and other reasons).
  4. CPU performance

These numbers can vary greatly according to the operating environment of the system, and different sets of statistics can be stored for "daytime OLTP" operations and "nighttime batch reporting" operations, and for "end of month reporting" if you wish.

Given these sets of statistics, a given query execution plan can be evaluated for cost in different operating environments, which might promote use of full table scans at some times or index scans at others.

The cost is not perfect, but the optimiser gets better at self-monitoring with every release, and can feedback the actual cost in comparison to the estimated cost in order to make better decisions for the future. this also makes it rather more difficult to predict.

Note that the cost is not necessarily wall clock time, as parallel query operations consume a total amount of time across multiple threads.

In older versions of Oracle the cost of CPU operations was ignored, and the relative costs of single and multiblock reads were effectively fixed according to init parameters.

Check for false

If you want to check for false and alert if not, then no there isn't.

If you use if(val), then anything that evaluates to 'truthy', like a non-empty string, will also pass. So it depends on how stringent your criterion is. Using === and !== is generally considered good practice, to avoid accidentally matching truthy or falsy conditions via JavaScript's implicit boolean tests.

Circular gradient in android

Here is the complete xml with gradient, stoke & circular shape.

<?xml version="1.0" encoding="utf-8"?>

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

    <!-- You can use gradient with below attributes-->
    <gradient
        android:angle="90"
        android:centerColor="#555994"
        android:endColor="#b5b6d2"
        android:startColor="#555994"
        android:type="linear" />

    <!-- You can omit below tag if you don't need stroke -->
   <stroke android:color="#3b91d7" android:width="5dp"/>

    <!-- Set the same value for both width and height to get a circular shape -->
    <size android:width="200dp" android:height="200dp"/>


    <!--if you need only a single color filled shape-->
    <solid android:color="#e42828"/>


</shape>

How do I get a file name from a full path with PHP?

There are several ways to get the file name and extension. You can use the following one which is easy to use.

$url = 'http://www.nepaltraveldoor.com/images/trekking/nepal/annapurna-region/Annapurna-region-trekking.jpg';
$file = file_get_contents($url); // To get file
$name = basename($url); // To get file name
$ext = pathinfo($url, PATHINFO_EXTENSION); // To get extension
$name2 =pathinfo($url, PATHINFO_FILENAME); // File name without extension

How to set image in circle in swift

If your image is rounded, it would have a height and width of the exact same size (i.e 120). You simply take half of that number and use that in your code (image.layer.cornerRadius = 60).

SQL query to select dates between two dates

I would go for

select Date,TotalAllowance from Calculation where EmployeeId=1
             and Date >= '2011/02/25' and Date < DATEADD(d, 1, '2011/02/27')

The logic being that >= includes the whole start date and < excludes the end date, so we add one unit to the end date. This can adapted for months, for instance:

select Date, ... from ...
             where Date >= $start_month_day_1 and Date < DATEADD(m, 1, $end_month_day_1)

Razor View throwing "The name 'model' does not exist in the current context"

if you take this problem without any change on your project as like as me, you need change your web.config that placed in View Folder. just write new line by Enter or Remove an empty line . then save your web.config and rebuild. my problem solved with this solution

How can I define a composite primary key in SQL?

CREATE TABLE `voting` (
  `QuestionID` int(10) unsigned NOT NULL,
  `MemberId` int(10) unsigned NOT NULL,
  `vote` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`QuestionID`,`MemberId`)
);

IIS7: Setup Integrated Windows Authentication like in IIS6

To enable the Windows Authentication on IIS7 on Windows 7 machine:

  • Go to Control Panel

  • Click Programs >> Programs and Features

  • Select "Turn Windows Features on or off" from left side.

  • Expand Internet Information Services >> World Wide Web Services >> Security

  • Select Windows Authentication and click OK.

  • Reset the IIS and Check in IIS now for windows authentication.

Enjoy

What is the difference between gravity and layout_gravity in Android?

From what I can gather layout_gravity is the gravity of that view inside its parent, and gravity is the gravity of the children inside that view.

I think this is right but the best way to find out is to play around.

invalid types 'int[int]' for array subscript

What to change? Aside from the 3 or 4 dimensional array problem, you should get rid of the magic numbers (10 and 9).

const int DIM_SIZE = 10;
int myArray[DIM_SIZE][DIM_SIZE][DIM_SIZE];

for (int i = 0; i < DIM_SIZE; ++i){
    for (int t = 0; t < DIM_SIZE; ++t){            
        for (int x = 0; x < DIM_SIZE; ++x){

How do I retrieve query parameters in Spring Boot?

To accept both @PathVariable and @RequestParam in the same /user endpoint:

@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
                 @RequestParam(required=false) Map<String,String> qparams) {
    qparams.forEach((a,b) -> {
        System.out.println(String.format("%s -> %s",a,b));
    }
  
    if (data != null) {
        System.out.println(data);
    }
}

Testing with curl:

  • curl 'http://localhost:8080/user/books'
  • curl 'http://localhost:8080/user?book=ofdreams&name=nietzsche'

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

If any other application is installed on your system which is using port:8080, then try other port like 8081 or uninstall and during installation it will prompt on which port it will run the Oracle DBA server.

jQuery access input hidden value

If you want to select an individual hidden field, you can select it through the different selectors of jQuery :

<input type="hidden" id="hiddenField" name="hiddenField" class="hiddenField"/> 


$("#hiddenField").val(); //by id
$("[name='hiddenField']").val(); // by name
$(".hiddenField").val(); // by class

How to input a regex in string.replace?

don't have to use regular expression (for your sample string)

>>> s
'this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. \nand there are many other lines in the txt files\nwith<[3> such tags </[3>\n'

>>> for w in s.split(">"):
...   if "<" in w:
...      print w.split("<")[0]
...
this is a paragraph with
 in between
 and then there are cases ... where the
 number ranges from 1-100
.
and there are many other lines in the txt files
with
 such tags

Get visible items in RecyclerView

For StaggeredGridLayoutManager do this:

RecyclerView rv = findViewById(...);
StaggeredGridLayoutManager lm = new StaggeredGridLayoutManager(...);
rv.setLayoutManager(lm);

And to get visible item views:

int[] viewsIds = lm.findFirstCompletelyVisibleItemPositions(null);
ViewHolder firstViewHolder = rvPlantios.findViewHolderForLayoutPosition(viewsIds[0]);
View itemView = viewHolder.itemView;

Remember to check if it is empty.

No Application Encryption Key Has Been Specified

If you git clone some project then this kind of issue may usually occur.

  1. make sure there is .env file
  2. run php artisan key:generate and then it should generate APP_KEY in .env
  3. finally run php artisan serve and it should be working.

Scraping html tables into R data frames using the XML package

Another option using Xpath.

library(RCurl)
library(XML)

theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
webpage <- getURL(theurl)
webpage <- readLines(tc <- textConnection(webpage)); close(tc)

pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE)

# Extract table header and contents
tablehead <- xpathSApply(pagetree, "//*/table[@class='wikitable sortable']/tr/th", xmlValue)
results <- xpathSApply(pagetree, "//*/table[@class='wikitable sortable']/tr/td", xmlValue)

# Convert character vector to dataframe
content <- as.data.frame(matrix(results, ncol = 8, byrow = TRUE))

# Clean up the results
content[,1] <- gsub(" ", "", content[,1])
tablehead <- gsub(" ", "", tablehead)
names(content) <- tablehead

Produces this result

> head(content)
   Opponent Played Won Drawn Lost Goals for Goals against % Won
1 Argentina     94  36    24   34       148           150 38.3%
2  Paraguay     72  44    17   11       160            61 61.1%
3   Uruguay     72  33    19   20       127            93 45.8%
4     Chile     64  45    12    7       147            53 70.3%
5      Peru     39  27     9    3        83            27 69.2%
6    Mexico     36  21     6    9        69            34 58.3%

How to properly highlight selected item on RecyclerView?

I think, I've found the best tutorial on how to use the RecyclerView with all basic functions we need (single+multiselection, highlight, ripple, click and remove in multiselection, etc...).

Here it is --> http://enoent.fr/blog/2015/01/18/recyclerview-basics/

Based on that, I was able to create a library "FlexibleAdapter", which extends a SelectableAdapter. I think this must be a responsibility of the Adapter, actually you don't need to rewrite the basic functionalities of Adapter every time, let a library to do it, so you can just reuse the same implementation.

This Adapter is very fast, it works out of the box (you don't need to extend it); you customize the items for every view types you need; ViewHolder are predefined: common events are already implemented: single and long click; it maintains the state after rotation and much much more.

Please have a look and feel free to implement it in your projects.

https://github.com/davideas/FlexibleAdapter

A Wiki is also available.

Return anonymous type results?

No you cannot return anonymous types without going through some trickery.

If you were not using C#, what you would be looking for (returning multiple data without a concrete type) is called a Tuple.

There are alot of C# tuple implementations, using the one shown here, your code would work like this.

public IEnumerable<Tuple<Dog,Breed>> GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new Tuple<Dog,Breed>(d, b);

    return result;
}

And on the calling site:

void main() {
    IEnumerable<Tuple<Dog,Breed>> dogs = GetDogsWithBreedNames();
    foreach(Tuple<Dog,Breed> tdog in dogs)
    {
        Console.WriteLine("Dog {0} {1}", tdog.param1.Name, tdog.param2.BreedName);
    }
}

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

Regular expression to find two strings anywhere in input

(.* word1.* word2.* )|(.* word2.* word1.*)

Pointer to 2D arrays in C

int *pointer[280]; //Creates 280 pointers of type int.

In 32 bit os, 4 bytes for each pointer. so 4 * 280 = 1120 bytes.

int (*pointer)[100][280]; // Creates only one pointer which is used to point an array of [100][280] ints.

Here only 4 bytes.

Coming to your question, int (*pointer)[280]; and int (*pointer)[100][280]; are different though it points to same 2D array of [100][280].

Because if int (*pointer)[280]; is incremented, then it will points to next 1D array, but where as int (*pointer)[100][280]; crosses the whole 2D array and points to next byte. Accessing that byte may cause problem if that memory doen't belongs to your process.

Getting "NoSuchMethodError: org.hamcrest.Matcher.describeMismatch" when running test in IntelliJ 10.5

I know that's not the best answer, but if you can't get the classpath working, this is a plan B solution.

In my test classpath, I added the following interface with a default implementation for the describeMismatch method.

package org.hamcrest;

/**
 * PATCH because there's something wrong with the classpath. Hamcrest should be higher than Mockito so that the BaseMatcher
 * implements the describeMismatch method, but it doesn't work for me. 
 */
public interface Matcher<T> extends SelfDescribing {

    boolean matches(Object item);

    default void describeMismatch(Object item, Description mismatchDescription) {
        mismatchDescription.appendDescriptionOf(this).appendValue(item);
    }

    @Deprecated
    void _dont_implement_Matcher___instead_extend_BaseMatcher_();
}

How to understand nil vs. empty vs. blank in Ruby

enter image description here

  • Everything that is nil? is blank?
  • Everything that is empty? is blank?
  • Nothing that is empty? is nil?
  • Nothing that is nil? is empty?

tl;dr -- only use blank? & present? unless you want to distinguish between "" and " "

private final static attribute vs private final attribute

This might help

public class LengthDemo {
public static void main(String[] args) {
    Rectangle box = new Rectangle();
    System.out.println("Sending the value 10.0 "
            + "to the setLength method.");
    box.setLength(10.0);
    System.out.println("Done.");
    }
}

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

How do I horizontally center a span element inside a div

Applying inline-block to the element that is to be centered and applying text-align:center to the parent block did the trick for me.

Works even on <span> tags.

How to do a GitHub pull request

To learn how to make a pull request I just followed two separate help pages on Github (linked below as bullet points). The following command line commands are for Part 1. Part 2, the actual pull request, is done entirely on Github's website.

$ git clone https://github.com/tim-peterson/dwolla-php.git
$ cd dwolla-php
$ git remote add upstream https://github.com/Dwolla/dwolla-php.git
$ git fetch upstream
// make your changes to this newly cloned, local repo 
$ git add .
$ git commit -m '1st commit to dwolla'
$ git push origin master
  • Part 1: fork someone's repo: https://help.github.com/articles/fork-a-repo

    1. click the 'fork' button on the repo you want to contribute to, in this case: Dwolla's PHP repo (Dwolla/dwolla-php)
    2. get the URL for your newly created fork, in this case: https://github.com/tim-peterson/dwolla-php.git (tim-peterson/dwolla-php)
    3. type the git clone->cd dwolla-php->git remote->git fetch sequence above to clone your fork somewhere in your computer (i.e., "copy/paste" it to, in this case: third_party TimPeterson$) and sync it with the master repo (Dwolla/dwolla-php)
    4. make your changes to your local repo
    5. type the git add->git commit->git push sequence above to push your changes to the remote repo, i.e., your fork on Github (tim-peterson/dwolla-php)
  • Part 2: make pull-request: https://help.github.com/articles/using-pull-requests

    1. go to your fork's webpage on Github (https://github.com/tim-peterson/dwolla-php)
    2. click 'pull-request' button
    3. give pull-request a name, fill in details of what changes you made, click submit button.
    4. you're done!!

jQuery get content between <div> tags

Use the text method [text()] to get text in the div element, by identifing the element by class or id.

How do I escape a single quote ( ' ) in JavaScript?

You should always consider what the browser will see by the end. In this case, it will see this:

<img src='something' onmouseover='change(' ex1')' />

In other words, the "onmouseover" attribute is just change(, and there's another "attribute" called ex1')' with no value.

The truth is, HTML does not use \ for an escape character. But it does recognise &quot; and &apos; as escaped quote and apostrophe, respectively.

Armed with this knowledge, use this:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(&quot;ex1&quot;)' />";

... That being said, you could just use JavaScript quotes:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";

Display Image On Text Link Hover CSS Only

add

.hover_img a:hover span {
    display: block;
    width: 350px;
}

to show hover image full size in table change 350 to your size.

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Short answer

datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")

Long answer

The reason that the "Z" is not included is because datetime.now() and even datetime.utcnow() return timezone naive datetimes, that is to say datetimes with no timezone information associated. To get a timezone aware datetime, you need to pass a timezone as an argument to datetime now. For example:

from datetime import datetime, timezone

datetime.utcnow()
#> datetime.datetime(2020, 9, 3, 20, 58, 49, 22253)
# This is timezone naive

datetime.now(timezone.utc)
#> datetime.datetime(2020, 9, 3, 20, 58, 49, 22253, tzinfo=datetime.timezone.utc)
# This is timezone aware

Once you have a timezone aware timestamp, isoformat will include a timezone designation. Thus, you can then get an ISO 8601 timestamp via:

datetime.now(timezone.utc).isoformat()
#> '2020-09-03T20:53:07.337670+00:00'

"+00:00" is a valid ISO 8601 timezone designation for UTC. If you want to have "Z" instead of "+00:00", you have to do the replacement yourself:

datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
#> '2020-09-03T20:53:07.337670Z'

How to set tbody height with overflow scroll

Webkit seems to use internally display: table-row-group for the tbody tag. There is currently a bug with setting height to it: https://github.com/w3c/csswg-drafts/issues/476

Let's hope it will be solved soon.

Best way to incorporate Volley (or other library) into Android Studio project

Nowadays

dependencies {
    compile 'com.android.volley:volley:1.0.0'
}   

A lot of different ways to do it back in the day (original answer)

  • Use the source files from git (a rather manual/general way described here)

    1. Download / install the git client (if you don't have it on your system yet): http://git-scm.com/downloads (or via git clone https://github.com/git/git ... sry bad one, but couldn't resist ^^)
    2. Execute git clone https://android.googlesource.com/platform/frameworks/volley
    3. Copy the com folder from within [path_where_you_typed_git_clone]/volley/src to your projects app/src/main/java folder (Integrate it instead, if you already have a com folder there!! ;-))

    The files show up immediately in Android Studio. For Eclipse you will have to right-click on the src folder and press refresh (or F5) first.

  • Use gradle via the "unofficial" maven mirror

    1. In your project's src/build.gradle file add following volley dependency:

      dependencies {
          compile fileTree(dir: 'libs', include: ['*.jar'])
          // ...
      
          compile 'com.mcxiaoke.volley:library:1.+'
      }
      
    2. Click on Try Again which should right away appear on the top of the file, or just Build it if not

    The main "advantage" here is, that this will keep the version up to date for you, whereas in the other two cases you would have to manually update volley.

    On the "downside" it is not officially from google, but a third party weekly mirror.

    But both of these points, are really relative to what you would need/want. Also if you don't want updates, just put the desired version there instead e.g. compile 'com.mcxiaoke.volley:library:1.0.7'.

css - position div to bottom of containing div

Assign position:relative to .outside, and then position:absolute; bottom:0; to your .inside.

Like so:

.outside {
    position:relative;
}
.inside {
    position: absolute;
    bottom: 0;
}

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

Moment JS - check if a date is today or in the future

If we want difference without the time you can get the date different (only date without time) like below, using moment's format.

As, I was facing issue with the difference while doing ;

moment().diff([YOUR DATE])

So, came up with following;

const dateValidate = moment(moment().format('YYYY-MM-DD')).diff(moment([YOUR SELECTED DATE HERE]).format('YYYY-MM-DD'))

IF dateValidate > 0 
   //it's past day
else
   //it's current or future

Please feel free to comment if there's anything to improve on.

Thanks,

How do you delete an ActiveRecord object?

It's destroy and destroy_all methods, like

user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)

Alternatively you can use delete and delete_all which won't enforce :before_destroy and :after_destroy callbacks or any dependent association options.

User.delete_all(condition: 'value') will allow you to delete records without a primary key

Note: from @hammady's comment, user.destroy won't work if User model has no primary key.

Note 2: From @pavel-chuchuva's comment, destroy_all with conditions and delete_all with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html

How to execute a stored procedure inside a select query

You can create a temp table matching your proc output and insert into it.

CREATE TABLE #Temp (
    Col1 INT
)

INSERT INTO #Temp
    EXEC MyProc

mvn command not found in OSX Mavrerick

I got same problem, I tried all above, noting solved my problem. Luckely, I solved the problem this way:

echo $SHELL

Output

/bin/zsh
OR 
/bin/bash

If it showing "bash" in output. You have to add env properties in .bashrc file (.bash_profile i did not tried, you can try) or else
It is showing 'zsh' in output. You have to add env properties in .zshrc file, if not exist already you create one no issue.

Initializing C# auto-properties

This will be possible in C# 6.0:

public int Y { get; } = 2;

What is the curl error 52 "empty reply from server"?

Try this -> Instead of going through cURL, try pinging the site you’re trying to reach with Telnet. The response that your connection attempt returns will be exactly what cURL sees when it tries to connect (but which it unhelpfully obfuscates from you). Now, depending on what what you see here, you might draw one of several conclusions:

You’re attempting to connect to a website that’s a name-based virtual host, meaning it cannot be reached via IP address. Something’s gone wrong with the hostname—you may have mistyped something. Note that using GET instead of POST for parameters will give you a more concrete answer.

The issue may also be tied to the 100-continue header. Try running curl_getinfo($ch, CURLINFO_HTTP_CODE), and check the result.

Can you force Visual Studio to always run as an Administrator in Windows 8?

After looking on Super User I found this question which explains how to do this with the shortcut on the start screen. Similarly you can do the same when Visual Studio is pinned to the task bar. In either location:

  1. Right click the Visual Studio icon
  2. Go to Properties
  3. Under the Shortcut tab select Advanced
  4. Check Run as administrator

setting default operation in admin mode

Unlike in Windows 7 this only works if you launch the application from the shortcut you changed. After updating both Visual Studio shortcuts it seems to also work when you open a solution file from Explorer.

Update Warning: It looks like one of the major flaws in running Visual Studio with elevated permissions is since Explorer isn't running with them as well you can't drag and drop files into Visual Studio for editing. You need to open them through the file open dialog. Nor can you double click any file associated to Visual Studio and have it open in Visual Studio (aside from solutions it seems) because you'll get an error message saying There was a problem sending the command to the program. Once I uncheck to always start with elevated permissions (using VSCommands) then I'm able to open files directly and drop them into an open instance of Visual Studio.

Update For The Daring: Despite there being no UI to turn off UAC like in the past, that I saw at least, you can still do so through the registry. The key to edit is:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
EnableLUA - DWORD 1-Enabled, 0-Disabled

After changing this Windows will prompt you to restart. Once restarted you'll be back to everything running with admin permissions if you're an admin. The issues I reported above are now gone as well.

Selenium Webdriver submit() vs click()

The submit() function is there to make life easier. You can use it on any element inside of form tags to submit that form.

You can also search for the submit button and use click().

So the only difference is click() has to be done on the submit button and submit() can be done on any form element.

It's up to you.

http://docs.seleniumhq.org/docs/03_webdriver.jsp#user-input-filling-in-forms

How do I print a list of "Build Settings" in Xcode project?

In Xcode 4 and possibly before, in the run script build phase there is an option "Show enviroment variables in build phase". If selected this will show then on a olive green background in the build log.

Get a list of all threads currently running in Java

Get a handle to the root ThreadGroup, like this:

ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();
ThreadGroup parentGroup;
while ((parentGroup = rootGroup.getParent()) != null) {
    rootGroup = parentGroup;
}

Now, call the enumerate() function on the root group repeatedly. The second argument lets you get all threads, recursively:

Thread[] threads = new Thread[rootGroup.activeCount()];
while (rootGroup.enumerate(threads, true ) == threads.length) {
    threads = new Thread[threads.length * 2];
}

Note how we call enumerate() repeatedly until the array is large enough to contain all entries.

How to combine two or more querysets in a Django view?

DATE_FIELD_MAPPING = {
    Model1: 'date',
    Model2: 'pubdate',
}

def my_key_func(obj):
    return getattr(obj, DATE_FIELD_MAPPING[type(obj)])

And then sorted(chain(Model1.objects.all(), Model2.objects.all()), key=my_key_func)

Quoted from https://groups.google.com/forum/#!topic/django-users/6wUNuJa4jVw. See Alex Gaynor

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

wt = tt - cpu tm.
Tt = cpu tm + wt.

Where wt is a waiting time and tt is turnaround time. Cpu time is also called burst time.

SQL select max(date) and corresponding value

You can use a subquery. The subquery will get the Max(CompletedDate). You then take this value and join on your table again to retrieve the note associate with that date:

select ET1.TrainingID,
  ET1.CompletedDate,
  ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
  select Max(CompletedDate) CompletedDate, TrainingID
  from HR_EmployeeTrainings
  --where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
  group by TrainingID
) ET2
  on ET1.TrainingID = ET2.TrainingID
  and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID

Download a file from HTTPS using download.file()

It might be easiest to try the RCurl package. Install the package and try the following:

# install.packages("RCurl")
library(RCurl)
URL <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
x <- getURL(URL)
## Or 
## x <- getURL(URL, ssl.verifypeer = FALSE)
out <- read.csv(textConnection(x))
head(out[1:6])
#   RT SERIALNO DIVISION PUMA REGION ST
# 1  H      186        8  700      4 16
# 2  H      306        8  700      4 16
# 3  H      395        8  100      4 16
# 4  H      506        8  700      4 16
# 5  H      835        8  800      4 16
# 6  H      989        8  700      4 16
dim(out)
# [1] 6496  188

download.file("https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv",destfile="reviews.csv",method="libcurl")

How to change to an older version of Node.js

For some reason Brew installs node 5 into a separate directory called node5.

The steps I took to get back to version 5 were: (You will need to look up standard brew installation/uninstallation, but otherwise this process is more straightforward than it looks.)

  1. Install node5 using Brew standard installation, BUT don't brew link, yet.
  2. Uninstall all other versions of node using brew unlink node and brew uninstall node. You might need to use --force to remove one of the versions.
  3. Find the cellar folder on your computer
  4. Delete the node folder in the cellar.
  5. Rename the node5 folder to node.
  6. Then, brew link node

You should be all set with node 5.

Oracle date format picture ends before converting entire input string

Perhaps you should check NLS_DATE_FORMAT and use the date string conforming the format. Or you can use to_date function within the INSERT statement, like the following:

insert into visit
values(123456, 
       to_date('19-JUN-13', 'dd-mon-yy'),
       to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));

Additionally, Oracle DATE stores date and time information together.

Html.fromHtml deprecated in Android N

fromHtml

This method was deprecated in API level 24.

You should use FROM_HTML_MODE_LEGACY

Separate block-level elements with blank lines (two newline characters) in between. This is the legacy behavior prior to N.

Code

if (Build.VERSION.SDK_INT >= 24)
        {
            etOBJ.setText(Html.fromHtml("Intellij \n Amiyo",Html.FROM_HTML_MODE_LEGACY));

         }
 else
        {
           etOBJ.setText(Html.fromHtml("Intellij \n Amiyo"));
        }

For Kotlin

fun setTextHTML(html: String): Spanned
    {
        val result: Spanned = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
        } else {
            Html.fromHtml(html)
        }
        return result
    }

Call

 txt_OBJ.text  = setTextHTML("IIT Amiyo")

jQuery - select the associated label element of a input field

There are two ways to specify label for element:

  1. Setting label's "for" attribute to element's id
  2. Placing element inside label

So, the proper way to find element's label is

   var $element = $( ... )

   var $label = $("label[for='"+$element.attr('id')+"']")
   if ($label.length == 0) {
     $label = $element.closest('label')
   }

   if ($label.length == 0) {
     // label wasn't found
   } else {
     // label was found
   }

How should I tackle --secure-file-priv in MySQL?

I had this problem on windows 10. "--secure-file-priv in MySQL" To solve this I did the following.

  1. In windows search (bottom left) I typed "powershell".
  2. Right clicked on powershell and ran as admin.
  3. Navigated to the server bin file. (C:\Program Files\MySQL\MySQL Server 5.6\bin);
  4. Typed ./mysqld
  5. Hit "enter"

The server started up as expected.

Split large string in n-size chunks in JavaScript

I created several faster variants which you can see on jsPerf. My favorite one is this:

function chunkSubstr(str, size) {
  const numChunks = Math.ceil(str.length / size)
  const chunks = new Array(numChunks)

  for (let i = 0, o = 0; i < numChunks; ++i, o += size) {
    chunks[i] = str.substr(o, size)
  }

  return chunks
}

Why I've got no crontab entry on OS X when using vim?

The error crontab: temp file must be edited in place is because of the way vim treats backup files.

To use vim with cron, add the following lines in your .bash_profile
export EDITOR=vim
alias crontab="VIM_CRONTAB=true crontab"

Source the file:
source .bash_profile

And then in your .vimrc add:
if $VIM_CRONTAB == "true" set nobackup set nowritebackup endif

This will disable backups when using vim with cron. And you will be able to use crontab -e to add/edit cronjobs.

On successfully saving your cronjob, you will see the message:
crontab: installing new crontab

Source:
http://drawohara.com/post/6344279/crontab-temp-file-must-be-edited-in-placeenter link description here

How do I find out which DOM element has the focus?

If you want to get a object that is instance of Element, you must use document.activeElement, but if you want to get a object that is instance of Text, you must to use document.getSelection().focusNode.

I hope helps.

How to create an integer array in Python?

Use the array module. With it you can store collections of the same type efficiently.

>>> import array
>>> import itertools
>>> a = array_of_signed_ints = array.array("i", itertools.repeat(0, 10))

For more information - e.g. different types, look at the documentation of the array module. For up to 1 million entries this should feel pretty snappy. For 10 million entries my local machine thinks for 1.5 seconds.

The second parameter to array.array is a generator, which constructs the defined sequence as it is read. This way, the array module can consume the zeros one-by-one, but the generator only uses constant memory. This generator does not get bigger (memory-wise) if the sequence gets longer. The array will grow of course, but that should be obvious.

You use it just like a list:

>>> a.append(1)
>>> a.extend([1, 2, 3])
>>> a[-4:]
array('i', [1, 1, 2, 3])
>>> len(a)
14

...or simply convert it to a list:

>>> l = list(a)
>>> len(l)
14

Surprisingly

>>> a = [0] * 10000000

is faster at construction than the array method. Go figure! :)

Load data from txt with pandas

You can do as:

import pandas as pd
df = pd.read_csv('file_location\filename.txt', delimiter = "\t")

(like, df = pd.read_csv('F:\Desktop\ds\text.txt', delimiter = "\t")

Text in a flex container doesn't wrap in IE11

I had a similar issue with overflowing images in a flex wrapper.

Adding either flex-basis: 100%; or flex: 1; to the overflowing child fixed worked for me.

ReferenceError: $ is not defined

You can install it by bower:

Node.js npm install underscore
Meteor.js meteor add underscore
Require.js require(["underscore"], ...
Bower bower install underscore
Component component install jashkenas/underscore

Here's the link to the oficial page http://underscorejs.org/

How to retrieve GET parameters from JavaScript

I do it like this (to retrieve a specific get-parameter, here 'parameterName'):

var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]);

Edit seaborn legend

Took me a while to read through the above. This was the answer for me:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

g = sns.lmplot(
    x="total_bill", 
    y="tip", 
    hue="smoker", 
    data=tips,  
    legend=False
)

plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh'])
plt.show(g)

Reference this for more arguments: matplotlib.pyplot.legend

enter image description here

Bootstrap carousel width and height

If you use bootstrap 4 Alpha and you have an error with the height of the images in chrome, I have a solution: The documentation of bootstrap 4 says this:

<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner" role="listbox">
    <div class="carousel-item active">
      <img class="d-block img-fluid" src="..." alt="First slide">
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="..." alt="Second slide">
    </div>
    <div class="carousel-item">
      <img class="d-block img-fluid" src="..." alt="Third slide">
    </div>
  </div>
</div>

Solution:

The solution is to put "div" around the image, with the class ".container", like this:

<div class="carousel-item active">
  <div class="container">
    <img src="images/proyecto_0.png" alt="First slide" class="d-block img-fluid">
  </div>
</div>

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

2.1.3.5 X-UA-Compatibility Meta Tag and HTTP Response Header

This functionality will not be implemented in any version of Microsoft Edge.

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

See https://msdn.microsoft.com/en-us/library/ff955275(v=vs.85).aspx

Yes, I know that I'm late to the party, but I just had some issues and discussions, and in the end my boss had me remove the X-UA-Compatible tag remove from all documents I've been working on.

If this information is out-of-date or no longer relevant, please correct me.

Create XML file using java

I am providing an answer from my own blog. Hope this will help.

What will be output?

Following XML file named users.xml will be created.

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<users>
    <user uid="1">
        <firstname>Interview</firstname>
        <lastname>Bubble</lastname>
        <email>[email protected]</email>
    </user>
</users>

PROCEDURE

Basic steps, in order to create an XML File with a DOM Parser, are:

  1. Create a DocumentBuilder instance.

  2. Create a Document from the above DocumentBuilder.

  3. Create the elements you want using the Element class and its appendChild method.

  4. Create a new Transformer instance and a new DOMSource instance.

  5. Create a new StreamResult to the output stream you want to use.

  6. Use transform method to write the DOM object to the output stream.

SOURCE CODE:

package com.example.TestApp;

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CreateXMLFileJava {

 public static void main(String[] args) throws ParserConfigurationException, 
                                               IOException, 
                                               TransformerException
    {
     // 1.Create a DocumentBuilder instance
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dbuilder = dbFactory.newDocumentBuilder();

    // 2. Create a Document from the above DocumentBuilder.
    Document document = dbuilder.newDocument();

    // 3. Create the elements you want using the Element class and its appendChild method.   

   // root element
    Element users = document.createElement("users");
    document.appendChild(users);   

    // child element
    Element user = document.createElement("user");
    users.appendChild(user);  

    // Attribute of child element
    user.setAttribute("uid", "1");   

    // firstname Element
    Element firstName = document.createElement("firstName");
    firstName.appendChild(document.createTextNode("Interview"));
    user.appendChild(firstName);   

    // lastName element
    Element lastName = document.createElement("lastName");
    lastName.appendChild(document.createTextNode("Bubble"));
    user.appendChild(lastName);   

    // email element
    Element email = document.createElement("email");
    email.appendChild(document.createTextNode("[email protected]"));
    user.appendChild(email);   

    // write content into xml file   

    // 4. Create a new Transformer instance and a new DOMSource instance.
   TransformerFactory transformerFactory = TransformerFactory.newInstance();
   Transformer transformer = transformerFactory.newTransformer();
   DOMSource source = new DOMSource(document);

   // 5. Create a new StreamResult to the output stream you want to use.
   StreamResult result = new StreamResult(new File("/Users/admin/Desktop/users.xml"));
   // StreamResult result = new StreamResult(System.out); // to print on console

   // 6. Use transform method to write the DOM object to the output stream.
   transformer.transform(source, result);  

   System.out.println("File created successfully");
 }
}

OUTPUT:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<users>
  <user uid="1">
     <firstName>Interview</firstName>
     <lastName>Bubble</lastName>
     <email>[email protected]</email>
  </user>
</users>

How to export the Html Tables data into PDF using Jspdf

A good option is AutoTable(a Table plugin for jsPDF), it includes themes, rowspan, colspan, extract data from html, works with json, you can also personalize your headers and make them horizontals. Here is a demo.

enter image description here

How to send a JSON object using html form data

HTML provides no way to generate JSON from form data.

If you really want to handle it from the client, then you would have to resort to using JavaScript to:

  1. gather your data from the form via DOM
  2. organise it in an object or array
  3. generate JSON with JSON.stringify
  4. POST it with XMLHttpRequest

You'd probably be better off sticking to application/x-www-form-urlencoded data and processing that on the server instead of JSON. Your form doesn't have any complicated hierarchy that would benefit from a JSON data structure.


Update in response to major rewrite of the question…

  • Your JS has no readystatechange handler, so you do nothing with the response
  • You trigger the JS when the submit button is clicked without cancelling the default behaviour. The browser will submit the form (in the regular way) as soon as the JS function is complete.

Image convert to Base64

It's useful to work with Deferred Object in this case, and return promise:

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;
    if (files && files[0]) {
        var fr= new FileReader();
        fr.onload = function(e) {
            deferred.resolve(e.target.result);
        };
        fr.readAsDataURL( files[0] );
    } else {
        deferred.resolve(undefined);
    }

    return deferred.promise();
}

And above function could be used in this way:

var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
    alert(base64Data);
});

Or in your case:

$(input).on('change',function(){
  readImage($(this)).done(function(base64Data){ alert(base64Data); });
});

Case objects vs Enumerations in Scala

The advantages of using case classes over Enumerations are:

  • When using sealed case classes, the Scala compiler can tell if the match is fully specified e.g. when all possible matches are espoused in the matching declaration. With enumerations, the Scala compiler cannot tell.
  • Case classes naturally supports more fields than a Value based Enumeration which supports a name and ID.

The advantages of using Enumerations instead of case classes are:

  • Enumerations will generally be a bit less code to write.
  • Enumerations are a bit easier to understand for someone new to Scala since they are prevalent in other languages

So in general, if you just need a list of simple constants by name, use enumerations. Otherwise, if you need something a bit more complex or want the extra safety of the compiler telling you if you have all matches specified, use case classes.

How do I check for equality using Spark Dataframe without SQL Query?

In Spark 2.4

To compare with one value:

df.filter(lower(trim($"col_name")) === "<value>").show()

To compare with collection of value:

df.filter($"col_name".isInCollection(new HashSet<>(Arrays.asList("value1", "value2")))).show()

Hibernate: "Field 'id' doesn't have a default value"

Another suggestion is to check that you use a valid type for the auto-generated field. Remember that it doesn't work with String, but it works with Long:

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long id;

@Constraints.Required
public String contents;

The above syntax worked for generating tables in MySQL using Hibernate as a JPA 2.0 provider.

Hide password with "•••••••" in a textField

Programmatically (Swift 4 & 5)

self.passwordTextField.isSecureTextEntry = true

refresh both the External data source and pivot tables together within a time schedule

I used the above answer but made use of the RefreshAll method. I also changed it to allow for multiple connections without having to specify the names. I then linked this to a button on my spreadsheet.

Sub Refresh()

    Dim conn As Variant

    For Each conn In ActiveWorkbook.Connections
        conn.ODBCConnection.BackgroundQuery = False
    Next conn

    ActiveWorkbook.RefreshAll
End Sub

angular 2 ngIf and CSS transition/animation

According to the latest angular 2 documentation you can animate "Entering and Leaving" elements (like in angular 1).

Example of simple fade animation:

In relevant @Component add:

animations: [
  trigger('fadeInOut', [
    transition(':enter', [   // :enter is alias to 'void => *'
      style({opacity:0}),
      animate(500, style({opacity:1})) 
    ]),
    transition(':leave', [   // :leave is alias to '* => void'
      animate(500, style({opacity:0})) 
    ])
  ])
]

Do not forget to add imports

import {style, state, animate, transition, trigger} from '@angular/animations';

The relevant component's html's element should look like:

<div *ngIf="toggle" [@fadeInOut]>element</div>

I built example of slide and fade animation here.

Explanation on 'void' and '*':

  • void is the state when ngIf is set to false (it applies when the element is not attached to a view).
  • * - There can be many animation states (read more in docs). The * state takes precedence over all of them as a "wildcard" (in my example this is the state when ngIf is set to true).

Notice (taken from angular docs):

Extra declare inside the app module, import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

Angular animations are built on top of the standard Web Animations API and run natively on browsers that support it. For other browsers, a polyfill is required. Grab web-animations.min.js from GitHub and add it to your page.

Re-sign IPA (iPhone)

In 2020, I did it with Fastlane -

Here is the command I used

$ fastlane run resign ipa:"/Users/my_user/path/to/app.ipa" signing_identity:"iPhone Distribution: MY Company (XXXXXXXX)" provisioning_profile:"/Users/my_user/path/to/profile.mobileprovision" bundle_id:com.company.new.bundle.name

Full docs here - https://docs.fastlane.tools/actions/resign/

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

SQL SELECT everything after a certain character

select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;

Please use http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php for further reference.

Python Script execute commands in Terminal

Jupyter

In a jupyter notebook you can use the magic function !

!echo "execute a command"
files = !ls -a /data/dir/ #get the output into a variable

ipython

To execute this as a .py script you would need to use ipython

files = get_ipython().getoutput('ls -a /data/dir/')

execute script

$ ipython my_script.py

Emulate/Simulate iOS in Linux

You might want to try screenfly. It worked great for me.

Hide Command Window of .BAT file that Executes Another .EXE File

To make the command window of a .bat file that executes a .exe file exit out as fast as possible, use the line @start before the file you're trying to execute. Here is an example:

(insert other code here)
@start executable.exe
(insert other code here)

You don't have to use other code with @start executable.exe.

MVC ajax post to controller action method

$('#loginBtn').click(function(e) {
    e.preventDefault(); /// it should not have this code or else it wont continue
    //....
});

Android - how to make a scrollable constraintlayout?

TO make a scrollable layout, the layout is correct. It will not be scrollable until there is reason to scroll(just like in any other layout). So add enough content and it will be scrollable, just like with any layout(Linear, Relative, etc). However, you cannot scroll properly in Blueprint or design-mode when designing with ConstraintLayout and ScrollView.

Meaning:

You can make a scrollable ConstraintLayout, but it will not scroll properly in the editor due to a bug/scenario that wasn't considered. But even though scrolling doesn't work in the editor, it works on devices. (I have made several scrolling COnstraintLayouts, so I have tested it)

Note

Regarding your code. The ScrollView is missing a closing tag, I don't know if it is the case in the file or if it is a copy-paste miss, but you may want to look at it.

Parsing JSON from URL

public static TargetClassJson downloadPaletteJson(String url) throws IOException {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        String genreJson = IOUtils.toString(new URL(url).openStream());
        return new Gson().fromJson(genreJson, TargetClassJson.class);
    }

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

You can use Rout redirecting.

protected void btnNewEntry_Click(object sender, EventArgs e)
{
    Response.RedirectToRoute("CMS_1"); 
}

which requires to define your routing logic in Global.asax file that could be like that:

routes.MapPageRoute("CMS_1", "CMS_1", "~/CMS_1.aspx");

where any request by CMS_1 pattern in application scope will be redirecting to CMS_1.aspx, but in URL shows like www.yoursite.com/CMS_1

The type or namespace name 'DbContext' could not be found

I had the same problem using VS2010. I know this isn't really an answer. I just thought it might help someone. I resolved it by using the fully qualified name for DBContext.

Instead of

public class MachineDbContext : DbContext

I used

public class MachineDbContext : System.Data.Entity.DbContext

and rebuilt the project. Suddenly VS was happy, and I was even able to remove the fully qualified name, and just use DBContext.

Difference between private, public, and protected inheritance

Accessors    | Base Class | Derived Class | World
—————————————+————————————+———————————————+———————
public       |      y     |       y       |   y
—————————————+————————————+———————————————+———————
protected    |      y     |       y       |   n
—————————————+————————————+———————————————+———————
private      |            |               |    
  or         |      y     |       n       |   n
no accessor  |            |               |

y: accessible
n: not accessible

Based on this example for java... I think a little table worth a thousand words :)

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

Java Revisited

  1. Resource included by include directive is loaded during jsp translation time, while resource included by include action is loaded during request time.
  2. Any change on included resource will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in next request.
  3. Include directive is static import, while include action is dynamic import
  4. Include directive uses file attribute to specify resource to be included while include action use page attribute for same purpose.

Height of an HTML select box (dropdown)

You can change the height of one. Don't use height="500"(Just an example number). Use the style. You can use <style>tag or just use this:

<!DOCTYPE html>
<html>
<body>
  <select id="option" style="height: 100px;">
    <option value="1">Option 1
    <option value="2">Option 2
  </select>
</body>
</html>

I spotlight the change:

  <select id="option" style="height: 100px;">

And even better...

style="height: 100px;">

You see that?

Please up vote if it's helpful!

Error: The type exists in both directories

This has been answered in a separate question and resolved the problem for me. Be sure to vote up the original person's answer.

ASP.Net error: "The type 'foo' exists in both "temp1.dll" and "temp2.dll"

Add the batch="false" attribute to the "compilation" element of the web.config file.

This problem occurs because of the way in which ASP.NET 2.0 uses the application references and the folder structure of the application to compile the application. If the batch property of the element in the web.config file for the application is set to true, ASP.NET 2.0 compiles each folder in the application into a separate assembly.

http://www.sellsbrothers.com/news/showTopic.aspx?ixTopic=1995

http://support.microsoft.com/kb/919284

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

For those that use .NET Standard project in combination with .NET Framework projects:

In the .NET Standard way, packages that are included in a .NET Standard project will correctly be used across other .NET Core and .NET Standard projects.

Im the .NET Framework way, if you are referring to a .NET Standard project from an .NET Framework (MVC) project, you need to manually download and install the same nuget packages.

So the answer to my question was that I had to download and install Microsoft.AspNet.WebApi.Client in the web project (.NET Framework) that is using a .NET Standard project where Microsoft.AspNet.WebApi.Client is needed. In fact, I already had this installed but there was a version difference.

I just add this answer for others to see, it might not directly answer OP's question but it did save me time by first checking this instead of doing the top-voted answers.

RuntimeError on windows trying python multiprocessing

Though the earlier answers are correct, there's a small complication it would help to remark on.

In case your main module imports another module in which global variables or class member variables are defined and initialized to (or using) some new objects, you may have to condition that import in the same way:

if __name__ ==  '__main__':
  import my_module

disable past dates on datepicker

Try this'
 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <!-- table -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
    <!-- end table -->

    <script>
       $(function() {
        $('#example').DataTable();
        $("#from_date").datepicker({
            dateFormat: "mm/d/yy",
            maxDate: 0,

            onSelect: function () {



                var minDate = $(this).datepicker('getDate');

                $('#to_date').datepicker('setDate', minDate);
                $('#to_date').datepicker('option', 'maxDate', 0);
                $('#to_date').datepicker('option', 'minDate', minDate);
            }
        });
        $('#to_date').datepicker({
            dateFormat: "mm/d/yy"
        });

       });
       </script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <!-- table -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
    <!-- end table -->

    <script>
       $(function() {
        $('#example').DataTable();
        $("#from_date").datepicker({
            dateFormat: "mm/d/yy",
            maxDate: 0,

            onSelect: function () {



                var minDate = $(this).datepicker('getDate');

                $('#to_date').datepicker('setDate', minDate);
                $('#to_date').datepicker('option', 'maxDate', 0);
                $('#to_date').datepicker('option', 'minDate', minDate);
            }
        });
        $('#to_date').datepicker({
            dateFormat: "mm/d/yy"
        });

       });
       </script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <!-- table -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
    <!-- end table -->

    <script>
       $(function() {
        $('#example').DataTable();
        $("#from_date").datepicker({
            dateFormat: "mm/d/yy",
            maxDate: 0,

            onSelect: function () {



                var minDate = $(this).datepicker('getDate');

                $('#to_date').datepicker('setDate', minDate);
                $('#to_date').datepicker('option', 'maxDate', 0);
                $('#to_date').datepicker('option', 'minDate', minDate);
            }
        });
        $('#to_date').datepicker({
            dateFormat: "mm/d/yy"
        });

       });
       </script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <!-- table -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
    <!-- end table -->

    <script>
       $(function() {
        $('#example').DataTable();
        $("#from_date").datepicker({
            dateFormat: "mm/d/yy",
            maxDate: 0,

            onSelect: function () {



                var minDate = $(this).datepicker('getDate');

                $('#to_date').datepicker('setDate', minDate);
                $('#to_date').datepicker('option', 'maxDate', 0);
                $('#to_date').datepicker('option', 'minDate', minDate);
            }
        });
        $('#to_date').datepicker({
            dateFormat: "mm/d/yy"
        });

       });
       </script><link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>

    <!-- table -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
    <!-- end table -->

    <script>
       $(function() {
        $('#example').DataTable();
        $("#from_date").datepicker({
            dateFormat: "mm/d/yy",
            maxDate: 0,

            onSelect: function () {



                var minDate = $(this).datepicker('getDate');

                $('#to_date').datepicker('setDate', minDate);
                $('#to_date').datepicker('option', 'maxDate', 0);
                $('#to_date').datepicker('option', 'minDate', minDate);
            }
        });
        $('#to_date').datepicker({
            dateFormat: "mm/d/yy"
        });

       });
       </script>

Using Java with Nvidia GPUs (CUDA)

There is not much information on the nature of the problem and the data, so difficult to advise. However, would recommend to assess the feasibility of other solutions, that can be easier to integrate with java and enables horizontal as well as vertical scaling. The first I would suggest to look at is an open source analytical engine called Apache Spark https://spark.apache.org/ that is available on Microsoft Azure but probably on other cloud IaaS providers too. If you stick to involving your GPU then the suggestion is to look at other GPU supported analytical databases on the market that fits in the budget of your organisation.

Trying to get property of non-object in

Your error

Notice: Trying to get property of non-object in C:\wamp\www\phone\pages\init.php on line 22

Your comment

@22 is <?php echo $sidemenu->mname."<br />";?>

$sidemenu is not an object, and you are trying to access one of its properties.

That is the reason for your error.

jquery get all form elements: input, textarea & select

Just to add another way:

$('form[name=' + formName + ']').find(':input')

Undo working copy modifications of one file in Git?

I always get confused with this, so here is a reminder test case; let's say we have this bash script to test git:

set -x
rm -rf test
mkdir test
cd test
git init
git config user.name test
git config user.email [email protected]
echo 1 > a.txt
echo 1 > b.txt
git add *
git commit -m "initial commit"
echo 2 >> b.txt
git add b.txt
git commit -m "second commit"
echo 3 >> b.txt

At this point, the change is not staged in the cache, so git status is:

$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   b.txt

no changes added to commit (use "git add" and/or "git commit -a")

If from this point, we do git checkout, the result is this:

$ git checkout HEAD -- b.txt
$ git status
On branch master
nothing to commit, working directory clean

If instead we do git reset, the result is:

$ git reset HEAD -- b.txt
Unstaged changes after reset:
M   b.txt
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   b.txt

no changes added to commit (use "git add" and/or "git commit -a")

So, in this case - if the changes are not staged, git reset makes no difference, while git checkout overwrites the changes.


Now, let's say that the last change from the script above is staged/cached, that is to say we also did git add b.txt at the end.

In this case, git status at this point is:

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   b.txt

If from this point, we do git checkout, the result is this:

$ git checkout HEAD -- b.txt
$ git status
On branch master
nothing to commit, working directory clean

If instead we do git reset, the result is:

$ git reset HEAD -- b.txt
Unstaged changes after reset:
M   b.txt
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   b.txt

no changes added to commit (use "git add" and/or "git commit -a")

So, in this case - if the changes are staged, git reset will basically make staged changes into unstaged changes - while git checkout will overwrite the changes completely.

How do I remove a submodule?

  • A submodule can be deleted by running git rm <submodule path> && git commit. This can be undone using git revert.
    • The deletion removes the superproject's tracking data, which are both the gitlink entry and the section in the .gitmodules file.
    • The submodule's working directory is removed from the file system, but the Git directory is kept around as it to make it possible to checkout past commits without requiring fetching from another repository.
  • To completely remove a submodule, additionally manually delete $GIT_DIR/modules/<name>/.

Source: git help submodules

Random / noise functions for GLSL

There is also a nice implementation described here by McEwan and @StefanGustavson that looks like Perlin noise, but "does not require any setup, i.e. not textures nor uniform arrays. Just add it to your shader source code and call it wherever you want".

That's very handy, especially given that Gustavson's earlier implementation, which @dep linked to, uses a 1D texture, which is not supported in GLSL ES (the shader language of WebGL).

Does Java read integers in little endian or big endian?

There's no way this could influence anything in Java, since there's no (direct non-API) way to map some bytes directly into an int in Java.

Every API that does this or something similar defines the behaviour pretty precisely, so you should look up the documentation of that API.

Log4Net configuring log level

Use threshold.

For example:

   <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <threshold value="WARN"/>
        <param name="File" value="File.log" />
        <param name="AppendToFile" value="true" />
        <param name="RollingStyle" value="Size" />
        <param name="MaxSizeRollBackups" value="10" />
        <param name="MaximumFileSize" value="1024KB" />
        <param name="StaticLogFileName" value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <param name="Header" value="[Server startup]&#13;&#10;" />
            <param name="Footer" value="[Server shutdown]&#13;&#10;" />
            <param name="ConversionPattern" value="%d %m%n" />
        </layout>
    </appender>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
        <threshold value="ERROR"/>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread]- %message%newline" />
        </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <threshold value="INFO"/>
        <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%thread] %m%n" />
        </layout>
    </appender>

In this example all INFO and above are sent to Console, all WARN are sent to file and ERRORs are sent to the Event-Log.

Tomcat in Intellij Idea Community Edition

VM :-Djava.endorsed.dirs="C:/Program Files/Apache Software Foundation/Tomcat 8.0/common/endorsed" 
    -Dcatalina.base="C:/Program Files/Apache Software Foundation/Tomcat 8.0"  
    -Dcatalina.home="C:/Program Files/Apache Software Foundation/Tomcat 8.0" 
    -Djava.io.tmpdir="C:/Program Files/Apache Software Foundation/Tomcat 8.0/temp" 
    -Xmx1024M

How to do a scatter plot with empty circles in Python?

From the documentation for scatter:

Optional kwargs control the Collection properties; in particular:

    edgecolors:
        The string ‘none’ to plot faces with no outlines
    facecolors:
        The string ‘none’ to plot unfilled outlines

Try the following:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.random.randn(60) 
y = np.random.randn(60)

plt.scatter(x, y, s=80, facecolors='none', edgecolors='r')
plt.show()

example image

Note: For other types of plots see this post on the use of markeredgecolor and markerfacecolor.

Why is 1/1/1970 the "epoch time"?

Early versions of unix measured system time in 1/60 s intervals. This meant that a 32-bit unsigned integer could only represent a span of time less than 829 days. For this reason, the time represented by the number 0 (called the epoch) had to be set in the very recent past. As this was in the early 1970s, the epoch was set to 1971-1-1.

Later, the system time was changed to increment every second, which increased the span of time that could be represented by a 32-bit unsigned integer to around 136 years. As it was no longer so important to squeeze every second out of the counter, the epoch was rounded down to the nearest decade, thus becoming 1970-1-1. One must assume that this was considered a bit neater than 1971-1-1.

Note that a 32-bit signed integer using 1970-1-1 as its epoch can represent dates up to 2038-1-19, on which date it will wrap around to 1901-12-13.

Render HTML in React Native

I found this component. https://github.com/jsdf/react-native-htmlview

This component takes HTML content and renders it as native views, with customisable style and handling of links, etc.

Getting the current Fragment instance in the viewpager

This is more future-proof than the accepted answer:

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

    /* ------------------------------------------------------------------------------------------ */
    // region Private attributes :

    private Context _context;
    private FragmentManager _fragmentManager;
    private Map<Integer, String> _fragmentsTags = new HashMap<>();

    // endregion
    /* ------------------------------------------------------------------------------------------ */



    /* ------------------------------------------------------------------------------------------ */
    // region Constructor :

    public MyFragmentPagerAdapter(Context context, FragmentManager fragmentManager) {

        super(fragmentManager);

        _context = context;
        _fragmentManager = fragmentManager;
    }

    // endregion
    /* ------------------------------------------------------------------------------------------ */



    /* ------------------------------------------------------------------------------------------ */
    // region FragmentPagerAdapter methods :

    @Override
    public int getCount() { return 2; }

    @Override
    public Fragment getItem(int position) {

        if(_fragmentsTags.containsKey(position)) {

            return _fragmentManager.findFragmentByTag(_fragmentsTags.get(position));
        }
        else {

            switch (position) {

                case 0 : { return Fragment.instantiate(_context, Tab1Fragment.class.getName()); }
                case 1 : { return Fragment.instantiate(_context, Tab2Fragment.class.getName()); }
            }
        }

        return null;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        // Instantiate the fragment and get its tag :
        Fragment result = (Fragment) super.instantiateItem(container, position);
        _fragmentsTags.put(position, result.getTag());

        return result;
    }

    // endregion
    /* ------------------------------------------------------------------------------------------ */
}

How to calculate Date difference in Hive

If you need the difference in seconds (i.e.: you're comparing dates with timestamps, and not whole days), you can simply convert two date or timestamp strings in the format 'YYYY-MM-DD HH:MM:SS' (or specify your string date format explicitly) using unix_timestamp(), and then subtract them from each other to get the difference in seconds. (And can then divide by 60.0 to get minutes, or by 3600.0 to get hours, etc.)

Example:

UNIX_TIMESTAMP('2017-12-05 10:01:30') - UNIX_TIMESTAMP('2017-12-05 10:00:00') AS time_diff -- This will return 90 (seconds). Unix_timestamp converts string dates into BIGINTs. 

More on what you can do with unix_timestamp() here, including how to convert strings with different date formatting: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

How do I find the parent directory in C#?

If you append ..\.. to your existing path, the operating system will correctly browse the grand-parent folder.

That should do the job:

System.IO.Path.Combine("C:\\Users\\Masoud\\Documents\\Visual Studio 2008\\Projects\\MyProj\\MyProj\\bin\\Debug", @"..\..");

If you browse that path, you will browse the grand-parent directory.

ALTER table - adding AUTOINCREMENT in MySQL

ALTER TABLE tblcatalog
    CHANGE COLUMN id id INT(11) NOT NULL AUTO_INCREMENT FIRST;

Custom designing EditText

Use the below code in your rounded_edittext.xml :

<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:thickness="0dp"
       android:shape="rectangle">

    <stroke android:width="2dp"
            android:color="#2F6699"/>

    <corners android:radius="3dp" />

    <gradient   android:startColor="#C8C8C8"
                android:endColor="#FFFFFF"
                android:type="linear"
                android:angle="270"/>
</shape>

Result

How do you check if a selector matches something in jQuery?

Yet another way:

$('#elem').each(function(){
  // do stuff
});

how to make password textbox value visible when hover an icon

In one line of code as below :

_x000D_
_x000D_
<p> cursor on text field shows text .if not password will be shown</p>_x000D_
<input type="password" name="txt_password" onmouseover="this.type='text'"_x000D_
       onmouseout="this.type='password'" placeholder="password" />
_x000D_
_x000D_
_x000D_

get user timezone

This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!

On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:

<?php    
    session_start();
    $timezone = $_SESSION['time'];
?>

This will read the session variable "time", which we are now about to create.

On the same page, in the <head> section, first of all you need to include jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

Also in the <head> section, paste this jQuery:

<script type="text/javascript">
    $(document).ready(function() {
        if("<?php echo $timezone; ?>".length==0){
            var visitortime = new Date();
            var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
            $.ajax({
                type: "GET",
                url: "http://example.com/timezone.php",
                data: 'time='+ visitortimezone,
                success: function(){
                    location.reload();
                }
            });
        }
    });
</script>

You may or may not have noticed, but you need to change the url to your actual domain.

One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)

<?php
    session_start();
    $_SESSION['time'] = $_GET['time'];
?>

If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.

You can read more about this on my blog

Android. Fragment getActivity() sometimes returns null

In Kotlin you can try this way to handle getActivity() null condition.

   activity.let { // activity == getActivity() in java

        //your code here

   }

It will check activity is null or not and if not null then execute inner code.

How can I listen to the form submit event in javascript?

With jQuery:

$('form').submit(function () {
    // Validate here

    if (pass)
        return true;
    else
        return false;
});

Writing image to local server

Cleanest way of saving image locally using request:

const request = require('request');
request('http://link/to/your/image/file.png').pipe(fs.createWriteStream('fileName.png'))

If you need to add authentication token in headers do this:

const request = require('request');
request({
        url: 'http://link/to/your/image/file.png',
        headers: {
            "X-Token-Auth": TOKEN,
        }
    }).pipe(fs.createWriteStream('filename.png'))                    

Input type=password, don't let browser remember the password

I've found the following works on Firefox and Chrome.

<form ... > <!-- more stuff -->
<input name="person" type="text" size=30 value="">
<input name="mypswd" type="password" size=6 value="" autocomplete="off">
<input name="userid" type="text" value="security" style="display:none">
<input name="passwd" type="password" value="faker" style="display:none">
<!-- more stuff --> </form>

All of these are within the forms section. "person" and "mypswd" are what you want, but the browser will save "userid" and "passwd" once, and never again since they don't change. You could eliminate the "person" field if you don't really need it. In that case, all you want is the "mypswd" field, which could change in some way known to the user of your web-page.

How can I get useful error messages in PHP?

If the error is in PHP code, you can use error_reporting() function within your code to set to the report all.

However, this does not handle the situation when PHP crashes. Information about that is only available in server logs. Maybe you don't have access to those, but many hosting providers I've worked with have some way to let you access it. For example, the approach I like best is that it creates the error_log file in the current directory where .php resides. Try searching there or contact your hosting provider about this.

Passing std::string by Value or Reference

Check this answer for C++11. Basically, if you pass an lvalue the rvalue reference

From this article:

void f1(String s) {
    vector<String> v;
    v.push_back(std::move(s));
}
void f2(const String &s) {
    vector<String> v;
    v.push_back(s);
}

"For lvalue argument, ‘f1’ has one extra copy to pass the argument because it is by-value, while ‘f2’ has one extra copy to call push_back. So no difference; for rvalue argument, the compiler has to create a temporary ‘String(L“”)’ and pass the temporary to ‘f1’ or ‘f2’ anyway. Because ‘f2’ can take advantage of move ctor when the argument is a temporary (which is an rvalue), the costs to pass the argument are the same now for ‘f1’ and ‘f2’."

Continuing: " This means in C++11 we can get better performance by using pass-by-value approach when:

  1. The parameter type supports move semantics - All standard library components do in C++11
  2. The cost of move constructor is much cheaper than the copy constructor (both the time and stack usage).
  3. Inside the function, the parameter type will be passed to another function or operation which supports both copy and move.
  4. It is common to pass a temporary as the argument - You can organize you code to do this more.

"

OTOH, for C++98 it is best to pass by reference - less data gets copied around. Passing const or non const depend of whether you need to change the argument or not.

How To Change DataType of a DataColumn in a DataTable?

I combined the efficiency of Mark's solution - so I do not have to .Clone the entire DataTable - with generics and extensibility, so I can define my own conversion function. This is what I ended up with:

/// <summary>
///     Converts a column in a DataTable to another type using a user-defined converter function.
/// </summary>
/// <param name="dt">The source table.</param>
/// <param name="columnName">The name of the column to convert.</param>
/// <param name="valueConverter">Converter function that converts existing values to the new type.</param>
/// <typeparam name="TTargetType">The target column type.</typeparam>
public static void ConvertColumnTypeTo<TTargetType>(this DataTable dt, string columnName, Func<object, TTargetType> valueConverter)
{
    var newType = typeof(TTargetType);

    DataColumn dc = new DataColumn(columnName + "_new", newType);

    // Add the new column which has the new type, and move it to the ordinal of the old column
    int ordinal = dt.Columns[columnName].Ordinal;
    dt.Columns.Add(dc);
    dc.SetOrdinal(ordinal);

    // Get and convert the values of the old column, and insert them into the new
    foreach (DataRow dr in dt.Rows)
    {
        dr[dc.ColumnName] = valueConverter(dr[columnName]);
    }

    // Remove the old column
    dt.Columns.Remove(columnName);

    // Give the new column the old column's name
    dc.ColumnName = columnName;
}

This way, usage is a lot more straightforward, while also customizable:

DataTable someDt = CreateSomeDataTable();
// Assume ColumnName is an int column which we want to convert to a string one.
someDt.ConvertColumnTypeTo<string>('ColumnName', raw => raw.ToString());

Debugging Stored Procedure in SQL Server 2008

Yes you can (provided you have at least the professional version of visual studio), although it requires a little setting up once you've done this it's not much different from debugging code. MSDN has a basic walkthrough.

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

You can use:

Bulk collect along with FOR ALL that is called Bulk binding.

Because PL/SQL forall operator speeds 30x faster for simple table inserts.

BULK_COLLECT and Oracle FORALL together these two features are known as Bulk Binding. Bulk Binds are a PL/SQL technique where, instead of multiple individual SELECT, INSERT, UPDATE or DELETE statements are executed to retrieve from, or store data in, at table, all of the operations are carried out at once, in bulk. This avoids the context-switching you get when the PL/SQL engine has to pass over to the SQL engine, then back to the PL/SQL engine, and so on, when you individually access rows one at a time. To do bulk binds with INSERT, UPDATE, and DELETE statements, you enclose the SQL statement within a PL/SQL FORALL statement. To do bulk binds with SELECT statements, you include the BULK COLLECT clause in the SELECT statement instead of using INTO.

It improves performance.

Remove white space above and below large text in an inline-block element

I've been annoyed by this problem often. Vertical-align would only work on bottom and center, but never top! :-(

It seems I may have stumbled on a solution that works for both table elements and free paragraph elements. I hope we are at least talking similar problem here.

CSS:

p {
    font-family: "Times New Roman", Times, serif;
    font-size: 15px;
    background: #FFFFFF;
    margin: 0
    margin-top: 3px;
    margin-bottom: 10px;
}

For me, the margin settings sorted it out no matter where I put my "p>.../p>" code.

Hope this helps...

Dynamic classname inside ngClass in angular 2

Here's an example of something I'm doing for multiple classes with multiple conditions:

[ngClass]="[variableInComponent || !anotherVariableInComponent ? classes.icon.large : classes.icon.small, editing ? classes.icon.editing : '']"

where:
classes is an object containing strings of various classnames. e.g. class.icon.large = "app__icon--large"

It's dynamic! Updates as the conditions update.

How to extract a single value from JSON response?

Only suggestion is to access your resp_dict via .get() for a more graceful approach that will degrade well if the data isn't as expected.

resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist

You could also add some logic to test for the key if you want as well.

if 'name' in resp_dict:
    resp_dict['name']
else:
    # do something else here.

Guzzle 6: no more json() method for responses

If you guys still interested, here is my workaround based on Guzzle middleware feature:

  1. Create JsonAwaraResponse that will decode JSON response by Content-Type HTTP header, if not - it will act as standard Guzzle Response:

    <?php
    
    namespace GuzzleHttp\Psr7;
    
    
    class JsonAwareResponse extends Response
    {
        /**
         * Cache for performance
         * @var array
         */
        private $json;
    
        public function getBody()
        {
            if ($this->json) {
                return $this->json;
            }
            // get parent Body stream
            $body = parent::getBody();
    
            // if JSON HTTP header detected - then decode
            if (false !== strpos($this->getHeaderLine('Content-Type'), 'application/json')) {
                return $this->json = \json_decode($body, true);
            }
            return $body;
        }
    }
    
  2. Create Middleware which going to replace Guzzle PSR-7 responses with above Response implementation:

    <?php
    
    $client = new \GuzzleHttp\Client();
    
    /** @var HandlerStack $handler */
    $handler = $client->getConfig('handler');
    $handler->push(\GuzzleHttp\Middleware::mapResponse(function (\Psr\Http\Message\ResponseInterface $response) {
        return new \GuzzleHttp\Psr7\JsonAwareResponse(
            $response->getStatusCode(),
            $response->getHeaders(),
            $response->getBody(),
            $response->getProtocolVersion(),
            $response->getReasonPhrase()
        );
    }), 'json_decode_middleware');
    

After this to retrieve JSON as PHP native array use Guzzle as always:

$jsonArray = $client->get('http://httpbin.org/headers')->getBody();

Tested with guzzlehttp/guzzle 6.3.3

Remove rows not .isin('X')

You can use the DataFrame.select method:

In [1]: df = pd.DataFrame([[1,2],[3,4]], index=['A','B'])

In [2]: df
Out[2]: 
   0  1
A  1  2
B  3  4

In [3]: L = ['A']

In [4]: df.select(lambda x: x in L)
Out[4]: 
   0  1
A  1  2

string.split - by multiple character delimiter

Regex.Split("abc][rfd][5][,][.", @"\]\]");

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

The issue is that you're not saving the mysqli connection. Change your connect to:

$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');

And then include it in your query:

$query1 = mysqli_query($aVar, "SELECT name1 FROM users
    ORDER BY RAND()
    LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];

Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.

Best way to disable button in Twitter's Bootstrap

For input and button:

$('button').prop('disabled', true);

For anchor:

$('a').attr('disabled', true);

Checked in firefox, chrome.

See http://jsfiddle.net/czL54/2/

Module AppRegistry is not registered callable module (calling runApplication)

I am using Expo

In my case, I resolved the issue by adding the following code in app.json file

"expo":{
  ...
  "android": {
    "package": "com.mycompanyname.myappname
  }
}

Find index of last occurrence of a sub-string using T-SQL

This answer uses MS SQL Server 2008 (I don't have access to MS SQL Server 2000), but the way I see it according to the OP are 3 situations to take into consideration. From what I've tried no answer here covers all 3 of them:

  1. Return the last index of a search character in a given string.
  2. Return the last index of a search sub-string (more than just a single character) in a given string.
  3. If the search character or sub-string is not in the given string return 0

The function I came up with takes 2 parameters:

@String NVARCHAR(MAX) : The string to be searched

@FindString NVARCHAR(MAX) : Either a single character or a sub-string to get the last index of in @String

It returns an INT that is either the positive index of @FindString in @String or 0 meaning that @FindString is not in @String

Here's an explanation of what the function does:

  1. Initializes @ReturnVal to 0 indicating that @FindString is not in @String
  2. Checks the index of the @FindString in @String by using CHARINDEX()
  3. If the index of @FindString in @String is 0, @ReturnVal is left as 0
  4. If the index of @FindString in @String is > 0, @FindString is in @String so it calculates the last index of @FindString in @String by using REVERSE()
  5. Returns @ReturnVal which is either a positive number that is the last index of @FindString in @String or 0 indicating that @FindString is not in @String

Here's the create function script (copy and paste ready):

CREATE FUNCTION [dbo].[fn_LastIndexOf] 
(@String NVARCHAR(MAX)
, @FindString NVARCHAR(MAX))
RETURNS INT
AS 
BEGIN
    DECLARE @ReturnVal INT = 0
    IF CHARINDEX(@FindString,@String) > 0
        SET @ReturnVal = (SELECT LEN(@String) - 
        (CHARINDEX(REVERSE(@FindString),REVERSE(@String)) + 
        LEN(@FindString)) + 2)  
    RETURN @ReturnVal
END

Here's a little bit that conveniently tests the function:

DECLARE @TestString NVARCHAR(MAX) = 'My_sub2_Super_sub_Long_sub1_String_sub_With_sub_Long_sub_Words_sub2_'
, @TestFindString NVARCHAR(MAX) = 'sub'

SELECT dbo.fn_LastIndexOf(@TestString,@TestFindString)

I have only run this on MS SQL Server 2008 because I don't have access to any other version but from what I've looked into this should be good for 2008+ at least.

Enjoy.

Select multiple columns using Entity Framework

var test_obj = from d in repository.DbPricing
join d1 in repository.DbOfficeProducts on d.OfficeProductId equals d1.Id
join d2 in repository.DbOfficeProductDetails on d1.ProductDetailsId equals d2.Id
    select new
    {
    PricingId = d.Id,
    LetterColor = d2.LetterColor,
    LetterPaperWeight = d2.LetterPaperWeight
    };


http://www.cybertechquestions.com/select-across-multiple-tables-in-entity-framework-resulting-in-a-generic-iqueryable_222801.html

Remove a symlink to a directory

Assuming your setup is something like: ln -s /mnt/bar ~/foo, then you should be able to do a rm foo with no problem. If you can't, make sure you are the owner of the foo and have permission to write/execute the file. Removing foo will not touch bar, unless you do it recursively.

Remove blank attributes from an Object in Javascript

Here's an alternative

Typescript:

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

Javascript:

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

How to deserialize JS date using Jackson?

This works for me - i am using jackson 2.0.4

ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);