Programs & Examples On #Nfa

An NFA is a nondeterministic finite automaton, a mathematical model of computation that decides membership in regular languages.

Are all Spring Framework Java Configuration injection examples buggy?

In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:

A failure occurred while executing com.android.build.gradle.internal.tasks

Finally found a solution for this by adding this line to gradle.properties.

org.gradle.jvmargs=-Xmx4608m

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

For anybody facing a similar issue at this point in time, all you need to do is update your Android Studio to the latest version

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

Extending Yoni Gibbs's answer, if you are in an android project using retrofit and configure serialization with Jackson you can do these things in order to deserialization works as expected with kotlin's data class.

In your build gradle import:

implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.11.+"

Then, your implementation of retrofit:

val serverURL = "http://localhost:8080/api/v1"

val objectMapper = ObjectMapper()
objectMapper.registerModule(KotlinModule())
//Only if you are using Java 8's Time API too, require jackson-datatype-jsr310
objectMapper.registerModule(JavaTimeModule())

Retrofit.Builder()
    .baseUrl(serverURL)
    .client(
        OkHttpClient.Builder()
           .readTimeout(1, TimeUnit.MINUTES)//No mandatory
            .connectTimeout(1, TimeUnit.MINUTES)//No mandatory
            .addInterceptor(UnauthorizedHandler())//No mandatory
            .build())
    .addConverterFactory(
                JacksonConverterFactory.create(objectMapper)
            )
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .build()

Data class:

@JsonIgnoreProperties(ignoreUnknown = true)
data class Task(val id: Int,
                val name: String,
                @JsonSerialize(using = LocalDateTimeSerializer::class)
                @JsonDeserialize(using = LocalDateTimeDeserializer::class)
                val specificDate: LocalDateTime?,
                var completed: Boolean,
                val archived: Boolean,
                val taskListId: UUID?

Axios having CORS issue

CORS issue can be simply resolved by following this:

Create a new shortcut of Google Chrome(update browser installation path accordingly) with following value:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:\chrome\temp"

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Configure Two DataSources in Spring Boot 2.0.* or above

If you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary, because various auto-configurations down the road expect to be able to get one by type.

If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
    return firstDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
    return DataSourceBuilder.create().type(BasicDataSource.class).build();
}

firstDataSourceProperties has to be flagged as @Primary so that the database initializer feature uses your copy (if you use the initializer).

And your application.propoerties will look something like this:

app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver

app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver

The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.

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

Not sure if this solution works for you or not but just want to heads you up on compiler and build tools version compatibility issues.

This could be because of Java and Gradle version mismatch.

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

Gradle 4.4 is compatible with only Java 7 and 8. So, point your global variable JAVA_HOME to Java 7 or 8.

In mac, add below line to your ~/.bash_profile

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home

You can have multiple java versions. Just change the JAVA_HOME path based on need. You can do it easily, check this

laravel Unable to prepare route ... for serialization. Uses Closure

The Actual solution of this problem is changing first line in web.php

Just replace Welcome route with following route

Route::view('/', 'welcome');

If still getting same error than you probab

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 can I manually set an Angular form field as invalid?

For unit test:

spyOn(component.form, 'valid').and.returnValue(true);

Hibernate Error executing DDL via JDBC Statement

in your CFG file please change the hibernate dialect

<!-- SQL dialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

not finding android sdk (Unity)

  1. Delete android sdk "tools" folder : [Your Android SDK root]/tools -> tools

  2. Download SDK Tools: http://dl-ssl.google.com/android/repository/tools_r25.2.5-windows.zip

  3. Extract that to Android SDK root

  4. Build your project

After that it didn't work for me yet, I had to

  1. Go to the Java archives (http://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html)

  2. Search for the jdk-8u131 release.

  3. Accept the Licence Agreement,make an account and download the release.

  4. Install it and define it as JDK path in Unity.

source : https://www.reddit.com/r/Unity3D/comments/77azfb/i_cant_get_unity_to_build_run_my_game/

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

In my case i have included jdbc api dependencies in the project so the "Hello World" not printed. After removing the below dependency it works like a charm.

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

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

1-Delete the migration file. 2-connect to your database and drop the table created by the migration. 3-recreate the file of the migration with the the right sql.

Retrofit 2: Get JSON from Response body

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

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

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

I resolved this issue by Adding implements Serializable in the Model.

@Entity
@Table(name="Model_Rest")
@IdClass(Model_Rest.class)
public class Model_Rest implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    /**
     * 
     */
    //@GeneratedValue(strategy = GenerationType.AUTO)
    //@Column(columnDefinition="id")

    @Id
    private String login;
    @Id
    private String password;




    @Autowired
    public String getLogin() {
        return login;
    }

    @Autowired
    public void setLogin(String login) {
        this.login = login;
    }

    @Autowired
    public String getPassword() {
        return password;
    }

    @Autowired
    public void setPassword(String password) {
        this.password = password;
    }

    public Model_Rest() {
        // TODO Auto-generated constructor stub
    }

    public Model_Rest(String login, String password) {
        this.login = login;
        this.password = password;
    }

    @Override
    public String toString() {
        return "Model_Rest [login=" + login + ", password=" + password + "]";
    }
  }

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

This is a well-known issue and based on this answer you could add setLenient:

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

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

Now, if you add this to your retrofit, it gives you another error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

This is another well-known error you can find answer here (this error means that your server response is not well-formatted); So change server response to return something:

{
    android:[
        { ver:"1.5", name:"Cupcace", api:"Api Level 3" }
        ...
    ]
}

For better comprehension, compare your response with Github api.

Suggestion: to find out what's going on to your request/response add HttpLoggingInterceptor in your retrofit.

Based on this answer your ServiceHelper would be:

private ServiceHelper() {
        httpClient = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.interceptors().add(interceptor);
        Retrofit retrofit = createAdapter().build();
        service = retrofit.create(IService.class);
    }

Also don't forget to add:

compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

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

For me the only thing that works is to add to repositories

maven {
        url "https://maven.google.com"
    }

It should look like this:

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }

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

I was getting this error even when all the relevant dependencies were in place because I hadn't created the schema in MySQL.

I thought it would be created automatically but it wasn't. Although the table itself will be created, you have to create the schema.

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

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

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

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

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

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

you must stop another running app involved with especial database table ... like running java API in other module or other project is not terminated .. so terminate running.

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

starting the hive metastore service worked for me. First, set up the database for hive metastore:

 $ hive --service metastore 

` https://docs.hortonworks.com/HDPDocuments/HDP2/HDP-2.3.4/bk_installing_manually_book/content/validate_installation.html

Second, run the following commands:

 $ schematool -dbType mysql -initSchema  
 $ schematool -dbType mysql -info

https://cwiki.apache.org/confluence/display/Hive/Hive+Schema+Tool

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

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

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

I got that error message in code line containing SqlConnection.Open() running my .NET code as x64 application. Running as x86 causing no errors.

Solution was to deactivate the Force protocol encryption option for TCP/IP in %windir%\System32\cliconfg.exe

Force protocol encryption

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

When I add @ComponentScan("com.firstday.spring.boot.services") or scanBasePackages{"com.firstday.spring.boot.services"} jsp is not loaded. So when I add the parent package of project in @SpringBootApplication class it's working fine in my case

Code Example:-

package com.firstday.spring.boot.firstday;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = {"com.firstday.spring.boot"})
public class FirstDayApplication {

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

}

OkHttp Post Body as JSON

Another approach is by using FormBody.Builder().
Here's an example of callback:

Callback loginCallback = new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        try {
            Log.i(TAG, "login failed: " + call.execute().code());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // String loginResponseString = response.body().string();
        try {
            JSONObject responseObj = new JSONObject(response.body().string());
            Log.i(TAG, "responseObj: " + responseObj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Log.i(TAG, "loginResponseString: " + loginResponseString);
    }
};

Then, we create our own body:

RequestBody formBody = new FormBody.Builder()
        .add("username", userName)
        .add("password", password)
        .add("customCredential", "")
        .add("isPersistent", "true")
        .add("setCookie", "true")
        .build();

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(this)
        .build();
Request request = new Request.Builder()
        .url(loginUrl)
        .post(formBody)
        .build();

Finally, we call the server:

client.newCall(request).enqueue(loginCallback);

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

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

  1. Search for sqllocaldb or localDB in your windows start menu and right click on open file location
  2. Open command prompt in the file location you found from the search
  3. On your command prompt type sqllocaldb start

  4. Use <add name="defaultconnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=tododb;Integrated Security=True" providerName="System.Data.SqlClient" />

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

This error is because of multiple project having the offending resources.

Try out adding the dependencies projects other way around. (like in pom.xml or external depandancies)

enter image description here

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.

WARNING: Exception encountered during context initialization - cancelling refresh attempt

The important part is this:

Cannot find class [com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl] for bean with name 'MemberPointSummaryDAOImpl' defined in ServletContext resource [/WEB-INF/context/PersistenceManagerContext.xml];

due to:

nested exception is java.lang.ClassNotFoundException: com.rakuten.points.persistence.manager.MemberPointSummaryDAOImpl

According to this log, Spring could not find your MemberPointSummaryDAOImpl class.

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

I had exact same error, I was not giving base package. Giving correct base package,ressolved it.

package com.ymc.backend.ymcbe;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages="com.ymc.backend")
public class YmcbeApplication {

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

}

Note: not including .controller @ComponentScan(basePackages="com.ymc.backend.controller") because i have many other component classes which my project does not scan if i just give .controller

Here is my controller sample:

package com.ymc.backend.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@CrossOrigin
@RequestMapping(value = "/user")
public class UserController {

    @PostMapping("/sendOTP")
    public String sendOTP() {
        return "OTP sent";
    };


}

Difference between request.getSession() and request.getSession(true)

request.getSession(true) and request.getSession() both do the same thing, but if we use request.getSession(false) it will return null if session object not created yet.

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.

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

Because of old version I got this error. Then I changed to this version n error gone Using maven my pom.xml

<properties>  
    ...
    <jackson.version>2.5.2</jackson.version>
</properties>

<dependencies>
...
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
</dependencies>

my old version was '2.2.3'

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

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;
}

Can't Autowire @Repository annotated interface in Spring Boot

It seems your @ComponentScan annotation is not set properly. Try :

@ComponentScan(basePackages = {"com.pharmacy"})

Actually you do not need the component scan if you have your main class at the top of the structure, for example directly under com.pharmacy package.

Also, you don't need both

@SpringBootApplication
@EnableAutoConfiguration

The @SpringBootApplication annotation includes @EnableAutoConfiguration by default.

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

I had faced this similar error too. In my case it was one of my picture files in my drawable folder. Removing the picture that was unused solved the problem for me. So, make sure to remove any unused items from drawable folder.

Spring boot - Not a managed type

Below worked for me..

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.apache.catalina.security.SecurityConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.something.configuration.SomethingConfig;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SomethingConfig.class, SecurityConfig.class }) //All your configuration classes
@EnableAutoConfiguration
@WebAppConfiguration // for MVC configuration
@EnableJpaRepositories("com.something.persistence.dataaccess")  //JPA repositories
@EntityScan("com.something.domain.entity.*")  //JPA entities
@ComponentScan("com.something.persistence.fixture") //any component classes you have
public class SomethingApplicationTest {

    @Autowired
    private WebApplicationContext ctx;
    private MockMvc mockMvc;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
    }

    @Test
    public void loginTest() throws Exception {
        this.mockMvc.perform(get("/something/login"))
        .andDo(print()).andExpect(status().isOk());
    }

}

Git Stash vs Shelve in IntelliJ IDEA

git shelve doesn't exist in Git.

Only git stash:

  • when you want to record the current state of the working directory and the index, but want to go back to a clean working directory.
  • which saves your local modifications away and reverts the working directory to match the HEAD commit.

You had a 2008 old project git shelve to isolate modifications in a branch, but that wouldn't be very useful nowadays.

As documented in Intellij IDEA shelve dialog, the feature "shelving and unshelving" is not linked to a VCS (Version Control System tool) but to the IDE itself, to temporarily storing pending changes you have not committed yet in changelist.

Note that since Git 2.13 (Q2 2017), you now can stash individual files too.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

1 Close Android Studio (AS)

2 Delete the folder in C:\Users.gradle\wrapper\dists\gradle-2.1-all

3 Run AS as admin

4 Sync your project files

pass JSON to HTTP POST Request

Example.

var request = require('request');

var url = "http://localhost:3000";

var requestData = {
    ...
} 

var data = {
    url: url,
    json: true,
    body: JSON.stringify(requestData)
}

request.post(data, function(error, httpResponse, body){
    console.log(body);
});

As inserting json: true option, sets body to JSON representation of value and adds "Content-type": "application/json" header. Additionally, parses the response body as JSON. LINK

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

just add login password to connect to RabbitMq

 CachingConnectionFactory connectionFactory = 
         new CachingConnectionFactory("rabbit_host");

 connectionFactory.setUsername("login");
 connectionFactory.setPassword("password");

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.

@GetMapping(value="/person/{id}/", 
            params="format=json",
            produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
    Person person = personMapRepository.findPerson(id);
    return ResponseEntity.ok(person);
} 
@GetMapping(value="/person/{id}/", 
            params="format=xml",
            produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
    return GetPerson(id); // delegate
}

org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

add spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect in application.properties file

Spring Boot, Spring Data JPA with multiple DataSources

thanks to the answers of Steve Park and Rafal Borowiec I got my code working, however, I had one issue: the DriverManagerDataSource is a "simple" implementation and does NOT give you a ConnectionPool (check http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/datasource/DriverManagerDataSource.html).

Hence, I replaced the functions which returns the DataSource for the secondDB to.

public DataSource <secondaryDB>DataSource() {
    // use DataSourceBuilder and NOT DriverManagerDataSource 
    // as this would NOT give you ConnectionPool
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.url(databaseUrl);
    dataSourceBuilder.username(username);
    dataSourceBuilder.password(password);
    dataSourceBuilder.driverClassName(driverClassName);
    return dataSourceBuilder.build();
}

Also, if do you not need the EntityManager as such, you can remove both the entityManager() and the @Bean annotation.

Plus, you may want to remove the basePackages annotation of your configuration class: maintaining it with the factoryBean.setPackagesToScan() call is sufficient.

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

I had this error too because in the file where I used @Transactional annotation, I was importing the wrong class

import javax.transaction.Transactional; 

Instead of javax, use

import org.springframework.transaction.annotation.Transactional; 

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/

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

I just solved this error happening in my tests.

Just make sure your test class has all dependencies in the attributes of the class being tested annotated with @MockBean so SpringBoot test context can wire your classes correctly.

Only if you are testing controller: you need also class annotations to load the Controller context propertly.

Check it out:

@DisplayName("UserController Adapter Test")
@WebMvcTest(UserController.class)
@AutoConfigureMockMvc(addFilters = false)
@Import(TestConfig.class)
public class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper objectMapper;

@MockBean
private CreateUserCommand createUserCommand;

@MockBean
private GetUserListQuery getUserListQuery;

@MockBean
private GetUserQuery getUserQuery;

Java ElasticSearch None of the configured nodes are available

For other users getting this problem.

You may get this error if you are running a newer ElasticSearch (5.5 or later) while running Spring Boot <2 version.

Recommendation is to use the REST Client since the Java Client will be deprecated.

Other workaround would be to upgrade to Spring Boot 2, since that should be compatible.

See https://discuss.elastic.co/t/spring-data-elasticsearch-cant-connect-with-elasticsearch-5-5-0/94235 for more information.

Spring Boot application.properties value not populating

You can use Environment Class to get data :

@Autowired
private Environment env;
String prop= env.getProperty('some.prop');

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

How to create JNDI context in Spring Boot with Embedded Tomcat Container

Please note instead of

public TomcatEmbeddedServletContainerFactory tomcatFactory()

I had to use the following method signature

public EmbeddedServletContainerFactory embeddedServletContainerFactory() 

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

I accomplished something similar using jQuery Waypoints.

There's a lot of moving parts, and quite a bit of logic (that I hope to get on GitHub some day soon), but essentially what you could do is...

  1. Duplicate the table DOM structure in JavaScript and add a class called fixed.
  2. Add styles for table.fixed that make it invisible.
  3. Set a way point at the bottom of the header navigation that adds a class called sticky to table.fixed
  4. Add styles for table.sticky.fixed that position it just below the navbar and also make just the thead content visible. This also has a z-index so it is laid above the rest of the content.
  5. Add another waypoint, but in the downward scroll event, that removes .sticky from the table.fixed

You have to duplicate the entire table DOM in order to ensure column widths line up appropriately.

If that sounds really complicated, you might want to try playing around with the DataTables plugin and the FixedHeader extension: https://datatables.net/extensions/fixedheader/

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

In my specific case I seemed to have been missing the dependency

 <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
 <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>5.1.3.RELEASE</version>
 </dependency>

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

If using Spring Boot this works well. Even with Spring Reactive Mongo.

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

and validation config:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@Configuration
public class MongoValidationConfig {

    @Bean
    public ValidatingMongoEventListener validatingMongoEventListener() {
        return new ValidatingMongoEventListener(validator());
    }

    @Bean
    public LocalValidatorFactoryBean validator() {
        return new LocalValidatorFactoryBean();
    }
}

java.lang.ClassNotFoundException: org.springframework.core.io.Resource

I received same error despite jar being in lib directory & added to deployment assembly in Eclipse.

So I doubted two things ,

1.Some Weblogic cache issue - as this app was deployed before & I was trying to redeploy after some changes

2.Jar itself is corrupt due to partial download etc

So I re downloaded the jar & deleted everything in directory - ..\Oracle_Home\user_projects\domains\base_domain\lib and redeployed again & all went well.

Make sure that the controller has a parameterless public constructor error

I've got this error when I accidentally defined a property as a specific object type, instead of the interface type I have defined in UnityContainer.

For example:

Defining UnityContainer:

var container = new UnityContainer();
container.RegisterInstance(typeof(IDashboardRepository), DashboardRepository);
config.DependencyResolver = new UnityResolver(container);

SiteController (the wrong way - notice repo type):

private readonly DashboardRepository _repo;

public SiteController(DashboardRepository repo)
{
    _repo = repo;
}

SiteController (the right way):

private readonly IDashboardRepository _repo;

public SiteController(IDashboardRepository repo)
{
    _repo = repo;
}

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

I got this issue for a console Application.

In my case i just changed the Platform Target to "Any CPU" which you can see when you right click your solution and click on properties , you will find a Tab "Build" click on it, you will see "Platform target:" change it to "Any CPU", which will solve your issue

ORA-28040: No matching authentication protocol exception

Here is some text I found at experts-exchange:

Bug 14575666

In 12.1, the default value for the SQLNET.ALLOWED_LOGON_VERSION parameter has been updated to 11. This means that database clients using pre-11g JDBC thin drivers cannot authenticate to 12.1 database servers unless theSQLNET.ALLOWED_LOGON_VERSION parameter is set to the old default of 8.

This will cause a 10.2.0.5 Oracle RAC database creation using DBCA to fail with the ORA-28040: No matching authentication protocol error in 12.1 Oracle ASM and Oracle Grid Infrastructure environments.

Workaround: Set SQLNET.ALLOWED_LOGON_VERSION=8 in the oracle/network/admin/sqlnet.ora file.

Spring Boot - Cannot determine embedded database driver class for database type NONE

The same to @Anas. I can run it in Eclipse, but when i use "java -jar ..." run it, it giving me this error. Then i find my java build path is wrong, it missing the folder “src/main/resources”, so, the application can't find application.properties. When i add the “src/main/resources” folder in java build path, it worked.

And, you need add "@PropertySource({"application.properties"})" in your Application class.

Screenshot-1

Screenshot-2

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController'

Make sure that you have added ojdbc14.jar into your library.

For oracle 11g, usie ojdbc6.jar.

How to test Spring Data repositories?

tl;dr

To make it short - there's no way to unit test Spring Data JPA repositories reasonably for a simple reason: it's way to cumbersome to mock all the parts of the JPA API we invoke to bootstrap the repositories. Unit tests don't make too much sense here anyway, as you're usually not writing any implementation code yourself (see the below paragraph on custom implementations) so that integration testing is the most reasonable approach.

Details

We do quite a lot of upfront validation and setup to make sure you can only bootstrap an app that has no invalid derived queries etc.

  • We create and cache CriteriaQuery instances for derived queries to make sure the query methods do not contain any typos. This requires working with the Criteria API as well as the meta.model.
  • We verify manually defined queries by asking the EntityManager to create a Query instance for those (which effectively triggers query syntax validation).
  • We inspect the Metamodel for meta-data about the domain types handled to prepare is-new checks etc.

All stuff that you'd probably defer in a hand-written repository which might cause the application to break at runtime (due to invalid queries etc.).

If you think about it, there's no code you write for your repositories, so there's no need to write any unittests. There's simply no need to as you can rely on our test base to catch basic bugs (if you still happen to run into one, feel free to raise a ticket). However, there's definitely need for integration tests to test two aspects of your persistence layer as they are the aspects that related to your domain:

  • entity mappings
  • query semantics (syntax is verified on each bootstrap attempt anyway).

Integration tests

This is usually done by using an in-memory database and test cases that bootstrap a Spring ApplicationContext usually through the test context framework (as you already do), pre-populate the database (by inserting object instances through the EntityManager or repo, or via a plain SQL file) and then execute the query methods to verify the outcome of them.

Testing custom implementations

Custom implementation parts of the repository are written in a way that they don't have to know about Spring Data JPA. They are plain Spring beans that get an EntityManager injected. You might of course wanna try to mock the interactions with it but to be honest, unit-testing the JPA has not been a too pleasant experience for us as well as it works with quite a lot of indirections (EntityManager -> CriteriaBuilder, CriteriaQuery etc.) so that you end up with mocks returning mocks and so on.

Better way to sum a property value in an array

Updated Answer

Due to all the downsides of adding a function to the Array prototype, I am updating this answer to provide an alternative that keeps the syntax similar to the syntax originally requested in the question.

class TravellerCollection extends Array {
    sum(key) {
        return this.reduce((a, b) => a + (b[key] || 0), 0);
    }
}
const traveler = new TravellerCollection(...[
    {  description: 'Senior', Amount: 50},
    {  description: 'Senior', Amount: 50},
    {  description: 'Adult', Amount: 75},
    {  description: 'Child', Amount: 35},
    {  description: 'Infant', Amount: 25 },
]);

console.log(traveler.sum('Amount')); //~> 235

Original Answer

Since it is an array you could add a function to the Array prototype.

traveler = [
    {  description: 'Senior', Amount: 50},
    {  description: 'Senior', Amount: 50},
    {  description: 'Adult', Amount: 75},
    {  description: 'Child', Amount: 35},
    {  description: 'Infant', Amount: 25 },
];

Array.prototype.sum = function (prop) {
    var total = 0
    for ( var i = 0, _len = this.length; i < _len; i++ ) {
        total += this[i][prop]
    }
    return total
}

console.log(traveler.sum("Amount"))

The Fiddle: http://jsfiddle.net/9BAmj/

org.hibernate.MappingException: Unknown entity: annotations.Users

Add the following code to hibernate.cfg.xml

  <property name="hibernate.c3p0.min_size">5</property>
  <property name="hibernate.c3p0.max_size">20</property>
  <property name="hibernate.c3p0.timeout">300</property>
  <property name="hibernate.c3p0.max_statements">50</property>
  <property name="hibernate.c3p0.idle_test_period">3000</property>

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

There is one more chance to get this exception even we used class name i.e., if we have two classes with same name in different packages. we'll get this problem.

I think hibernate may get ambiguity and throws this exception, so the solution is to use complete qualified name(like com.test.Customerv)

I added this answer that will help in scenario as I mentioned. I got the same scenario got stuck for some time.

System.Data.SqlClient.SqlException: Login failed for user

I faced the same situation. Create your connection string as follows.

Replace

"connectionString": "Data Source=server name;Initial Catalog=DB name;User id=user id;Password=password;Integrated Security=True;MultipleActiveResultSets=True"

by

"connectionString": "Server=server name; Database=Treat; User Id=user id; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true"

Why does my Spring Boot App always shutdown immediately after starting?

If you have a circular spring injected dependency it will fail without warning, depending on the level of logging, and a few other factors.

Class A injects Class B, and Class B injects Class A. Via constructor, in this particular case.

'Invalid update: invalid number of rows in section 0

You need to remove the object from your data array before you call deleteRowsAtIndexPaths:withRowAnimation:. So, your code should look like this:

// Editing of rows is enabled
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        //when delete is tapped
        [currentCart removeObjectAtIndex:indexPath.row];

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

You can also simplify your code a little by using the array creation shortcut @[]:

[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

I had the exact same problem, found that I was missing

<mdb>  
  <resource-adapter-ref resource-adapter-name="hornetq-ra"/>  
  <bean-instance-pool-ref pool-name="mdb-strict-max-pool"/>  
</mdb>  

under

<subsystem xmlns="urn:jboss:domain:ejb3:1.2">  

in standalone/configuration/standalone.xml

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

In my case, I was fetching data from database, changing some column values and updating it in database but for updating I was using the same save query which was violating primary key constraints i.e duplicate values for primary key, so I had written a separate query for updating the columns and it solved my problem..!

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Add "EntityFramework.SqlServer.dll" into your bin folder. Problem will get resolved.

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :

@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}

Spring doc about Aggregating @Configuration classes with @Import: link

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

The best way to handle the LazyInitializationException is to use the JOIN FETCH directive:

Query query = session.createQuery("""
    select m
    from Model m
    join fetch m.modelType
    where modelGroup.id = :modelGroupId
    """
);

Anyway, DO NOT use the following Anti-Patterns as suggested by some of the answers:

Sometimes, a DTO projection is a better choice than fetching entities, and this way, you won't get any LazyInitializationException.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

Mocking static methods with Mockito

Use PowerMockito on top of Mockito.

Example code:

@RunWith(PowerMockRunner.class)
@PrepareForTest(DriverManager.class)
public class Mocker {

    @Test
    public void shouldVerifyParameters() throws Exception {

        //given
        PowerMockito.mockStatic(DriverManager.class);
        BDDMockito.given(DriverManager.getConnection(...)).willReturn(...);

        //when
        sut.execute(); // System Under Test (sut)

        //then
        PowerMockito.verifyStatic();
        DriverManager.getConnection(...);

    }

More information:

android studio 0.4.2: Gradle project sync failed error

After reporting the problem on the Android Studio feedback site, they found a solution for me. I am now using Gradle 1.10 and Android Studio 0.4.3.

Here is the link to the page with a description of how I fixed mine: https://code.google.com/p/android/issues/detail?id=65219

Hope this helps!

OPTION (RECOMPILE) is Always Faster; Why?

There are times that using OPTION(RECOMPILE) makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:

EXEC sp_updatestats

And then recreating your execution plan. This will ensure that when your execution plan is created it will be using the latest information.

Adding OPTION(RECOMPILE) rebuilds the execution plan every time that your query executes. I have never heard that described as creates a new lookup strategy but maybe we are just using different terms for the same thing.

When a stored procedure is created (I suspect you are calling ad-hoc sql from .NET but if you are using a parameterized query then this ends up being a stored proc call) SQL Server attempts to determine the most effective execution plan for this query based on the data in your database and the parameters passed in (parameter sniffing), and then caches this plan. This means that if you create the query where there are 10 records in your database and then execute it when there are 100,000,000 records the cached execution plan may no longer be the most effective.

In summary - I don't see any reason that OPTION(RECOMPILE) would be a benefit here. I suspect you just need to update your statistics and your execution plan. Rebuilding statistics can be an essential part of DBA work depending on your situation. If you are still having problems after updating your stats, I would suggest posting both execution plans.

And to answer your question - yes, I would say it is highly unusual for your best option to be recompiling the execution plan every time you execute the query.

how to fetch data from database in Hibernate

I know that it is very late to answer the question, but it may help someone like me who spent lots off time to fetch data using hql

So the thing is you just have to write a query

Query query = session.createQuery("from Employee");

it will give you all the data list but to fetch data from this you have to write this line.

List<Employee> fetchedData = query.list();

As simple as it looks.

Launching Spring application Address already in use

This is because the port is already running in the background.So you can restart the eclipse and try again. OR open the file application.properties and change the value of 'server.port' to some other value like ex:- 8000/8181

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

Error: java.lang.NoSuchMethodError: javax.persistence.JoinTable.indexes()[Ljavax/persistence/Index;

The only thing that solved my problem was removing the following dependency in pom.xml: <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency>

And replace it for:

<dependency>
  <groupId>javax.persistence</groupId>
  <artifactId>persistence-api</artifactId>
  <version>1.0.2</version>
</dependency>

Hope it helps someone.

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

Because these days ASP.NET is open source, you can find it on GitHub: AspNet.Identity 3.0 and AspNet.Identity 2.0.

From the comments:

/* =======================
 * HASHED PASSWORD FORMATS
 * =======================
 * 
 * Version 2:
 * PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
 * (See also: SDL crypto guidelines v5.1, Part III)
 * Format: { 0x00, salt, subkey }
 *
 * Version 3:
 * PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
 * Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
 * (All UInt32s are stored big-endian.)
 */

"The system cannot find the file specified"

Server Error in '/' Application.

The system cannot find the file specified

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified

Source Error:

     {
                   SqlCommand cmd = new SqlCommand("select * from tblemployee",con);
                   con.Open();
                   GridView1.DataSource = cmd.ExecuteReader();
                   GridView1.DataBind();

Source File: d:\C# programs\kudvenkat\adobasics1\adobasics1\employeedata.aspx.cs Line: 23

if your error is same like mine..just do this

right click on your table in sqlserver object explorer,choose properties in lower left corner in general option there is a connection block with server and connection specification.in your web config for datasource=. or local choose name specified in server in properties..

@Autowired - No qualifying bean of type found for dependency

I was facing the same issue while auto-wiring the class from one of my jar file. I fixed the issue by using @Lazy annotation:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

    @Autowired
    @Lazy
    private IGalaxyCommand iGalaxyCommand;

MySQL Daemon Failed to Start - centos 6

Reference here 2.10.2.1 Troubleshooting Problems Starting the MySQL Server.

1.Find the data directory ,it was configured in my.cnf.

[mysqld]
datadir=/var/lib/mysql

2. Check the err file,it log the error message about why mysql server start failed. the name of err file is related with your hostname.

cd /var/lib/mysql
ll
tail (hostname).err

3.If you find some messages like :

InnoDB: Error: log file ./ib_logfile0 is of different size 0 33554432 bytes
InnoDB: than specified in the .cnf file 0 5242880 bytes!
170513 14:25:22 [ERROR] Plugin 'InnoDB' init function returned error.
170513 14:25:22 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
170513 14:25:22 [ERROR] Unknown/unsupported storage engine: InnoDB
170513 14:25:22 [ERROR] Aborting

then

delete ib_logfile0 and ib_logfile1

, then,

/etc/init.d/mysqld start

Could not resolve placeholder in string value

You can also try default values. spring-value-annotation

Default values can be provided for properties that might not be defined. In this example the value “some default” will be injected:

@Value("${unknown.param:some default}")
private String someDefault;

If the same property is defined as a system property and in the properties file, then the system property would be applied.

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

For my situation, I switched the value of "fork" to false, such as <fork>false</fork>. I do not understand why, hope someone could explain to me. Thanks in advance.

BeanFactory not initialized or already closed - call 'refresh' before

This problem can be caused also by jvm version used to compile the project and the jvm supported by the servlet container. Try to Fix the project build path. For example if you deploy on tomcat 9, use jvm 1.8.0 or lower.

could not extract ResultSet in hibernate

The @JoinColumn annotation specifies the name of the column being used as the foreign key on the targeted entity.

On the Product class above, the name of the join column is set to ID_CATALOG.

@ManyToOne
@JoinColumn(name="ID_CATALOG")
private Catalog catalog;

However, the foreign key on the Product table is called catalog_id

`catalog_id` int(11) DEFAULT NULL,

You'll need to change either the column name on the table or the name you're using in the @JoinColumn so that they match. See http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-association

WCF Exception: Could not find a base address that matches scheme http for the endpoint

I tried the binding according to the answer by @Szymon but It did not work for me. I tried basicHttpsBinding which is new in .net 4.5 and It solved the issue. Here is the complete configuration that works for me.

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <basicHttpsBinding>
        <binding name="basicHttpsBindingForYourService">
          <security mode="Transport">
            <transport clientCredentialType="None" proxyCredentialType="None"/>
          </security>
        </binding>
      </basicHttpsBinding>
    </bindings>
    <services>
      <service name="YourServiceName">
        <endpoint address="" binding="basicHttpsBinding" bindingName="basicHttpsBindingForYourService" contract="YourContract" />
      </service>
    </services>   
</system.serviceModel>

FYI: My application's target framework is 4.5.1. IIS web site that I created to deploy this wcf service only has https binding enabled.

Parsing JSON in Java without knowing JSON format

JSON of unknown format to HashMap

writing JSON And reading Json

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

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

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

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

    JSONObject json = new JSONObject();

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

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

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

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

    json.put("InnerObject", jsonObj);

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

    json.put("InnerObjectArray", jsonObjArray);

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

    json.put("TreeMap", sortedTree);        

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

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

}

How to add header data in XMLHttpRequest when using formdata?

Use: xmlhttp.setRequestHeader(key, value);

Spring Data JPA - "No Property Found for Type" Exception

In JPA a relationship has a single owner, and by using mappedByin your UserBoard class you tell that PinItem is the owner of that bidirectional relationship, and that the property in PinItem of the relationship is named board.

In your UserBoard class you do not have any fields/properties with the name board, but it has a property pinItemList, so you might try to use that property instead.

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

YES!!!

Install-Package Microsoft.AspNet.WebApi -Version 5.0.0

It works fine in my case....thnkz

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

This is the normal behavior and the reason is that your sqlCommandHandlerService.persist method needs a TX when being executed (because it is marked with @Transactional annotation). But when it is called inside processNextRegistrationMessage, because there is a TX available, the container doesn't create a new one and uses existing TX. So if any exception occurs in sqlCommandHandlerService.persist method, it causes TX to be set to rollBackOnly (even if you catch the exception in the caller and ignore it).

To overcome this you can use propagation levels for transactions. Have a look at this to find out which propagation best suits your requirements.

Update; Read this!

Well after a colleague came to me with a couple of questions about a similar situation, I feel this needs a bit of clarification.
Although propagations solve such issues, you should be VERY careful about using them and do not use them unless you ABSOLUTELY understand what they mean and how they work. You may end up persisting some data and rolling back some others where you don't expect them to work that way and things can go horribly wrong.


EDIT Link to current version of the documentation

Setting up JUnit with IntelliJ IDEA

  1. Create and setup a "tests" folder
    • In the Project sidebar on the left, right-click your project and do New > Directory. Name it "test" or whatever you like.
    • Right-click the folder and choose "Mark Directory As > Test Source Root".
  2. Adding JUnit library
    • Right-click your project and choose "Open Module Settings" or hit F4. (Alternatively, File > Project Structure, Ctrl-Alt-Shift-S is probably the "right" way to do this)
    • Go to the "Libraries" group, click the little green plus (look up), and choose "From Maven...".
    • Search for "junit" -- you're looking for something like "junit:junit:4.11".
    • Check whichever boxes you want (Sources, JavaDocs) then hit OK.
    • Keep hitting OK until you're back to the code.
  3. Write your first unit test

    • Right-click on your test folder, "New > Java Class", call it whatever, e.g. MyFirstTest.
    • Write a JUnit test -- here's mine:

      import org.junit.Assert;
      import org.junit.Test;
      
      public class MyFirstTest {
          @Test
          public void firstTest() {
              Assert.assertTrue(true);
          }
      }
      
  4. Run your tests
    • Right-click on your test folder and choose "Run 'All Tests'". Presto, testo.
    • To run again, you can either hit the green "Play"-style button that appeared in the new section that popped on the bottom of your window, or you can hit the green "Play"-style button in the top bar.

Use a loop to plot n charts Python

Ok, so the easiest method to create several plots is this:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
    plt.figure()
    plt.plot(x[i],y[i])
    # Show/save figure as desired.
    plt.show()
# Can show all four figures at once by calling plt.show() here, outside the loop.
#plt.show()

Note that you need to create a figure every time or pyplot will plot in the first one created.

If you want to create several data series all you need to do is:

import matplotlib.pyplot as plt
plt.figure()
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')

You could automate it by having a list of colours like ['r','g','b','k'] and then just calling both entries in this list and corresponding data to be plotted in a loop if you wanted to. If you just want to programmatically add data series to one plot something like this will do it (no new figure is created each time so everything is plotted in the same figure):

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']
plt.figure() # In this example, all the plots will be in one figure.    
for i in range(len(x)):
    plt.plot(x[i],y[i],colours[i])
plt.show()

Hope this helps. If anything matplotlib has a very good documentation page with plenty of examples.

17 Dec 2019: added plt.show() and plt.figure() calls to clarify this part of the story.

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

I took @jaytrixz's answer/comment one step further and added "text/html" to the existing set of types. That way when they fix it on the server side to "application/json" or "text/json" I claim it'll work seamlessly.

  manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

Q: If PyPy can solve these great challenges (speed, memory consumption, parallelism) in comparison to CPython, what are its weaknesses that are preventing wider adoption?

A: First, there is little evidence that the PyPy team can solve the speed problem in general. Long-term evidence is showing that PyPy runs certain Python codes slower than CPython and this drawback seems to be rooted very deeply in PyPy.

Secondly, the current version of PyPy consumes much more memory than CPython in a rather large set of cases. So PyPy didn't solve the memory consumption problem yet.

Whether PyPy solves the mentioned great challenges and will in general be faster, less memory hungry, and more friendly to parallelism than CPython is an open question that cannot be solved in the short term. Some people are betting that PyPy will never be able to offer a general solution enabling it to dominate CPython 2.7 and 3.3 in all cases.

If PyPy succeeds to be better than CPython in general, which is questionable, the main weakness affecting its wider adoption will be its compatibility with CPython. There also exist issues such as the fact that CPython runs on a wider range of CPUs and OSes, but these issues are much less important compared to PyPy's performance and CPython-compatibility goals.


Q: Why can't I do drop in replacement of CPython with PyPy now?

A: PyPy isn't 100% compatible with CPython because it isn't simulating CPython under the hood. Some programs may still depend on CPython's unique features that are absent in PyPy such as C bindings, C implementations of Python object&methods, or the incremental nature of CPython's garbage collector.

CodeIgniter - How to return Json response from controller

For CodeIgniter 4, you can use the built-in API Response Trait

Here's sample code for reference:

<?php namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class Home extends BaseController
{
    use ResponseTrait;

    public function index()
    {
        $data = [
            'data' => 'value1',
            'data2' => 'value2',
        ];

        return $this->respond($data);
    }
}

Solve error javax.mail.AuthenticationFailedException

I had this issue as well but the solution had nothing to do with coding. Make sure you are able to connect to gmail. Ping smtp.gmail.com. If you don't get a reply check your firewall settings. It could also be a proxy setting issue.

Location of hibernate.cfg.xml in project?

Give the path relative to your project.

Create a folder called resources in your src and put your config file there.

   configuration.configure("/resources/hibernate.cfg.xml");

And If you check your code

Configuration  configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return new Configuration().configure().buildSessionFactory();

In two lines you are creating two configuration objects.

That should work(haven't tested) if you write,

Configuration  configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return  configuration.buildSessionFactory();

But It fails after you deploy on the server,Since you are using system path than project relative path.

Javascript String to int conversion

Convert by Number Class:-

Eg:

var n = Number("103");
console.log(n+1)

Output: 104

Note:- Number is class. When we pass string, then constructor of Number class will convert it.

Send XML data to webservice using php curl

Previous anwser works fine. I would just add that you dont need to specify CURLOPT_POSTFIELDS as "xmlRequest=" . $input_xml to read your $_POST. You can use file_get_contents('php://input') to get the raw post data as plain XML.

HQL Hibernate INNER JOIN

Joins can only be used when there is an association between entities. Your Employee entity should not have a field named id_team, of type int, mapped to a column. It should have a ManyToOne association with the Team entity, mapped as a JoinColumn:

@ManyToOne
@JoinColumn(name="ID_TEAM")
private Team team;

Then, the following query will work flawlessly:

select e from Employee e inner join e.team

Which will load all the employees, except those that aren't associated to any team.

The same goes for all the other fields which are a foreign key to some other table mapped as an entity, of course (id_boss, id_profession).

It's time for you to read the Hibernate documentation, because you missed an extremely important part of what it is and how it works.

java.math.BigInteger cannot be cast to java.lang.Long

I'm lacking context, but this is working just fine:

List<BigInteger> nums = new ArrayList<BigInteger>();
Long max = Collections.max(nums).longValue(); // from BigInteger to Long...

Cannot hide status bar in iOS7

In order to use the legacy UIApplication method to hide/show the status bar, your app must set a plist value for iOS 7:

View-Controller Based Status Bar Appearance = NO

This value is set to YES by default. If you change it to NO, you can use the legacy methods. If you leave it set to YES, you can still hide the status bar, but it's up to each view controller subclass in your app to override: prefersStatusBarHidden to return YES.

Any time your app needs the status bar appearance or visibility to change, and View-Controller Based Status Bar Appearance is set to YES, your outermost view controller needs to call:

setNeedsStatusBarAppearanceUpdateAnimation

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

You are missing setter for salt property as indicated by the exception

Please add the setter as

 public void setSalt(long salt) {
      this.salt=salt;
 }

How to build & install GLFW 3 and use it in a Linux project

I solved it in this way

A pkg-config file describes all necessary compile-time and link-time flags and dependencies needed to use a library.

pkg-config --static --libs glfw3

shows me that

-L/usr/local/lib -lglfw3 -lrt -lXrandr -lXinerama -lXi -lXcursor -lGL -lm -ldl -lXrender -ldrm -lXdamage -lX11-xcb -lxcb-glx -lxcb-dri2 -lxcb-dri3 -lxcb-present -lxcb-sync -lxshmfence -lXxf86vm -lXfixes -lXext -lX11 -lpthread -lxcb -lXau -lXdmcp  

I don't know if all these libs are actually necessary for compiling but for me it works...

Spring not autowiring in unit tests with JUnit

You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml available on the test classpath.

import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {

    @Autowired
    protected SessionFactory sessionFactory;

    @Test
    public void testDBSourceIsCorrect() throws SQLException {
        String databaseProductName = sessionFactory.getCurrentSession()
                .connection()
                .getMetaData()
                .getDatabaseProductName();
        assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
    }
}

Note: This works with Spring 2.5.2 and Hibernate 3.6.5

WCF Service, the type provided as the service attribute values…could not be found

This is an old bug, but I encountered it today on a web service which had barely been altered since being created via "New \ Project.."

For me, this issue was caused by the "IService.cs" file containing the following:

<%@ ServiceHost Language="C#" Debug="true" Service="JSONWebService.Service1.svc" CodeBehind="Service1.svc.cs" %>

Notice the value in the Service attribute contains ".svc" at the end.

This shouldn't be there.

Removing those 4 characters resolved this issue.

<%@ ServiceHost Language="C#" Debug="true" Service="JSONWebService.Service1" CodeBehind="Service1.svc.cs" %>

Note that you need to open this file from outside of Visual Studio.

Visual Studio shows one file, Service1.cs in the Solution Explorer, but that only lets you alter Service1.svc.cs, not the Service1.svc file.

Gradle: Execution failed for task ':processDebugManifest'

I also faced this error when I was adding firebase push notifications in my app. but in my case I was doing a very silly mistake which i noticed after some time. I declared below code in manifest two times. After removing duplicate declaration. my issue solved.

        <service   android:name="com.evampsaanga.mytelenor.firebase.MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>`

so you also check if there is anything duplicate in your app manifest file.

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

If you are maintaining one more cinfiguration file for app.config , Don't include any key in parent page.

Parent Page : app.config

<appSettings configSource="appSettings.config">
    <add key="ClientSettings" value="venice" /> <!-- Don't add Key Here -->
</appSettings>

Child Page : appSettings.config

<appSettings>
  <add key="ClientSettings" value="venice"/> <!-- add Here -->
</appSettings>

WCF error - There was no endpoint listening at

You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding, and the default value for securityMode\transport for that binding is Message.

Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration attribute:

<bindings>
  <wsHttpBinding>
    <binding name="ota2010AEndpoint" 
             .......>
      <readerQuotas maxDepth="32" ... />
        <reliableSession ordered="true" .... />
          <security mode="Transport">
            <transport clientCredentialType="None" proxyCredentialType="None"
                       realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
                     establishSecurityContext="true" />
          </security>
    </binding>
  </wsHttpBinding>
</bindings>    

(Snipped parts of the config to save space in the answer).

<service name="Synxis" behaviorConfiguration="SynxisWCF">
    <endpoint address="" name="wsHttpEndpoint" 
              binding="wsHttpBinding" 
              bindingConfiguration="ota2010AEndpoint"
              contract="Synxis" />

This will then assign your defined binding (with Transport security) to the endpoint.

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this:

 Select 
    Id, 
    Salt, 
    Password, 
    BannedEndDate, 
    (Select Count(*) 
        From LoginFails 
        Where username = '" + LoginModel.Username + "' And IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "')
 From Users 
 Where username = '" + LoginModel.Username + "'

And I recommend you strongly to use parameters in your query to avoid security risks with sql injection attacks!

Hope that helps!

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Read the message:

Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element.

Move the configSections element to the top - just above where system.data is currently.

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

Use above annotation if someone is facing :--org.hibernate.jpa.HibernatePersistenceProvider persistence provider when it attempted to create the container entity manager factory for the paymentenginePU persistence unit. The following error occurred: [PersistenceUnit: paymentenginePU] Unable to build Hibernate SessionFactory ** This is a solution if you are using Audit table.@Audit

Use:- @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) on superclass.

How does it work - requestLocationUpdates() + LocationRequest/Listener

You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:

mLocationClient.requestLocationUpdates(mLocationRequest, this);

Be sure that the LocationListener you're implementing is from the google api, that is import this:

import com.google.android.gms.location.LocationListener;

and not this:

import android.location.LocationListener;

and it should work just fine.

It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html

Decoding JSON String in Java

Instead of downloading separate java files as suggested by Veer, you could just add this JAR file to your package.

To add the jar file to your project in Eclipse, do the following:

  1. Right click on your project, click Build Path > Configure Build Path
  2. Goto Libraries tab > Add External JARs
  3. Locate the JAR file and add

SQL Error: 0, SQLState: 08S01 Communications link failure

Check your server config file /etc/mysql/my.cnf - verify bind_address is not set to 127.0.0.1. Set it to 0.0.0.0 or comment it out then restart server with:

sudo service mysql restart

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

For me the problem was invalid permissions - I was requesting "birthday" instead of "user_birthday". It's a shame the error message isn't at least minimally descriptive - just saying "permissions invalid" rather than ERROR CODE 2 would have saved me so much time.

javax.naming.NoInitialContextException - Java

We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext.

In a standalone application, you can specify that as below

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");

Context ctx = new InitialContext(env);

But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext as below

System.getProperty(Context.PROVIDER_URL);

and

these values will be set while starting the container as JVM arguments. So if you are running the code in a container, the following will work

InitialContext ctx = new InitialContext();

Pandas: rolling mean by time interval

user2689410's code was exactly what I needed. Providing my version (credits to user2689410), which is faster due to calculating mean at once for whole rows in the DataFrame.

Hope my suffix conventions are readable: _s: string, _i: int, _b: bool, _ser: Series and _df: DataFrame. Where you find multiple suffixes, type can be both.

import pandas as pd
from datetime import datetime, timedelta
import numpy as np

def time_offset_rolling_mean_df_ser(data_df_ser, window_i_s, min_periods_i=1, center_b=False):
    """ Function that computes a rolling mean

    Credit goes to user2689410 at http://stackoverflow.com/questions/15771472/pandas-rolling-mean-by-time-interval

    Parameters
    ----------
    data_df_ser : DataFrame or Series
         If a DataFrame is passed, the time_offset_rolling_mean_df_ser is computed for all columns.
    window_i_s : int or string
         If int is passed, window_i_s is the number of observations used for calculating
         the statistic, as defined by the function pd.time_offset_rolling_mean_df_ser()
         If a string is passed, it must be a frequency string, e.g. '90S'. This is
         internally converted into a DateOffset object, representing the window_i_s size.
    min_periods_i : int
         Minimum number of observations in window_i_s required to have a value.

    Returns
    -------
    Series or DataFrame, if more than one column

    >>> idx = [
    ...     datetime(2011, 2, 7, 0, 0),
    ...     datetime(2011, 2, 7, 0, 1),
    ...     datetime(2011, 2, 7, 0, 1, 30),
    ...     datetime(2011, 2, 7, 0, 2),
    ...     datetime(2011, 2, 7, 0, 4),
    ...     datetime(2011, 2, 7, 0, 5),
    ...     datetime(2011, 2, 7, 0, 5, 10),
    ...     datetime(2011, 2, 7, 0, 6),
    ...     datetime(2011, 2, 7, 0, 8),
    ...     datetime(2011, 2, 7, 0, 9)]
    >>> idx = pd.Index(idx)
    >>> vals = np.arange(len(idx)).astype(float)
    >>> ser = pd.Series(vals, index=idx)
    >>> df = pd.DataFrame({'s1':ser, 's2':ser+1})
    >>> time_offset_rolling_mean_df_ser(df, window_i_s='2min')
                          s1   s2
    2011-02-07 00:00:00  0.0  1.0
    2011-02-07 00:01:00  0.5  1.5
    2011-02-07 00:01:30  1.0  2.0
    2011-02-07 00:02:00  2.0  3.0
    2011-02-07 00:04:00  4.0  5.0
    2011-02-07 00:05:00  4.5  5.5
    2011-02-07 00:05:10  5.0  6.0
    2011-02-07 00:06:00  6.0  7.0
    2011-02-07 00:08:00  8.0  9.0
    2011-02-07 00:09:00  8.5  9.5
    """

    def calculate_mean_at_ts(ts):
        """Function (closure) to apply that actually computes the rolling mean"""
        if center_b == False:
            dslice_df_ser = data_df_ser[
                ts-pd.datetools.to_offset(window_i_s).delta+timedelta(0,0,1):
                ts
            ]
            # adding a microsecond because when slicing with labels start and endpoint
            # are inclusive
        else:
            dslice_df_ser = data_df_ser[
                ts-pd.datetools.to_offset(window_i_s).delta/2+timedelta(0,0,1):
                ts+pd.datetools.to_offset(window_i_s).delta/2
            ]
        if  (isinstance(dslice_df_ser, pd.DataFrame) and dslice_df_ser.shape[0] < min_periods_i) or \
            (isinstance(dslice_df_ser, pd.Series) and dslice_df_ser.size < min_periods_i):
            return dslice_df_ser.mean()*np.nan   # keeps number format and whether Series or DataFrame
        else:
            return dslice_df_ser.mean()

    if isinstance(window_i_s, int):
        mean_df_ser = pd.rolling_mean(data_df_ser, window=window_i_s, min_periods=min_periods_i, center=center_b)
    elif isinstance(window_i_s, basestring):
        idx_ser = pd.Series(data_df_ser.index.to_pydatetime(), index=data_df_ser.index)
        mean_df_ser = idx_ser.apply(calculate_mean_at_ts)

    return mean_df_ser

An Authentication object was not found in the SecurityContext - Spring 3.2.2

This could also happens if you put a @PreAuthorize or @PostAuthorize in a Bean in creation. I would recommend to move such annotations to methods of interest.

Start an activity from a fragment

If you are using getActivity() then you have to make sure that the calling activity is added already. If activity has not been added in such case so you may get null when you call getActivity()

in such cases getContext() is safe

then the code for starting the activity will be slightly changed like,

Intent intent = new Intent(getContext(), mFragmentFavorite.class);
startActivity(intent);

Activity, Service and Application extends ContextWrapper class so you can use this or getContext() or getApplicationContext() in the place of first argument.

How do I disable fail_on_empty_beans in Jackson?

ObjectMapper mapper = new ObjectMapper();

Hi,

When I use mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)

My json object values come '' blank in angular page mean in response

Solved with the help of only below settings

mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker().
withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

My Application Could not open ServletContext resource

I encountered this exception in WebLogic, turns out it is a bug in WebLogic. Please see here for more details: Spring Boot exception: Could not open ServletContext resource [/WEB-INF/dispatcherServlet-servlet.xml]

File inside jar is not visible for spring

I know this question has already been answered. However, for those using spring boot, this link helped me - https://smarterco.de/java-load-file-classpath-spring-boot/

However, the resourceLoader.getResource("classpath:file.txt").getFile(); was causing this problem and sbk's comment:

That's it. A java.io.File represents a file on the file system, in a directory structure. The Jar is a java.io.File. But anything within that file is beyond the reach of java.io.File. As far as java is concerned, until it is uncompressed, a class in jar file is no different than a word in a word document.

helped me understand why to use getInputStream() instead. It works for me now!

Thanks!

Can't access Eclipse marketplace

in my case the solution was to set the proxy to "native" I had configured the proxy under linux with cntlm and also in Firefox (used as eclipse browser also.

Spring Security redirect to previous page after successful login

What happens after login (to which url the user is redirected) is handled by the AuthenticationSuccessHandler.

This interface (a concrete class implementing it is SavedRequestAwareAuthenticationSuccessHandler) is invoked by the AbstractAuthenticationProcessingFilter or one of its subclasses like (UsernamePasswordAuthenticationFilter) in the method successfulAuthentication.

So in order to have an other redirect in case 3 you have to subclass SavedRequestAwareAuthenticationSuccessHandler and make it to do what you want.


Sometimes (depending on your exact usecase) it is enough to enable the useReferer flag of AbstractAuthenticationTargetUrlRequestHandler which is invoked by SimpleUrlAuthenticationSuccessHandler (super class of SavedRequestAwareAuthenticationSuccessHandler).

<bean id="authenticationFilter"
      class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
    <property name="filterProcessesUrl" value="/login/j_spring_security_check" />
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="authenticationSuccessHandler">
        <bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
            <property name="useReferer" value="true"/>
        </bean>
    </property>
    <property name="authenticationFailureHandler">
        <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
            <property name="defaultFailureUrl" value="/login?login_error=t" />
        </bean>
    </property>
</bean>

Hibernate table not mapped error in HQL query

This answer comes late but summarizes the concept involved in the "table not mapped" exception(in order to help those who come across this problem since its very common for hibernate newbies). This error can appear due to many reasons but the target is to address the most common one that is faced by a number of novice hibernate developers to save them hours of research. I am using my own example for a simple demonstration below.

The exception:

org.hibernate.hql.internal.ast.QuerySyntaxException: subscriber is not mapped [ from subscriber]

In simple words, this very usual exception only tells that the query is wrong in the below code.

Session session = this.sessionFactory.getCurrentSession();
List<Subscriber> personsList = session.createQuery(" from subscriber").list();

This is how my POJO class is declared:

@Entity
@Table(name = "subscriber")
public class Subscriber

But the query syntax "from subscriber" is correct and the table subscriber exists. Which brings me to a key point:

  • It is an HQL query not SQL.

and how its explained here

HQL works with persistent objects and their properties not with the database tables and columns.

Since the above query is an HQL one, the subscriber is supposed to be an entity name not a table name. Since I have my table subscriber mapped with the entity Subscriber. My problem solves if I change the code to this:

Session session = this.sessionFactory.getCurrentSession();
List<Subscriber> personsList = session.createQuery(" from Subscriber").list();

Just to keep you from getting confused. Please note that HQL is case sensitive in a number of cases. Otherwise it would have worked in my case.

Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.

https://www.tutorialspoint.com/hibernate/hibernate_query_language.htm

To further understand how hibernate mapping works, please read this

Autowiring fails: Not an managed Type

Refering to Oliver Gierke's hint:

When the manipulation of the persistance.xml does the trick, then you created a normal java-class instead of a entity-class.

When creating a new entity-class then the entry in the persistance.xml should be set by Netbeans (in my case).

But as mentioned by Oliver Gierke you can add the entry later to the persistance.xml (if you created a normal java-class).

Entity Framework Provider type could not be loaded?

This only happens inside my load/unit testing projects. Frustrating, I jyst had it crop up in a project I have been running for 2 years. Must have been some order of test running that breaks things. I guess once that fi gets removed its gone.

I found that simply declaring a variable that uses the correct value fixes the issue... I never even call the method. Just define it. Odd but it works.

    /// <summary>
    /// So that the test runner copies dlls not directly referenced by the integration project
    /// </summary>
    private void referenceLibs()
    {
        var useless = SqlProviderServices.Instance;
    }

Cannot find the declaration of element 'beans'

Add this code ..It helped me

<?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns:context="http://www.springframework.org/schema/context" 
         xmlns:aop="http://www.springframework.org/schema/aop" 
         xsi:schemaLocation="
         http://www.springframework.org/schema/beans 
           classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd 
         http://www.springframework.org/schema/context 
         classpath:/org/springframework/context/config/spring-context-3.0.xsd
        http://www.springframework.org/schema/aop 
        classpath:/org/springframework/aop/config/spring-aop-3.0.xsd
         ">      
     </beans>

Jackson - best way writes a java list to a json array

In objectMapper we have writeValueAsString() which accepts object as parameter. We can pass object list as parameter get the string back.

List<Apartment> aptList =  new ArrayList<Apartment>();
    Apartment aptmt = null;
    for(int i=0;i<5;i++){
         aptmt= new Apartment();
         aptmt.setAptName("Apartment Name : ArrowHead Ranch");
         aptmt.setAptNum("3153"+i);
         aptmt.setPhase((i+1));
         aptmt.setFloorLevel(i+2);
         aptList.add(aptmt);
    }
mapper.writeValueAsString(aptList)

Spring profiles and testing

public class LoginTest extends BaseTest {
    @Test
    public void exampleTest( ){ 
        // Test
    }
}

Inherits from a base test class (this example is testng rather than jUnit, but the ActiveProfiles is the same):

@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
@ActiveProfiles(resolver = MyActiveProfileResolver.class)
public class BaseTest extends AbstractTestNGSpringContextTests { }

MyActiveProfileResolver can contain any logic required to determine which profile to use:

public class MyActiveProfileResolver implements ActiveProfilesResolver {
    @Override
    public String[] resolve(Class<?> aClass) {
        // This can contain any custom logic to determine which profiles to use
        return new String[] { "exampleProfile" };
    }
}

This sets the profile which is then used to resolve dependencies required by the test.

Hibernate Delete query

I'm not sure but:

  • If you call the delete method with a non transient object, this means first fetched the object from the DB. So it is normal to see a select statement. Perhaps in the end you see 2 select + 1 delete?

  • If you call the delete method with a transient object, then it is possible that you have a cascade="delete" or something similar which requires to retrieve first the object so that "nested actions" can be performed if it is required.


Edit: Calling delete() with a transient instance means doing something like that:

MyEntity entity = new MyEntity();
entity.setId(1234);
session.delete(entity);

This will delete the row with id 1234, even if the object is a simple pojo not retrieved by Hibernate, not present in its session cache, not managed at all by Hibernate.

If you have an entity association Hibernate probably have to fetch the full entity so that it knows if the delete should be cascaded to associated entities.

ActiveMQ connection refused

I encountered a similar problem when I was using the below to obtain connection factory ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");

Its resolved when I changed it to the below

ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");

The below then showed that my Q size was increasing.. http://:8161/admin/queues.jsp

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

for converting dd/mm/yyyy to mm/dd/yyyy

=DATE(RIGHT(a1,4),MID(a1,4,2),LEFT(a1,2))

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

I encountered the same problem in the code and What I did is I found out all the changes I have made from the last correct compilation. And I have observed one function declaration was without ";" and also it was passing a value and I have declared it to pass nothing "void". this method will surely solve the problem for many.

Viscon

How to make Sonar ignore some classes for codeCoverage metric?

For me this worked (basically pom.xml level global properties):

<properties>
    <sonar.exclusions>**/Name*.java</sonar.exclusions>
</properties>

According to: http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus#NarrowingtheFocus-Patterns

It appears you can either end it with ".java" or possibly "*"

to get the java classes you're interested in.

Could not autowire field in spring. why?

I had exactly the same problem try to put the two classes in the same package and add line in the pom.xml

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

User GETDATE() to put current date into SQL variable

You don't need the SELECT

DECLARE @LastChangeDate as date
SET @LastChangeDate = GetDate()

How to pass arguments from command line to gradle

project.group is a predefined property. With -P, you can only set project properties that are not predefined. Alternatively, you can set Java system properties (-D).

deleted object would be re-saved by cascade (remove deleted object from associations)

Some how all the above solutions did not worked in hibernate 5.2.10.Final.

But setting the map to null as below worked for me:

playlist.setPlaylistadMaps(null);

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

I can't see anything obviously wrong, but perhaps a different approach might help you debug it?

You could try specify your datasource in the per-application-context instead of the global tomcat one.

You can do this by creating a src/main/webapp/META-INF/context.xml (I'm assuming you're using the standard maven directory structure - if not, then the META-INF folder should be a sibling of your WEB-INF directory). The contents of the META-INF/context.xml file would look something like:

<?xml version="1.0" encoding="UTF-8"?>

<Context [optional other attributes as required]>

<Resource name="jdbc/PollDatasource" auth="Container"
          type="javax.sql.DataSource" driverClassName="org.apache.derby.jdbc.ClientDriver"
          url="jdbc:derby://localhost:1527/poll_database;create=true"
          username="suhail" password="suhail" maxActive="20" maxIdle="10" maxWait="-1"/>
</Context>

Obviously the path and docBase would need to match your application's specific details.

Using this approach, you don't have to specify the datasource details in Tomcat's context.xml file. Although, if you have multiple applications talking to the same database, then your approach makes more sense.

At any rate, give this a whirl and see if it makes any difference. It might give us a clue as to what is going wrong with your approach.

How to POST request using RestSharp

it is better to use json after post your resuest like below

  var clien = new RestClient("https://smple.com/");
  var request = new RestRequest("index", Method.POST);
  request.AddHeader("Sign", signinstance);    
  request.AddJsonBody(JsonConvert.SerializeObject(yourclass));
  var response = client.Execute<YourReturnclassSample>(request);
  if (response.StatusCode == System.Net.HttpStatusCode.Created)
   {
       return Ok(response.Content);
   }

Hibernate: get entity by id

Using EntityManager em;

public User getUserById(Long id) {
     return em.getReference(User.class, id);
}

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

Copy Local = True was solve for one of my projects. But in another project, I get the same error, tried to set Copy Local = true, but it not solve my problem. Changing the Target framework from 4.5.1 to 4.5 in Project Properties Helped with this.

WCF service maxReceivedMessageSize basicHttpBinding issue

Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:

<services>
  <service name="Service.IService">
    <clear />
    <endpoint binding="basicHttpBinding" contract="Service.IService" />
  </service>
</services>
<bindings>
  <basicHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
      <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
        maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
    </binding>
  </basicHttpBinding>
  <webHttpBinding>
    <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
  </webHttpBinding>
</bindings>

Also note that I removed the bindingConfiguration attribute from the endpoint node. Otherwise you would get an exception.

This same solution was found here : Problem with large requests in WCF

Hibernate error: ids for this class must be manually assigned before calling save():

Your @Entity class has a String type for its @Id field, so it can't generate ids for you.

If you change it to an auto increment in the DB and a Long in java, and add the @GeneratedValue annotation:

@Id
@Column(name="U_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long U_id;

it will handle incrementing id generation for you.

hash keys / values as array

In ES5 supported (or shimmed) browsers...

var keys = Object.keys(myHash);

var values = keys.map(function(v) { return myHash[v]; });

Shims from MDN...

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

You will have to annotate your service with @Service since you have said I am using annotations for mapping

Tomcat 7 "SEVERE: A child container failed during start"

I have the same problem a few months ago. This solve my problem using Maven instead of a downloaded version of Spring and some changes in the web.xml.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SpringWEB1</groupId>
  <artifactId>SpringWEB1</artifactId>
  <version>1</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
  </dependencies>
</project>

Controller.java

package com.jmtm.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@org.springframework.stereotype.Controller
public class Controller {

    @RequestMapping("/hi")
    public ModelAndView hi(){
        return new ModelAndView("Hello", "msg", "Hello user.");
    }

}

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:c="http://www.springframework.org/schema/c"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util"
    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-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">

    <context:component-scan base-package="com.jmtm.controller"></context:component-scan>

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

</beans>

And the most important part of the solution, include the path of the servlet dispatcher (A.K.A. spring-servlet.xml) in the 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" 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>SpringWEB1</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

Something weird happen when I try to solve this. Any downloaded version of Spring from maven.springframework.org/release/org/springframework/spring gives me a lot of problems (Tomcat couldn't find servlet, Spring stops Tomcat, Eclipse couldn't start the server {weird}) so with many problems find many partial solutions. I hope this works for you.

As an extra help, in Eclipse, download from the Eclipse Marketplace the Spring STS Tool for Eclipse, this will help you to create configuration files (servlet.xml) and write code for the servlet in the web.xml file.

Error creating bean with name

It looks like your Spring component scan Base is missing UserServiceImpl

<context:component-scan base-package="org.assessme.com.controller." />

Powershell send-mailmessage - email to multiple recipients

to send a .NET / C# powershell eMail use such a structure:

for best behaviour create a class with a method like this

 using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddCommand("Send-MailMessage")
                                  .AddParameter("SMTPServer", "smtp.xxx.com")
                                  .AddParameter("From", "[email protected]")
                                  .AddParameter("Subject", "xxx Notification")
                                  .AddParameter("Body", body_msg)
                                  .AddParameter("BodyAsHtml")
                                  .AddParameter("To", recipients);

                // invoke execution on the pipeline (ignore output) --> nothing will be displayed
                PowerShellInstance.Invoke();
            }              

Whereby these instance is called in a function like:

        public void sendEMailPowerShell(string body_msg, string[] recipients)

Never forget to use a string array for the recepients, which can be look like this:

string[] reportRecipient = { 
                        "xxx <[email protected]>",
                        "xxx <[email protected]>"
                        };

body_msg

this message can be overgiven as parameter to the method itself, HTML coding enabled!!

recipients

never forget to use a string array in case of multiple recipients, otherwise only the last address in the string will be used!!!

calling the function can look like this:

        mail reportMail = new mail(); //instantiate from class
        reportMail.sendEMailPowerShell(reportMessage, reportRecipient); //msg + email addresses

ThumbUp

Requested bean is currently in creation: Is there an unresolvable circular reference?

I think you could use Spring's

@Lazy

annotation on one of the autowired fields to break circular dependency.

I'm not sure if this works/exists in mentioned Spring version.

Hibernate error - QuerySyntaxException: users is not mapped [from users]

In the HQL , you should use the java class name and property name of the mapped @Entity instead of the actual table name and column name , so the HQL should be :

List<User> result = session.createQuery("from User", User.class).getResultList();

Update : To be more precise , you should use the entity name configured in @Entity to refer to the "table" , which default to unqualified name of the mapped java class if you do not set it explicitly.

(P.S. It is @javax.persistence.Entity but not @org.hibernate.annotations.Entity)

How to force HTTPS using a web.config file

I am using below code and it perfect works for me, hope it will help you.

<configuration>
<system.webServer>
    <rewrite>
        <rules>
            <rule name="Force redirect to https" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="^OFF$" />
                </conditions>
                <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

In the endpoint tag you need to include the property address=""

<endpoint address="" binding="webHttpBinding" bindingConfiguration="SecureBasicRest" behaviorConfiguration="svcEndpoint" name="webHttp" contract="SvcContract.Authenticate" />

Xcode error - Thread 1: signal SIGABRT

SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

I was also facing the error "Error preloading the connection pool" while using Oracle 10g Express Edition with my Spring and CAS based application during login.

My CAS based application only has classes12.jar in its classpath, Placing ojdbc14.jar in the classpath has resolved my problem.

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

I solved the error by modifying the following property in hibernate.cfg.xml

  <property name="hibernate.hbm2ddl.auto">validate</property>

Earlier, the table was getting deleted each time I ran the program and now it doesnt, as hibernate only validates the schema and does not affect changes to it.

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

Instead of passing reference object passed the saved object, below is explanation which solve my issue:

//wrong
entityManager.persist(role);
user.setRole(role);
entityManager.persist(user)

//right
Role savedEntity= entityManager.persist(role);
user.setRole(savedEntity);
entityManager.persist(user)

No matching bean of type ... found for dependency

In my case it was the wrong dependecy for CrudRepository. My IDE added also follwing:

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-commons</artifactId>
        <version>1.11.2.RELEASE</version>
    </dependency>

But I just needed:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <version>RELEASE</version>
    </dependency>

I removed the first one and everything was fine.

Manually map column names with class properties

The simple solution to the problem Kaleb is trying to solve is just to accept the property name if the column attribute doesn't exist:

Dapper.SqlMapper.SetTypeMap(
    typeof(T),
    new Dapper.CustomPropertyTypeMap(
        typeof(T),
        (type, columnName) =>
            type.GetProperties().FirstOrDefault(prop =>
                prop.GetCustomAttributes(false)
                    .OfType<ColumnAttribute>()
                    .Any(attr => attr.Name == columnName) || prop.Name == columnName)));

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

Please do check Hibernate Property Name and Id Name also.

Using ResourceManager

This SO answer might help in this case.
If the main project already references the resource project, then you could just explicitly work with your generated-resource class in your code, and access its ResourceManager from that. Hence, something along the lines of:

ResourceManager resMan = YeagerTechResources.Resources.ResourceManager;

// then, you could go on working with that
ResourceSet resourceSet = resMan.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
// ...

CORS - How do 'preflight' an httprequest?

Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:

  • jQuery sent its XHR request using only limited headers; only 'Origin' was sent.
  • No preflight request was needed.
  • The server only had to detect such a request, and add the "Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN'] header, after detecting that this was a cross-origin XHR.

PHP Code sample:

if (!empty($_SERVER['HTTP_ORIGIN'])) {
    // Uh oh, this XHR comes from outer space...
    // Use this opportunity to filter out referers that shouldn't be allowed to see this request
    if (!preg_match('@\.partner\.domain\.net$@'))
        die("End of the road if you're not my business partner.");

    // otherwise oblige
    header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
    // local request, no need to send a specific header for CORS
}

In particular, don't add an exit; as no preflight is needed.

Is the buildSessionFactory() Configuration method deprecated in Hibernate

Yes, it is deprecated. http://docs.jboss.org/hibernate/core/4.0/javadocs/org/hibernate/cfg/Configuration.html#buildSessionFactory() specifically tells you to use the other method you found instead (buildSessionFactory(ServiceRegistry serviceRegistry)) - so use it.

The documentation is copied over from release to release, and likely just hasn't been updated yet (they don't rewrite the manual with every release) - so trust the Javadocs.

The specifics of this change can be viewed at:

Some additional references:

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

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

I encountered this error recently and after some brief investigation, found the cause to be that we were running out of space on the disk holding the database (less than 1GB).

As soon as I moved out the database files (.mdf and .ldf) to another disk on the same server (with lots more space), the same page (running the query) that had timed-out loaded within three seconds.

One other thing to investigate, while trying to resolve this error, is the size of the database log files. Your log files just might need to be shrunk.

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

Check the items in forEach

    <c:forEach items="${pools}" var="pool"> 

        ${pool.name}

    </c:forEach>

Some times items="${pools}" has an extra space or it acts like string, retyping it should solve the issue.

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

I was also getting the same error, the WCF was working properly for me when i was using it in the Dev Environment with my credentials, but when someone else was using it in TEST, it was throwing the same error. I did a lot of research, and then instead of doing config updates, handled an exception in the WCF method with the help of fault exception. Also the identity for the WCF needs to be set with the same credentials which are having access in the database, someone might have changed your authority. Please find below the code for the same:

 [ServiceContract]
public interface IService1
{
    [OperationContract]
    [FaultContract(typeof(ServiceData))]
    ForDataset GetCCDBdata();

    [OperationContract]
    [FaultContract(typeof(ServiceData))]
    string GetCCDBdataasXMLstring();


    //[OperationContract]
    //string GetData(int value);

    //[OperationContract]
    //CompositeType GetDataUsingDataContract(CompositeType composite);

    // TODO: Add your service operations here
}

  [DataContract]
public class ServiceData
{
    [DataMember]
    public bool Result { get; set; }
    [DataMember]
    public string ErrorMessage { get; set; }
    [DataMember]
    public string ErrorDetails { get; set; }
}

in your service1.svc.cs you can use this in the catch block:

 catch (Exception ex)
        {
            myServiceData.Result = false;
            myServiceData.ErrorMessage = "unforeseen error occured. Please try later.";
            myServiceData.ErrorDetails = ex.ToString();
            throw new FaultException<ServiceData>(myServiceData, ex.ToString());
        }

And use this in the Client application like below code:

  ConsoleApplicationWCFClient.CCDB_HIG_service.ForDataset ds = obj.GetCCDBdata();

            string str = obj.GetCCDBdataasXMLstring();

        }

        catch (FaultException<ConsoleApplicationWCFClient.CCDB_HIG_service.ServiceData> Fex)
      {
          Console.WriteLine("ErrorMessage::" + Fex.Detail.ErrorMessage + Environment.NewLine);
          Console.WriteLine("ErrorDetails::" + Environment.NewLine + Fex.Detail.ErrorDetails);
          Console.ReadLine();
      }

Just try this, it will help for sure to get the exact issue.

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

There is also another possible source of this error. In some J2EE / web containers (in my experience under Jboss 7.x and Tomcat 7.x) You have to add each class You want to use as a hibernate Entity into the file persistence.xml as

<class>com.yourCompanyName.WhateverEntityClass</class>

In case of jboss this concerns every entity class (local - i.e. within the project You are developing or in a library). In case of Tomcat 7.x this concerns only entity classes within libraries.

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

In C# and SQL SERVER, we can fix the error by adding Integrated Security = true to the connection string.

Please find the full connection string:

constr = @"Data Source=<Data-Source-Server-Name>;Initial Catalog=<DB-Name>;Integrated Security=true";

Creating a PHP header/footer

You can do it by using include_once() function in php. Construct a header part in the name of header.php and construct the footer part by footer.php. Finally include all the content in one file.

For example:

header.php

<html>
<title>
<link href="sample.css">

footer.php

</html>

So the final files look like

include_once("header.php") 

body content(The body content changes based on the file dynamically)

include_once("footer.php") 

Hibernate openSession() vs getCurrentSession()

+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Parameter            |                                openSession                                 |                                          getCurrentSession                                          |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session  creation    | Always open new session                                                    | It opens a new Session if not exists , else use same session which is in current hibernate context. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session close        | Need to close the session object once all the database operations are done | No need to close the session. Once the session factory is closed, this session object is closed.    |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Flush and close      | Need to explicity flush and close session objects                          | No need to flush and close sessions , since it is automatically taken by hibernate internally.      |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Performance          | In single threaded environment , it is slower than getCurrentSession       | In single threaded environment , it is faster than openSession                                      |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Configuration        | No need to configure any property to call this method                      | Need to configure additional property:                                                              |
|                      |                                                                            |  <property name=""hibernate.current_session_context_class"">thread</property>                       |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+

Create session factory in Hibernate 4

In earlier versions session factory was created as below:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be like:

Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());

Injection of autowired dependencies failed;

The error shows that com.bd.service.ArticleService is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:

<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>

Alternatively, if you want to include all subpackages in com.bd:

<context:component-scan base-package="com.bd">
     <context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>

As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration.

@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {

    @Autowired
    ArticleService articleService;
    ...
}

You might find this Spring in depth section on Autowiring useful.

Annotation @Transactional. How to rollback?

Just throw any RuntimeException from a method marked as @Transactional.

By default all RuntimeExceptions rollback transaction whereas checked exceptions don't. This is an EJB legacy. You can configure this by using rollbackFor() and noRollbackFor() annotation parameters:

@Transactional(rollbackFor=Exception.class)

This will rollback transaction after throwing any exception.

Login failed for user 'IIS APPPOOL\ASP.NET v4.0'

You can change the ApplicationPoolIdentity from IIS7 -> Application Pools -> Advanced Settings. AdvancedSettings

Under ApplicationPoolIdentity you will find local system. This will make your application run under NT AUTHORITY\SYSTEM, which is an existing login for the database by default.

Edit: Before applying this suggestion you should note and understand the security implications.

C# Example of AES256 encryption using System.Security.Cryptography.Aes

public class AesCryptoService
{
    private static byte[] Key = Encoding.ASCII.GetBytes(@"qwr{@^h`h&_`50/ja9!'dcmh3!uw<&=?");
    private static byte[] IV = Encoding.ASCII.GetBytes(@"9/\~V).A,lY&=t2b");


    public static string EncryptStringToBytes_Aes(string plainText)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        byte[] encrypted;


        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        
        return Convert.ToBase64String(encrypted);
    }


    
    public static string DecryptStringFromBytes_Aes(string Text)
    {
        if (Text == null || Text.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        string plaintext = null;
        byte[] cipherText = Convert.FromBase64String(Text.Replace(' ', '+'));

        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            aesAlg.Padding = PaddingMode.PKCS7;


            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;
    }
}

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

My personal opinion: Go for Swing together with the NetBeans platform.

If you need advanced components (more than NetBeans offers) you can easily integrate SwingX without problems (or JGoodies) as the NetBeans platform is completely based on Swing.

I would not start a large desktop application (or one that is going to be large) without a good platform that is build upon the underlying UI framework.

The other option is SWT together with the Eclipse RCP, but it's harder (though not impossible) to integrate "pure" Swing components into such an application.

The learning curve is a bit steep for the NetBeans platform (although I guess that's true for Eclipse as well) but there are some good books around which I would highly recommend.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

you need to add jar file in your build path..

commons-dbcp-1.1-RC2.jar

or any version of that..!!!!

ADDED : also make sure you have commons-pool-1.1.jar too in your build path.

ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.

inject bean reference into a Quartz job in Spring?

Same problem has been resolved in LINK:

I could found other option from post on the Spring forum that you can pass a reference to the Spring application context via the SchedulerFactoryBean. Like the example shown below:

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<propertyy name="triggers">
    <list>
        <ref bean="simpleTrigger"/>
            </list>
    </property>
    <property name="applicationContextSchedulerContextKey">
        <value>applicationContext</value>
</property>

Then using below code in your job class you can get the applicationContext and get whatever bean you want.

appCtx = (ApplicationContext)context.getScheduler().getContext().get("applicationContextSchedulerContextKey");

Hope it helps. You can get more information from Mark Mclaren'sBlog

javax.mail.AuthenticationFailedException: failed to connect, no password specified?

First of all, enable the less secure app in your Gmail account from which you will send emails using this link:- https://myaccount.google.com/lesssecureapps?pli=1

Then you simply add the following code in your session creation. It will work fine then.

Session mailSession = Session.getInstance(props, new javax.mail.Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "your_email", "your_password");// Specify the Username and the PassWord
            }
        });

if you want the more elaborated one use the following:-

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailSender {

    public Properties mailProperties() {
        Properties props = new Properties();

        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.user", "your_email");
        props.setProperty("mail.smtp.password", "your_password");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.auth", "true");

        return props;
    }

    public String sendMail(String from, String to, String subject, String msgBody) {
        Properties props = mailProperties();
        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "your_email", "your_password");// Specify the Username and the PassWord
            }
        });

        mailSession.setDebug(false);

        try {
            Transport transport = mailSession.getTransport();

            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject);
            message.setFrom(new InternetAddress(from));
            message.addRecipients(Message.RecipientType.TO, to);

            MimeMultipart multipart = new MimeMultipart();

            MimeBodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setContent(msgBody, "text/html");

            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);

            transport.connect();
            transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
            transport.close();
            return "SUCCESS";
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            return "INVALID_EMAIL";
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return "ERROR";
    }

    public static void main(String args[]) {
        System.out.println(new MailSender().sendMail("your_email/from_email", "to_email", "Subject", "Message"));
    }
}

Hope! it helps. Thanks!

Get connection string from App.config

I referenced System.Configuration library and I have the same error. The debug files had not their app.config, create manually this file. The error is, I solved this copying the file "appname.exe.config" in debug folder. The IDE was not create the file.

not-null property references a null or transient value

Every InvoiceItem must have an Invoice attached to it because of the not-null="true" in the many-to-one mapping.

So the basic idea is you need to set up that explicit relationship in code. There are many ways to do that. On your class I see a setItems method. I do NOT see an addInvoiceItem method. When you set items, you need to loop through the set and call item.setInvoice(this) on all of the items. If you implement an addItem method, you need to do the same thing. Or you need to otherwise set the Invoice of every InvoiceItem in the collection.

org.hibernate.PersistentObjectException: detached entity passed to persist

Two solutions 1. use merge if you want to update the object 2. use save if you want to just save new object (make sure identity is null to let hibernate or database generate it) 3. if you are using mapping like
@OneToOne(fetch = FetchType.EAGER,cascade=CascadeType.ALL) @JoinColumn(name = "stock_id")

Then use CascadeType.ALL to CascadeType.MERGE

thanks Shahid Abbasi

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

For me the thing that worked was the order in which the namespaces were defined in the xsi:schemaLocation tag : [ since the version was all good and also it was transaction-manager already ]

The error was with :

 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"

AND RESOLVED WITH :

http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"

Parsing JSON in Spring MVC using Jackson JSON

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","[email protected]");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

How to check if a file exists from inside a batch file

C:\>help if

Performs conditional processing in batch programs.

IF [NOT] ERRORLEVEL number command

IF [NOT] string1==string2 command

IF [NOT] EXIST filename command

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

You are using POST method, but are you providing an array of data? E.g.

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Selenium WebDriver and DropDown Boxes

You can use this

(new SelectElement(driver.FindElement(By.Id(""))).SelectByText("");

Accessing an SQLite Database in Swift

Sometimes, a Swift version of the "SQLite in 5 minutes or less" approach shown on sqlite.org is sufficient. The "5 minutes or less" approach uses sqlite3_exec() which is a convenience wrapper for sqlite3_prepare(), sqlite3_step(), sqlite3_column(), and sqlite3_finalize().

Swift 2.2 can directly support the sqlite3_exec() callback function pointer as either a global, non-instance procedure func or a non-capturing literal closure {}.

Readable typealias

typealias sqlite3 = COpaquePointer
typealias CCharHandle = UnsafeMutablePointer<UnsafeMutablePointer<CChar>>
typealias CCharPointer = UnsafeMutablePointer<CChar>
typealias CVoidPointer = UnsafeMutablePointer<Void>

Callback Approach

func callback(
    resultVoidPointer: CVoidPointer, // void *NotUsed 
    columnCount: CInt,               // int argc
    values: CCharHandle,             // char **argv     
    columns: CCharHandle             // char **azColName
    ) -> CInt {
    for  i in 0 ..< Int(columnCount) {
        guard let value = String.fromCString(values[i]) 
        else { continue }
        guard let column = String.fromCString(columns[i]) 
        else { continue }
        print("\(column) = \(value)")
    }
    return 0 // status ok
}

func sqlQueryCallbackBasic(argc: Int, argv: [String]) -> Int {
    var db: sqlite3 = nil 
    var zErrMsg:CCharPointer = nil
    var rc: Int32 = 0 // result code

    if argc != 3 {
        print(String(format: "ERROR: Usage: %s DATABASE SQL-STATEMENT", argv[0]))
        return 1
    }

    rc = sqlite3_open(argv[1], &db)
    if  rc != 0 {
        print("ERROR: sqlite3_open " + String.fromCString(sqlite3_errmsg(db))! ?? "" )
        sqlite3_close(db)
        return 1
    }

    rc = sqlite3_exec(db, argv[2], callback, nil, &zErrMsg)
    if rc != SQLITE_OK {
        print("ERROR: sqlite3_exec " + String.fromCString(zErrMsg)! ?? "")
        sqlite3_free(zErrMsg)
    }

    sqlite3_close(db)
    return 0
}

Closure Approach

func sqlQueryClosureBasic(argc argc: Int, argv: [String]) -> Int {
    var db: sqlite3 = nil 
    var zErrMsg:CCharPointer = nil
    var rc: Int32 = 0

    if argc != 3 {
        print(String(format: "ERROR: Usage: %s DATABASE SQL-STATEMENT", argv[0]))
        return 1
    }

    rc = sqlite3_open(argv[1], &db)
    if  rc != 0 {
        print("ERROR: sqlite3_open " + String.fromCString(sqlite3_errmsg(db))! ?? "" )
        sqlite3_close(db)
        return 1
    }

    rc = sqlite3_exec(
        db,      // database 
        argv[2], // statement
        {        // callback: non-capturing closure
            resultVoidPointer, columnCount, values, columns in

            for i in 0 ..< Int(columnCount) {
                guard let value = String.fromCString(values[i]) 
                else { continue }
                guard let column = String.fromCString(columns[i]) 
                else { continue }
                print("\(column) = \(value)")
            }
            return 0
        }, 
        nil, 
        &zErrMsg
    )

    if rc != SQLITE_OK {
        let errorMsg = String.fromCString(zErrMsg)! ?? ""
        print("ERROR: sqlite3_exec \(errorMsg)")
        sqlite3_free(zErrMsg)
    }
    sqlite3_close(db)
    return 0
}

To prepare an Xcode project to call a C library such as SQLite, one needs to (1) add a Bridging-Header.h file reference C headers like #import "sqlite3.h", (2) add Bridging-Header.h to Objective-C Bridging Header in project settings, and (3) add libsqlite3.tbd to Link Binary With Library target settings.

The sqlite.org's "SQLite in 5 minutes or less" example is implemented in a Swift Xcode7 project here.

C++ Structure Initialization

It is possible, but only if the struct you're initializing is a POD (plain old data) struct. It cannot contain any methods, constructors, or even default values.

MySQL: What's the difference between float and double?

They both represent floating point numbers. A FLOAT is for single-precision, while a DOUBLE is for double-precision numbers.

MySQL uses four bytes for single-precision values and eight bytes for double-precision values.

There is a big difference from floating point numbers and decimal (numeric) numbers, which you can use with the DECIMAL data type. This is used to store exact numeric data values, unlike floating point numbers, where it is important to preserve exact precision, for example with monetary data.

Python extending with - using super() Python 3 vs Python 2

In a single inheritance case (when you subclass one class only), your new class inherits methods of the base class. This includes __init__. So if you don't define it in your class, you will get the one from the base.

Things start being complicated if you introduce multiple inheritance (subclassing more than one class at a time). This is because if more than one base class has __init__, your class will inherit the first one only.

In such cases, you should really use super if you can, I'll explain why. But not always you can. The problem is that all your base classes must also use it (and their base classes as well -- the whole tree).

If that is the case, then this will also work correctly (in Python 3 but you could rework it into Python 2 -- it also has super):

class A:
    def __init__(self):
        print('A')
        super().__init__()

class B:
    def __init__(self):
        print('B')
        super().__init__()

class C(A, B):
    pass

C()
#prints:
#A
#B

Notice how both base classes use super even though they don't have their own base classes.

What super does is: it calls the method from the next class in MRO (method resolution order). The MRO for C is: (C, A, B, object). You can print C.__mro__ to see it.

So, C inherits __init__ from A and super in A.__init__ calls B.__init__ (B follows A in MRO).

So by doing nothing in C, you end up calling both, which is what you want.

Now if you were not using super, you would end up inheriting A.__init__ (as before) but this time there's nothing that would call B.__init__ for you.

class A:
    def __init__(self):
        print('A')

class B:
    def __init__(self):
        print('B')

class C(A, B):
    pass

C()
#prints:
#A

To fix that you have to define C.__init__:

class C(A, B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)

The problem with that is that in more complicated MI trees, __init__ methods of some classes may end up being called more than once whereas super/MRO guarantee that they're called just once.

Run a mySQL query as a cron job?

I personally find it easier use MySQL event scheduler than cron.

Enable it with

SET GLOBAL event_scheduler = ON;

and create an event like this:

CREATE EVENT name_of_event
ON SCHEDULE EVERY 1 DAY
STARTS '2014-01-18 00:00:00'
DO
DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) ,  timestamp ) >=7;

and that's it.

Read more about the syntax here and here is more general information about it.

Android - Back button in the title bar

I have finally managed to properly add back button to actionbar/toolbar

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}  

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
    }

    return super.onOptionsItemSelected(item);
}

public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}

Removing a model in rails (reverse of "rails g model Title...")

  1. To remove migration (if you already migrated the migration)

    rake db:migrate:down VERSION="20130417185845" #Your migration version
    
  2. To remove Model

    rails d model name  #name => Your model name
    

jQuery set radio button

In my case, radio button value is fetched from database and then set into the form. Following code works for me.

$("input[name=name_of_radio_button_fields][value=" + saved_value_comes_from_database + "]").prop('checked', true);

How do I add a tool tip to a span element?

Here's the simple, built-in way:

<span title="My tip">text</span>

That gives you plain text tooltips. If you want rich tooltips, with formatted HTML in them, you'll need to use a library to do that. Fortunately there are loads of those.

Visual Studio 2012 Web Publish doesn't copy files

First:

  • Build in release Configuration.
  • In Project Properties-> page select All files and folders under Package/Publish Web.
  • Rebuild solution (after Clean solution).
  • now publish.

While publishing recheck what u have opted.
this should do it. It did for me!:)

What is http multipart request?

I have found an excellent and relatively short explanation here.

A multipart request is a REST request containing several packed REST requests inside its entity.

Jquery find nearest matching element

var otherInput = $(this).closest('.row').find('.inputQty');

That goes up to a row level, then back down to .inputQty.

How can I make Bootstrap 4 columns all the same height?

Equal height columns is the default behaviour for Bootstrap 4 grids.

_x000D_
_x000D_
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
      <br>_x000D_
      Line 2_x000D_
      <br>_x000D_
      Line 3_x000D_
    </div>_x000D_
    <div class="col">_x000D_
      1 of 3_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ImportError: No module named 'Tkinter'

You might need to install for your specific version, I have known cases where this was needed when I was using many versions of python and one version in a virtualenv using for example python 3.7 was not importing tkinter I would have to install it for that version specifically.

For example

sudo apt-get install python3.7-tk 

No idea why - but this has occured.

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

I was having a very similar problem. I was getting inconsistent height() values when I refreshed my page. (It wasn't my variable causing the problem, it was the actual height value.)

I noticed that in the head of my page I called my scripts first, then my css file. I switched so that the css file is linked first, then the script files and that seems to have fixed the problem so far.

Hope that helps.

pass array to method Java

public static void main(String[] args) {

    int[] A=new int[size];
      //code for take input in array
      int[] C=sorting(A); //pass array via method
      //and then print array

    }
public static int[] sorting(int[] a) {
     //code for work with array 
     return a; //retuen array
}

XSLT equivalent for JSON

it is very possible to convert JSON using XSLT: you need JSON2SAX deserializer and SAX2JSON serializer.

Sample code in Java: http://www.gerixsoft.com/blog/json/xslt4json

Meaning of Open hashing and Closed hashing

The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).

In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.

This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)

How to create text file and insert data to that file on Android

First create a Project With PdfCreation in Android Studio

Then Follow below steps:

1.Download itextpdf-5.3.2.jar library from this link [https://sourceforge.net/projects/itext/files/iText/iText5.3.2/][1] and then
2.Add to app>libs>itextpdf-5.3.2.jar
3.Right click on jar file then click on add to library
4. Document document = new Document(PageSize.A4); // Create Directory in External Storage
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/PDF");
        System.out.print(myDir.toString());
        myDir.mkdirs(); // Create Pdf Writer for Writting into New Created Document
        try {
            PdfWriter.getInstance(document, new FileOutputStream(FILE));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } // Open Document for Writting into document
        document.open(); // User Define Method
        addMetaData(document);
        try {
            addTitlePage(document);
        } catch (DocumentException e) {
            e.printStackTrace();
        } // Close Document after writting all content
        document.close();

5.   public void addMetaData(Document document)
    {
        document.addTitle("RESUME");
        document.addSubject("Person Info");
        document.addKeywords("Personal, Education, Skills");
                document.addAuthor("TAG");
        document.addCreator("TAG");
    }
    public void addTitlePage(Document document) throws DocumentException
    { // Font Style for Document
        Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
        Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
                | Font.UNDERLINE, BaseColor.GRAY);
        Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
        Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); // Start New Paragraph
        Paragraph prHead = new Paragraph(); // Set Font in this Paragraph
        prHead.setFont(titleFont); // Add item into Paragraph
        prHead.add("RESUME – Name\n"); // Create Table into Document with 1 Row
        PdfPTable myTable = new PdfPTable(1); // 100.0f mean width of table is same as Document size
        myTable.setWidthPercentage(100.0f); // Create New Cell into Table
        PdfPCell myCell = new PdfPCell(new Paragraph(""));
        myCell.setBorder(Rectangle.BOTTOM); // Add Cell into Table
        myTable.addCell(myCell);
        prHead.setFont(catFont);
        prHead.add("\nName1 Name2\n");
        prHead.setAlignment(Element.ALIGN_CENTER); // Add all above details into Document
        document.add(prHead);
        document.add(myTable);
        document.add(myTable); // Now Start another New Paragraph
        Paragraph prPersinalInfo = new Paragraph();
        prPersinalInfo.setFont(smallBold);
        prPersinalInfo.add("Address 1\n");
        prPersinalInfo.add("Address 2\n");
        prPersinalInfo.add("City: SanFran. State: CA\n");
        prPersinalInfo.add("Country: USA Zip Code: 000001\n");
        prPersinalInfo.add("Mobile: 9999999999 Fax: 1111111 Email: [email protected] \n");
        prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
        document.add(prPersinalInfo);
        document.add(myTable);
        document.add(myTable);
        Paragraph prProfile = new Paragraph();
        prProfile.setFont(smallBold);
        prProfile.add("\n \n Profile : \n ");
        prProfile.setFont(normal);
        prProfile.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
        prProfile.setFont(smallBold);
        document.add(prProfile); // Create new Page in PDF
        document.newPage();
    }

python-dev installation error: ImportError: No module named apt_pkg

Make sure you have a working python-apt package. You could try and remove and install that package again to fix the problem with apt_pkg.so not being located.

apt-get install python-apt

JavaScript: function returning an object

The latest way to do this with ES2016 JavaScript

let makeGamePlayer = (name, totalScore, gamesPlayed) => ({
    name,
    totalScore,
    gamesPlayed
})

Soft Edges using CSS?

It depends on what type of fading you are looking for.

But with shadow and rounded corners you can get a nice result. Rounded corners because the bigger the shadow, the weirder it will look in the edges unless you balance it out with rounded corners.

http://jsfiddle.net/tLu7u/

also.. http://css3pie.com/

vertical-align image in div

If you have a fixed height in your container, you can set line-height to be the same as height, and it will center vertically. Then just add text-align to center horizontally.

Here's an example: http://jsfiddle.net/Cthulhu/QHEnL/1/

EDIT

Your code should look like this:

.img_thumb {
    float: left;
    height: 120px;
    margin-bottom: 5px;
    margin-left: 9px;
    position: relative;
    width: 147px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 3px;
    line-height:120px;
    text-align:center;
}

.img_thumb img {
    vertical-align: middle;
}

The images will always be centered horizontally and vertically, no matter what their size is. Here's 2 more examples with images with different dimensions:

http://jsfiddle.net/Cthulhu/QHEnL/6/

http://jsfiddle.net/Cthulhu/QHEnL/7/

UPDATE

It's now 2016 (the future!) and looks like a few things are changing (finally!!).

Back in 2014, Microsoft announced that it will stop supporting IE8 in all versions of Windows and will encourage all users to update to IE11 or Edge. Well, this is supposed to happen next Tuesday (12th January).

Why does this matter? With the announced death of IE8, we can finally start using CSS3 magic.

With that being said, here's an updated way of aligning elements, both horizontally and vertically:

.container {
    position: relative;
}

.container .element {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

Using this transform: translate(); method, you don't even need to have a fixed height in your container, it's fully dynamic. Your element has fixed height or width? Your container as well? No? It doesn't matter, it will always be centered because all centering properties are fixed on the child, it's independent from the parent. Thank you CSS3.

If you only need to center in one dimension, you can use translateY or translateX. Just try it for a while and you'll see how it works. Also, try to change the values of the translate, you will find it useful for a bunch of different situations.

Here, have a new fiddle: https://jsfiddle.net/Cthulhu/1xjbhsr4/

For more information on transform, here's a good resource.

Happy coding.

Interfaces — What's the point?

Interfaces are used to drive consistency,in a manner that is loosely coupled which makes it different to abstract class which is tightly coupled.That's why its also commonly defined as a contract.Whichever classes that implements the interface has abide to "rules/syntax" defined by the interface and there is no concrete elements within it.

I'll just give an example supported by the graphic below.

Imagine in a factory there are 3 types of machines.A rectangle machine,a triangle machine and a polygon machine.Times are competitive and you want to streamline operator training.You just want to train them in one methodology of starting and stopping machines so you have a green start button and red stop button.So now across 3 different machines you have a consistent way of starting and stopping 3 different types of machines.Now imagine these machines are classes and the classes need to have start and stop methods,how you going to drive consistency across these classes which can be very different? Interface is the answer.

enter image description here

A simple example to help you visualize,one might ask why not use abstract class? With an interface the objects don't have to be directly related or inherited and you can still drive consistency across different classes.

public interface IMachine
{
    bool Start();
    bool Stop();
}

public class Car : IMachine
{
    public bool Start()
    {
        Console.WriteLine("Car started");
        return true;
    }

    public bool Stop()
    {
        Console.WriteLine("Car stopped");
        return false;
    }
}

public class Tank : IMachine
{
    public bool Start()
    {
        Console.WriteLine("Tank started");
        return true;
    }

    public bool Stop()
    {
        Console.WriteLine("Tank stopped");
        return false;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var car = new Car();
        car.Start();
        car.Stop();

        var tank = new Tank();
        tank.Start();
        tank.Stop();

    }
}

What is pluginManagement in Maven's pom.xml?

The difference between <pluginManagement/> and <plugins/> is that a <plugin/> under:

  • <pluginManagement/> defines the settings for plugins that will be inherited by modules in your build. This is great for cases where you have a parent pom file.

  • <plugins/> is a section for the actual invocation of the plugins. It may or may not be inherited from a <pluginManagement/>.

You don't need to have a <pluginManagement/> in your project, if it's not a parent POM. However, if it's a parent pom, then in the child's pom, you need to have a declaration like:

<plugins>
    <plugin>
        <groupId>com.foo</groupId>
        <artifactId>bar-plugin</artifactId>
    </plugin>
</plugins>

Notice how you aren't defining any configuration. You can inherit it from the parent, unless you need to further adjust your invocation as per the child project's needs.

For more specific information, you can check:

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

Div Background Image Z-Index Issue

To solve the issue, you are using the z-index on the footer and header, but you forgot about the position, if a z-index is to be used, the element must have a position:

Add to your footer and header this CSS:

position: relative; 

EDITED:

Also noticed that the background image on the #backstretch has a negative z-index, don't use that, some browsers get really weird...

Remove From the #backstretch:

z-index: -999999;

Read a little bit about Z-Index here!

How to get ER model of database from server with Workbench

I want to enhance Mr. Kamran Ali's answer with pictorial view.

Pictorial View is given step by step:

  1. Go to "Database" Menu option
  2. Select the "Reverse Engineer" option.

enter image description here

  1. A wizard will come. Select from "Stored Connection" and press "Next" button.

enter image description here

  1. Then "Next"..to.."Finish"

Enjoy :)

Copy every nth line from one sheet to another

In A1 of your new sheet, put this:

=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0)

... and copy down. If you start somewhere other than row 1, change ROW() to ROW(A1) or some other cell on row 1, then copy down again.

If you want to copy the nth line but multiple columns, use the formula:

=OFFSET(Sheet1!A$1,(ROW()-1)*7,0)

This can be copied right too.

Redirecting to URL in Flask

flask.redirect(location, code=302)

Docs can be found here.

setting request headers in selenium

You can do it with PhantomJSDriver.

PhantomJSDriver pd = ((PhantomJSDriver) ((WebDriverFacade) getDriver()).getProxiedDriver());
pd.executePhantomJS(
            "this.onResourceRequested = function(request, net) {" +
            "   net.setHeader('header-name', 'header-value')" +
            "};");

Using the request object, you can filter also so the header won't be set for every request.

How to animate RecyclerView items when they appear

In 2019, I would suggest putting all the item animations into the ItemAnimator.

Let's start with declaring the animator in the recycler-view:

with(view.recycler_view) {
adapter = Adapter()
itemAnimator = CustomAnimator()
}

Declare the custom animator then,

class CustomAnimator() : DefaultItemAnimator() {

     override fun animateAppearance(
       holder: RecyclerView.ViewHolder,
       preInfo: ItemHolderInfo?,
       postInfo: ItemHolderInfo): Boolean{} // declare  what happens when a item appears on the recycler view

     override fun animatePersistence(
       holder: RecyclerView.ViewHolder,
       preInfo: ItemHolderInfo,
       postInfo: ItemHolderInfo): Boolean {} // declare animation for items that persist in a recycler view even when the items change

}

Similar to the ones above there is one for disappearance animateDisappearance, for add animateAdd, for change animateChange and move animateMove.

One important point would be to call the correct animation-dispatchers inside them.

Using grep to search for hex strings in a file

grep has a -P switch allowing to use perl regexp syntax the perl regex allows to look at bytes, using \x.. syntax.

so you can look for a given hex string in a file with: grep -aP "\xdf"

but the outpt won't be very useful; indeed better do a regexp on the hexdump output;

The grep -P can be useful however to just find files matrching a given binary pattern. Or to do a binary query of a pattern that actually happens in text (see for example How to regexp CJK ideographs (in utf-8) )

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

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

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

Differences between Hashtable and Dictionary

Dictionary:

  • Dictionary returns error if we try to find a key which does not exist.
  • Dictionary faster than a Hashtable because there is no boxing and unboxing.
  • Dictionary is a generic type which means we can use it with any data type.

Hashtable:

  • Hashtable returns null if we try to find a key which does not exist.
  • Hashtable slower than dictionary because it requires boxing and unboxing.
  • Hashtable is not a generic type,

sqlite copy data from one table to another

I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:

create table destination_old as select * from destination;

drop table destination;

create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;

It's safe because you have a copy of destination before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.

Using the pattern above you end up with two country fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old and perhaps using coalesce to retrieve the values from destination_old if the country field in source is null. So for example:

create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

How to have a a razor action link open in a new tab?

If your goal is to use the ActionLink helper and open a new tab:

@Html.ActionLink("New tab please", "Home", null , new { target = "_blank" })

@Html.ActionLink("New tab please", "Home", Nothing, New With {Key .target = "_blank"})

What is the difference between a static and const variable?

Static variables in the context of a class are shared between all instances of a class.

In a function, it remains a persistent variable, so you could for instance count the number of times a function has been called.

When used outside of a function or class, it ensures the variable can only be used by code in that specific file, and nowhere else.

Constant variables however are prevented from changing. A common use of const and static together is within a class definition to provide some sort of constant.

class myClass {
public:
     static const int TOTAL_NUMBER = 5;
     // some public stuff
private:
     // some stuff
};

Cannot catch toolbar home button click event

I have handled back and Home button in Navigation Drawer like

public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private ActionBarDrawerToggle drawerToggle;
    private DrawerLayout drawerLayout;
    NavigationView navigationView;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_home);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        resetActionBar();

        navigationView = (NavigationView) findViewById(R.id.navigation_view);
        navigationView.setNavigationItemSelectedListener(this);

        //showing first fragment on Start
        getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).replace(R.id.content_fragment, new FirstFragment()).commit();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //listener for home
        if(id==android.R.id.home)
        {  
            if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                onBackPressed();
            else
                drawerLayout.openDrawer(navigationView);
            return  true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
       if (drawerLayout.isDrawerOpen(GravityCompat.START)) 
            drawerLayout.closeDrawer(GravityCompat.START);
       else 
            super.onBackPressed();
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Begin the transaction

        Fragment fragment = null;
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (id == R.id.nav_companies_list) {
            fragment = new FirstFragment();
            // Handle the action
        } 


        // Begin the transaction
        if(fragment!=null){

            if(item.isChecked()){
                if(getSupportFragmentManager().getBackStackEntryCount()==0){
                    drawer.closeDrawers();
            }else{
                    removeAllFragments();
                    getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
                    drawer.closeDrawer(GravityCompat.START);
                }

            }else{
                removeAllFragments();
                getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
                drawer.closeDrawer(GravityCompat.START);
            }
        }

        return true;
    }

    public void removeAllFragments(){
        getSupportFragmentManager().popBackStackImmediate(null,
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    public void replaceFragment(final Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .replace(R.id.WikiCompany, fragment).addToBackStack("")
                .commit();
    }


    public void updateDrawerIcon() {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
                    if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                        drawerToggle.setDrawerIndicatorEnabled(false);
                    else
                        drawerToggle.setDrawerIndicatorEnabled(true);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }, 50);
    }

    public void resetActionBar()
    {
        //display home
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    public void setActionBarTitle(String title) {
        getSupportActionBar().setTitle(title);
    }
}

and In each onViewCreated I call

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ((HomeActivity)getActivity()).updateDrawerIcon();
    ((HomeActivity) getActivity()).setActionBarTitle("List");
}

Normalization in DOM parsing with java - how does it work?

As an extension to @JBNizet's answer for more technical users here's what implementation of org.w3c.dom.Node interface in com.sun.org.apache.xerces.internal.dom.ParentNode looks like, gives you the idea how it actually works.

public void normalize() {
    // No need to normalize if already normalized.
    if (isNormalized()) {
        return;
    }
    if (needsSyncChildren()) {
        synchronizeChildren();
    }
    ChildNode kid;
    for (kid = firstChild; kid != null; kid = kid.nextSibling) {
         kid.normalize();
    }
    isNormalized(true);
}

It traverses all the nodes recursively and calls kid.normalize()
This mechanism is overridden in org.apache.xerces.dom.ElementImpl

public void normalize() {
     // No need to normalize if already normalized.
     if (isNormalized()) {
         return;
     }
     if (needsSyncChildren()) {
         synchronizeChildren();
     }
     ChildNode kid, next;
     for (kid = firstChild; kid != null; kid = next) {
         next = kid.nextSibling;

         // If kid is a text node, we need to check for one of two
         // conditions:
         //   1) There is an adjacent text node
         //   2) There is no adjacent text node, but kid is
         //      an empty text node.
         if ( kid.getNodeType() == Node.TEXT_NODE )
         {
             // If an adjacent text node, merge it with kid
             if ( next!=null && next.getNodeType() == Node.TEXT_NODE )
             {
                 ((Text)kid).appendData(next.getNodeValue());
                 removeChild( next );
                 next = kid; // Don't advance; there might be another.
             }
             else
             {
                 // If kid is empty, remove it
                 if ( kid.getNodeValue() == null || kid.getNodeValue().length() == 0 ) {
                     removeChild( kid );
                 }
             }
         }

         // Otherwise it might be an Element, which is handled recursively
         else if (kid.getNodeType() == Node.ELEMENT_NODE) {
             kid.normalize();
         }
     }

     // We must also normalize all of the attributes
     if ( attributes!=null )
     {
         for( int i=0; i<attributes.getLength(); ++i )
         {
             Node attr = attributes.item(i);
             attr.normalize();
         }
     }

    // changed() will have occurred when the removeChild() was done,
    // so does not have to be reissued.

     isNormalized(true);
 } 

Hope this saves you some time.

Android getResources().getDrawable() deprecated API 22

Just an example of how I fixed the problem in an array to load a listView, hope it helps.

 mItems = new ArrayList<ListViewItem>();
//    Resources resources = getResources();

//    mItems.add(new ListViewItem(resources.getDrawable(R.drawable.az_lgo), getString(R.string.st_az), getString(R.string.all_nums)));
//    mItems.add(new ListViewItem(resources.getDrawable(R.drawable.ca_lgo), getString(R.string.st_ca), getString(R.string.all_nums)));
//    mItems.add(new ListViewItem(resources.getDrawable(R.drawable.co_lgo), getString(R.string.st_co), getString(R.string.all_nums)));
    mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.az_lgo, null), getString(R.string.st_az), getString(R.string.all_nums)));
    mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.ca_lgo, null), getString(R.string.st_ca), getString(R.string.all_nums)));
    mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.co_lgo, null), getString(R.string.st_co), getString(R.string.all_nums)));

How to get the system uptime in Windows?

Following are eight ways to find the Uptime in Windows OS.

1: By using the Task Manager

In Windows Vista and Windows Server 2008, the Task Manager has been beefed up to show additional information about the system. One of these pieces of info is the server’s running time.

  1. Right-click on the Taskbar, and click Task Manager. You can also click CTRL+SHIFT+ESC to get to the Task Manager.
  2. In Task Manager, select the Performance tab.
  3. The current system uptime is shown under System or Performance ⇒ CPU for Win 8/10.

    "Up Time" field in Task Manager

2: By using the System Information Utility

The systeminfo command line utility checks and displays various system statistics such as installation date, installed hotfixes and more. Open a Command Prompt and type the following command:

systeminfo

You can also narrow down the results to just the line you need:

systeminfo | find "System Boot Time:"

enter image description here

3: By using the Uptime Utility

Microsoft have published a tool called Uptime.exe. It is a simple command line tool that analyses the computer's reliability and availability information. It can work locally or remotely. In its simple form, the tool will display the current system uptime. An advanced option allows you to access more detailed information such as shutdown, reboots, operating system crashes, and Service Pack installation.

Read the following KB for more info and for the download links:

To use it, follow these steps:

  1. Download uptime.exe from the above link, and save it to a folder, preferably in one that's in the system's path (such as SYSTEM32).
  2. Open an elevated Command Prompt window. To open an elevated Command Prompt, click Start, click All Programs, click Accessories, right-click Command Prompt, and then click Run as administrator. You can also type CMD in the search box of the Start menu, and when you see the Command Prompt icon click on it to select it, hold CTRL+SHIFT and press ENTER.
  3. Navigate to where you've placed the uptime.exe utility.
  4. Run the uptime.exe utility. You can add a /? to the command in order to get more options. enter image description here

It does not offer many command line parameters:

C:\uptimefromcodeplex\> uptime /?
usage: Uptime [-V]
    -V   display version

C:\uptimefromcodeplex\> uptime -V
version 1.1.0

3.1: By using the old Uptime Utility

There is an older version of the "uptime.exe" utility. This has the advantage of NOT needing .NET. (It also has a lot more features beyond simple uptime.)

Download link: Windows NT 4.0 Server Uptime Tool (uptime.exe) (final x86)

C:\uptimev100download>uptime.exe /?

UPTIME, Version 1.00
(C) Copyright 1999, Microsoft Corporation

Uptime [server] [/s ] [/a] [/d:mm/dd/yyyy | /p:n] [/heartbeat] [/? | /help]
        server          Name or IP address of remote server to process.
        /s              Display key system events and statistics.
        /a              Display application failure events (assumes /s).
        /d:             Only calculate for events after mm/dd/yyyy.
        /p:             Only calculate for events in the previous n days.
        /heartbeat      Turn on/off the system's heartbeat
        /?              Basic usage.
        /help           Additional usage information.

4: By using the NET STATISTICS Utility

Another easy method, if you can remember it, is to use the approximate information found in the statistics displayed by the NET STATISTICS command. Open a Command Prompt and type the following command:

net statistics workstation

The statistics should tell you how long it’s been running, although in some cases this information is not as accurate as other methods.

enter image description here

5: By Using the Event Viewer

Probably the most accurate of them all, but it does require some clicking. It does not display an exact day or hour count since the last reboot, but it will display important information regarding why the computer was rebooted and when it did so. We need to look at Event ID 6005, which is an event that tells us that the computer has just finished booting, but you should be aware of the fact that there are virtually hundreds if not thousands of other event types that you could potentially learn from.

Note: BTW, the 6006 Event ID is what tells us when the server has gone down, so if there’s much time difference between the 6006 and 6005 events, the server was down for a long time.

Note: You can also open the Event Viewer by typing eventvwr.msc in the Run command, and you might as well use the shortcut found in the Administrative tools folder.

  1. Click on Event Viewer (Local) in the left navigation pane.
  2. In the middle pane, click on the Information event type, and scroll down till you see Event ID 6005. Double-click the 6005 Event ID, or right-click it and select View All Instances of This Event.
  3. A list of all instances of the 6005 Event ID will be displayed. You can examine this list, look at the dates and times of each reboot event, and so on.
  4. Open Server Manager tool by right-clicking the Computer icon on the start menu (or on the Desktop if you have it enabled) and select Manage. Navigate to the Event Viewer.

enter image description here

5.1: Eventlog via PowerShell

Get-WinEvent -ProviderName eventlog | Where-Object {$_.Id -eq 6005 -or $_.Id -eq 6006}

6: Programmatically, by using GetTickCount64

GetTickCount64 retrieves the number of milliseconds that have elapsed since the system was started.

7: By using WMI

wmic os get lastbootuptime

8: The new uptime.exe for Windows XP and up

Like the tool from Microsoft, but compatible with all operating systems up to and including Windows 10 and Windows Server 2016, this uptime utility does not require an elevated command prompt and offers an option to show the uptime in both DD:HH:MM:SS and in human-readable formats (when executed with the -h command-line parameter).

Additionally, this version of uptime.exe will run and show the system uptime even when launched normally from within an explorer.exe session (i.e. not via the command line) and pause for the uptime to be read:

enter image description here

and when executed as uptime -h:

enter image description here

Update TensorFlow

Upgrading to Tensorflow 2.0 using pip. Requires Python > 3.4 and pip >= 19.0

CST:~ USERX$ pip3 show tensorflow
Name: tensorflow
Version: 1.13.1

CST:~ USERX$ python3 --version
Python 3.7.3

CST:~ USERX$ pip3 install --upgrade tensorflow

CST:~ USERX$ pip3 show tensorflow
Name: tensorflow
Version: 2.0.0

How do I write a RGB color value in JavaScript?

dec2hex = function (d) {
  if (d > 15)
    { return d.toString(16) } else
    { return "0" + d.toString(16) }
}
rgb = function (r, g, b) { return "#" + dec2hex(r) + dec2hex(g) + dec2hex(b) };

and:

parent.childNodes[1].style.color = rgb(155, 102, 102);

Date format in dd/MM/yyyy hh:mm:ss

CREATE FUNCTION DBO.ConvertDateToVarchar
(
@DATE DATETIME
)

RETURNS VARCHAR(24) 
BEGIN
RETURN (SELECT CONVERT(VARCHAR(19),@DATE, 121))
END

Getting only hour/minute of datetime

Just use Hour and Minute properties

var date = DateTime.Now;
date.Hour;
date.Minute;

Or you can easily zero the seconds using

var zeroSecondDate = date.AddSeconds(-date.Second);

How to set the context path of a web application in Tomcat 7.0

Here follows the only solutions that worked for me. Add this to the Host node in the conf/server.xml

<Context path="" docBase="yourAppContextName">

  <!-- Default set of monitored resources -->
  <WatchedResource>WEB-INF/web.xml</WatchedResource>

</Context>

go to Tomcat server.xml file and set path blank

How can I remove non-ASCII characters but leave periods and spaces using Python?

According to @artfulrobot, this should be faster than filter and lambda:

import re
re.sub(r'[^\x00-\x7f]',r'', your-non-ascii-string) 

See more examples here Replace non-ASCII characters with a single space

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

This is the question all others as well as Google redirect to so I'm posting this here.

Many of these answers are correct but too cumbersome for simple situations such as when you don't have over 26 columns. If you have any doubt whether you might go into double character columns then ignore this answer, but if you're sure you won't, then you could do it as simple as this in C#:

public static char ColIndexToLetter(short index)
{
    if (index < 0 || index > 25) throw new ArgumentException("Index must be between 0 and 25.");
    return (char)('A' + index);
}

Heck, if you're confident about what you're passing in you could even remove the validation and use this inline:

(char)('A' + index)

This will be very similar in many languages so you can adapt it as needed.

Again, only use this if you're 100% sure you won't have more than 26 columns.

super() in Java

That is correct. Super is used to call the parent constructor. So suppose you have a code block like so

class A{
    int n;
    public A(int x){
        n = x;
    }
}

class B extends A{
    int m;
    public B(int x, int y){
        super(x);
        m = y;
    }
}

Then you can assign a value to the member variable n.

Search for a string in all tables, rows and columns of a DB

To "find where the data I get comes from", you can start SQL Profiler, start your report or application, and you will see all the queries issued against your database.

changing minDate option in JQuery DatePicker not working

There is no need to destroy current instance, just refresh.

$('#datepicker')
    .datepicker('option', 'minDate', new Date)
    .datepicker('refresh');

How to Query Database Name in Oracle SQL Developer?

I know this is an old thread but you can also get some useful info from the V$INSTANCE view as well. the V$DATABASE displays info from the control file, the V$INSTANCE view displays state of the current instance.

How to call Stored Procedure in a View?

This construction is not allowed in SQL Server. An inline table-valued function can perform as a parameterized view, but is still not allowed to call an SP like this.

Here's some examples of using an SP and an inline TVF interchangeably - you'll see that the TVF is more flexible (it's basically more like a view than a function), so where an inline TVF can be used, they can be more re-eusable:

CREATE TABLE dbo.so916784 (
    num int
)
GO

INSERT INTO dbo.so916784 VALUES (0)
INSERT INTO dbo.so916784 VALUES (1)
INSERT INTO dbo.so916784 VALUES (2)
INSERT INTO dbo.so916784 VALUES (3)
INSERT INTO dbo.so916784 VALUES (4)
INSERT INTO dbo.so916784 VALUES (5)
INSERT INTO dbo.so916784 VALUES (6)
INSERT INTO dbo.so916784 VALUES (7)
INSERT INTO dbo.so916784 VALUES (8)
INSERT INTO dbo.so916784 VALUES (9)
GO

CREATE PROCEDURE dbo.usp_so916784 @mod AS int
AS 
BEGIN
    SELECT  *
    FROM    dbo.so916784
    WHERE   num % @mod = 0
END
GO

CREATE FUNCTION dbo.tvf_so916784 (@mod AS int)
RETURNS TABLE
    AS
RETURN
    (
     SELECT *
     FROM   dbo.so916784
     WHERE  num % @mod = 0
    )
GO    

EXEC dbo.usp_so916784 3
EXEC dbo.usp_so916784 4

SELECT * FROM dbo.tvf_so916784(3)    
SELECT * FROM dbo.tvf_so916784(4)

DROP FUNCTION dbo.tvf_so916784
DROP PROCEDURE dbo.usp_so916784
DROP TABLE dbo.so916784

How to make a local variable (inside a function) global

Here are two methods to achieve the same thing:

Using parameters and return (recommended)

def other_function(parameter):
    return parameter + 5

def main_function():
    x = 10
    print(x)    
    x = other_function(x)
    print(x)

When you run main_function, you'll get the following output

>>> 10
>>> 15

Using globals (never do this)

x = 0   # The initial value of x, with global scope

def other_function():
    global x
    x = x + 5

def main_function():
    print(x)    # Just printing - no need to declare global yet
    global x   # So we can change the global x
    x = 10
    print(x)
    other_function()
    print(x)

Now you will get:

>>> 0    # Initial global value
>>> 10   # Now we've set it to 10 in `main_function()`
>>> 15   # Now we've added 5 in `other_function()`

set background color: Android

This question is a old one but it can help for others too.

Try this :

    li.setBackgroundColor(getResources().getColor(R.color.blue));

    or

    li.setBackgroundColor(getResources().getColor(android.R.color.red));

    or

    li.setBackgroundColor(Color.rgb(226, 11, 11));


    or
    li.setBackgroundColor(Color.RED)

MySQL Fire Trigger for both Insert and Update

unfortunately we can't use in MySQL after INSERT or UPDATE description, like in Oracle

How to include static library in makefile

use

LDFLAGS= -L<Directory where the library resides> -l<library name>

Like :

LDFLAGS = -L. -lmine

for ensuring static compilation you can also add

LDFLAGS = -static

Or you can just get rid of the whole library searching, and link with with it directly.

say you have main.c fun.c

and a static library libmine.a

then you can just do in your final link line of the Makefile

$(CC) $(CFLAGS) main.o fun.o libmine.a

How to replace plain URLs with links?

This solution works like many of the others, and in fact uses the same regex as one of them, however in stead of returning a HTML String this will return a document fragment containing the A element and any applicable text nodes.

 function make_link(string) {
    var words = string.split(' '),
        ret = document.createDocumentFragment();
    for (var i = 0, l = words.length; i < l; i++) {
        if (words[i].match(/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi)) {
            var elm = document.createElement('a');
            elm.href = words[i];
            elm.textContent = words[i];
            if (ret.childNodes.length > 0) {
                ret.lastChild.textContent += ' ';
            }
            ret.appendChild(elm);
        } else {
            if (ret.lastChild && ret.lastChild.nodeType === 3) {
                ret.lastChild.textContent += ' ' + words[i];
            } else {
                ret.appendChild(document.createTextNode(' ' + words[i]));
            }
        }
    }
    return ret;
}

There are some caveats, namely with older IE and textContent support.

here is a demo.

Object Dump JavaScript

For Chrome/Chromium

console.log(myObj)

or it's equivalent

console.debug(myObj)

How to pass parameters or arguments into a gradle task

I would suggest the method presented on the Gradle forum:

def createMinifyCssTask(def brand, def sourceFile, def destFile) {
    return tasks.create("minify${brand}Css", com.eriwen.gradle.css.tasks.MinifyCssTask) {
        source = sourceFile
        dest = destFile
    }
}

I have used this method myself to create custom tasks, and it works very well.

Equals(=) vs. LIKE

For this example we take it for granted that varcharcol doesn't contain '' and have no empty cell against this column

select * from some_table where varcharCol = ''
select * from some_table where varcharCol like ''

The first one results in 0 row output while the second one shows the whole list. = is strictly-match case while like acts like a filter. if filter has no criteria, every data is valid.

like - by the virtue of its purpose works a little slower and is intended for use with varchar and similar data.

How to check if a variable is set in Bash?

You can do:

function a {
        if [ ! -z "$1" ]; then
                echo '$1 is set'
        fi
}

Difference between Return and Break statements

Break statement will break the whole loop and execute the code after loop and Return will not execute the code after that return statement and execute the loop with next increment.

Break

for(int i=0;i<5;i++){
    print(i)
    if(i==2)
    {
      break;
    }
}

output: 0 1

return

for(int i=0;i<5;i++)
{
   print(i)
   if(i==2)
   {
    return;
   }
}

output: 0 1 3 4

how to check for null with a ng-if values in a view with angularjs?

You can also use ng-template, I think that would be more efficient while run time :)

<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
    <div>2</div>
</ng-template>

Cheers

Is it still valid to use IE=edge,chrome=1?

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> serves two purposes.

  1. IE=edge: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.
  2. chrome=1: specifies that Google Chrome frame should start if the user has it installed

The IE=edge flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.

As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1 will do nothing more than consume a few bytes of bandwidth.

I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.

Note, the W3C validator will flag chrome=1 as an error:

Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.

Fastest way to list all primes below N

If you don't want to reinvent the wheel, you can install the symbolic maths library sympy (yes it's Python 3 compatible)

pip install sympy

And use the primerange function

from sympy import sieve
primes = list(sieve.primerange(1, 10**6))

Facebook database design?

Keep a friend table that holds the UserID and then the UserID of the friend (we will call it FriendID). Both columns would be foreign keys back to the Users table.

Somewhat useful example:

Table Name: User
Columns:
    UserID PK
    EmailAddress
    Password
    Gender
    DOB
    Location

TableName: Friends
Columns:
    UserID PK FK
    FriendID PK FK
    (This table features a composite primary key made up of the two foreign 
     keys, both pointing back to the user table. One ID will point to the
     logged in user, the other ID will point to the individual friend
     of that user)

Example Usage:

Table User
--------------
UserID EmailAddress Password Gender DOB      Location
------------------------------------------------------
1      [email protected]  bobbie   M      1/1/2009 New York City
2      [email protected]  jonathan M      2/2/2008 Los Angeles
3      [email protected]  joseph   M      1/2/2007 Pittsburgh

Table Friends
---------------
UserID FriendID
----------------
1      2
1      3
2      3

This will show that Bob is friends with both Jon and Joe and that Jon is also friends with Joe. In this example we will assume that friendship is always two ways, so you would not need a row in the table such as (2,1) or (3,2) because they are already represented in the other direction. For examples where friendship or other relations aren't explicitly two way, you would need to also have those rows to indicate the two-way relationship.

How to get document height and width without using jquery

Even the last example given on http://www.howtocreate.co.uk/tutorials/javascript/browserwindow is not working on Quirks mode. Easier to find than I thought, this seems to be the solution(extracted from latest jquery code):

Math.max(
    document.documentElement["clientWidth"],
    document.body["scrollWidth"],
    document.documentElement["scrollWidth"],
    document.body["offsetWidth"],
    document.documentElement["offsetWidth"]
);

just replace Width for "Height" to get Height.

An error occurred while collecting items to be installed (Access is denied)

On Windows 7, the Program Files directory is protected so apps can't automatically write there. The simplest solution I've heard is just to install Eclipse into a user-writable location instead. For example, C:\Java\Eclipse

You should be able to just move your entire eclipse directory, there's no registry entries or anything else that ties Eclipse to the place where you extracted it.

[Edit] Have you checked that the directory it is complaining about i actually writable? Other than that, I really don't have any ideas. I haven't worked on Windows in several years and never with Win7. My only other suggestion is to just download the latest Eclipse, install it to a new location (do NOT intall it over top of your existing Eclipse), and point it to your existing workspace.

Creating a triangle with for loops

A fun, simple solution:

for (int i = 0; i < 5; i++) 
  System.out.println("    *********".substring(i, 5 + 2*i));

MySQL - length() vs char_length()

LENGTH() returns the length of the string measured in bytes.
CHAR_LENGTH() returns the length of the string measured in characters.

This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:

select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1

As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC in UTF-8) even though it's only one character.

Deleting multiple elements from a list

An alternative list comprehension method that uses list index values:

stuff = ['a', 'b', 'c', 'd', 'e', 'f', 'woof']
index = [0, 3, 6]
new = [i for i in stuff if stuff.index(i) not in index]

This returns:

['b', 'c', 'e', 'f']

Default Xmxsize in Java 8 (max heap size)

Surprisingly this question doesn't have a definitive documented answer. Perhaps another data point would provide value to others looking for an answer. On my systems running CentOS (6.8,7.3) and Java 8 (build 1.8.0_60-b27, 64-Bit Server):

default memory is 1/4 of physical memory, not limited by 1GB.

Also, -XX:+PrintFlagsFinal prints to STDERR so command to determine current default memory presented by others above should be tweaked to the following:

java -XX:+PrintFlagsFinal 2>&1 | grep MaxHeapSize

The following is returned on system with 64GB of physical RAM:

uintx MaxHeapSize                                  := 16873684992      {product}

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;


public class WindowHandling
{
    [DllImport("User32.dll")]
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
    {
        Process p = Process.Start("notepad++.exe");
        p.WaitForInputIdle();
        IntPtr h = p.MainWindowHandle;
        SetForegroundWindow(h);
        SendKeys.SendWait("k");
        IntPtr processFoundWindow = p.MainWindowHandle;
    }
}

auto refresh for every 5 mins

Install an interval:

<script type="text/javascript">    
    setInterval(page_refresh, 5*60000); //NOTE: period is passed in milliseconds
</script>

Capture characters from standard input without waiting for enter to be pressed

#include <conio.h>

if (kbhit() != 0) {
    cout << getch() << endl;
}

This uses kbhit() to check if the keyboard is being pressed and uses getch() to get the character that is being pressed.

unary operator expected in shell script when comparing null value with string

Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that

let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"

It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?

CSS to stop text wrapping under image

Very simple answer for this problem that seems to catch a lot of people:

<img src="url-to-image">
<p>Nullam id dolor id nibh ultricies vehicula ut id elit.</p>

    img {
        float: left;
    }
    p {
        overflow: hidden;
    }

See example: http://jsfiddle.net/vandigroup/upKGe/132/

Calling functions in a DLL from C++

Presuming you're talking about dynamic runtime loading of DLLs, you're looking for LoadLibrary and GetProAddress. There's an example on MSDN.

jQuery Ajax Request inside Ajax Request

$.ajax({
    url: "<?php echo site_url('upToWeb/ajax_edit/')?>/" + id,
    type: "GET",
    dataType: "JSON",
    success: function (data) {
        if (data.web == 0) {
            if (confirm('Data product upToWeb ?')) {
                $.ajax({
                    url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
                    type: "post",
                    dataType: "json",
                    data: {web: 1},
                    success: function (respons) {
                        location.href = location.pathname;
                    },
                    error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
                        alert(xhr.responseText); // munculkan alert
                    }
                });
            }
        }
        else {
            if (confirm('Data product DownFromWeb ?')) {
                $.ajax({
                    url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
                    type: "post",
                    dataType: "json",
                    data: {web: 0},
                    success: function (respons) {
                        location.href = location.pathname;
                    },
                    error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
                        alert(xhr.responseText); // munculkan alert
                    }
                });
            }
        }
    },

    error: function (jqXHR, textStatus, errorThrown) {
        alert('Error get data from ajax');
    }

});

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

If you are using Linux OS:

  1. Remove matplotlib==1.3.1 from requirements.txt
  2. Try to install with sudo apt-get install python-matplotlib
  3. Run pip install -r requirements.txt (Python 2), or pip3 install -r requirements.txt (Python 3)
  4. pip freeze > requirements.txt

If you are using Windows OS:

  1. python -m pip install -U pip setuptools
  2. python -m pip install matplotlib

Configuring angularjs with eclipse IDE

Download angular js from this link and add as new software in eclipse http://oss.opensagres.fr/angularjs-eclipse/0.6.0/

static files with express.js

res.sendFile & express.static both will work for this

var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');

// viewed at http://localhost:8080
app.get('/', function(req, res) {
    res.sendFile(path.join(public, 'index.html'));
});

app.use('/', express.static(public));

app.listen(8080);

Where public is the folder in which the client side code is

As suggested by @ATOzTOA and clarified by @Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.

How to change Android version and code version number?

You can manage your application versioning wisely by using the Advanced Build Version Plugin for Gradle.

You just need to include the plugin in yout build.gradle:

buildscript {
  repositories {
      jcenter()
  }

  dependencies {
      classpath 'org.moallemi.gradle.advanced-build-version:gradle-plugin:1.5.0'
  }
}

apply plugin: 'org.moallemi.advanced-build-version'

And then you can use the versioning functions (and, obviously, customize them):

advancedVersioning {
    nameOptions { }
    codeOptions { }
    outputOptions { }
}

def appVersionName = advancedVersioning.versionName
def appVersionCode = advancedVersioning.versionCode

For more information, take a look at the official documentation.

Javadoc link to method in other class

Aside from @see, a more general way of refering to another class and possibly method of that class is {@link somepackage.SomeClass#someMethod(paramTypes)}. This has the benefit of being usable in the middle of a javadoc description.

From the javadoc documentation (description of the @link tag):

This tag is very simliar to @see – both require the same references and accept exactly the same syntax for package.class#member and label. The main difference is that {@link} generates an in-line link rather than placing the link in the "See Also" section. Also, the {@link} tag begins and ends with curly braces to separate it from the rest of the in-line text.

"Exception has been thrown by the target of an invocation" error (mscorlib)

Encounter the same error when tried to connect to SQLServer2017 through Management Studio 2014

enter image description here

The reason was backward compatibility

So I just downloaded the Management Studio 2017 and tried to connect to SQLServer2017.

Problem Solve!!

sizing div based on window width

html, body {
    height: 100%;
    width: 100%;
}

html {
    display: table;
    margin: auto;
}

body {
    padding-top: 50px;
    display: table-cell;
}

div {
    margin: auto;
}

This will center align objects and then also center align the items within them to center align multiple objects with different widths.

Example picture

Basic calculator in Java

import java.util.Scanner; import javax.swing.JOptionPane;

public class javaCalculator {

public static void main(String[] args) 
{
    int num1;
    int num2;
    String operation;


    Scanner input = new Scanner(System.in);

    System.out.println("please enter the first number");
    num1 = input.nextInt();

    System.out.println("please enter the second number");
    num2 = input.nextInt();

    Scanner op = new Scanner(System.in);

    System.out.println("Please enter operation");
    operation = op.next();

    if (operation.equals("+"))
    {
        System.out.println("your answer is" + (num1 + num2));
    }
   else if  (operation.equals("-"))
    {
        System.out.println("your answer is" + (num1 - num2));
    }

  else if (operation.equals("/"))
    {
        System.out.println("your answer is" + (num1 / num2));
    }
   else if (operation.equals("*"))
    {
        System.out.println("your answer is" + (num1 * num2));
    }
   else 
    {
       System.out.println("Wrong selection");
    }


}

}

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

Try this:

jsonResponse = json.loads(response.decode('utf-8'))

How to set a tkinter window to a constant size

You turn off pack_propagate by setting pack_propagate(0)

Turning off pack_propagate here basically says don't let the widgets inside the frame control it's size. So you've set it's width and height to be 500. Turning off propagate stills allows it to be this size without the widgets changing the size of the frame to fill their respective width / heights which is what would happen normally

To turn off resizing the root window, you can set root.resizable(0, 0), where resizing is allowed in the x and y directions respectively.

To set a maxsize to window, as noted in the other answer you can set the maxsize attribute or minsize although you could just set the geometry of the root window and then turn off resizing. A bit more flexible imo.

Whenever you set grid or pack on a widget it will return None. So, if you want to be able to keep a reference to the widget object you shouldn't be setting a variabe to a widget where you're calling grid or pack on it. You should instead set the variable to be the widget Widget(master, ....) and then call pack or grid on the widget instead.

import tkinter as tk

def startgame():

    pass

mw = tk.Tk()

#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")

mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction

back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window

#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy)
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()

mw.mainloop()

Clicking HTML 5 Video element to play, pause video, breaks play button

must separate this code to work well, or it well pause and play in one click !

 $('video').click(function(){this.played ? this.pause() ;});
  $('video').click(function(){this.paused ? this.play() ;});

How do I change Eclipse to use spaces instead of tabs?

Don't miss Tab policy for both of * Spaces only * Use spaces to indent wrapped lines

I checked only the latter thing and left the Combobox as Tabs Only which kept failing CheckStyle.. FYI, I'm talking about Preferences > Java > Formatter > Edit...

How to delete/truncate tables from Hadoop-Hive?

To Truncate:

hive -e "TRUNCATE TABLE IF EXISTS $tablename"

To Drop:

hive -e "Drop TABLE IF EXISTS $tablename"

How to prevent a dialog from closing when a button is clicked

For pre API 8 i solved the problem using a boolean flag, a dismiss listener and calling dialog.show again if in case the content of the editText wasn´t correct. Like this:

case ADD_CLIENT:
        LayoutInflater factoryClient = LayoutInflater.from(this);
        final View EntryViewClient = factoryClient.inflate(
                R.layout.alert_dialog_add_client, null);

        EditText ClientText = (EditText) EntryViewClient
                .findViewById(R.id.client_edit);

        AlertDialog.Builder builderClient = new AlertDialog.Builder(this);
        builderClient
                .setTitle(R.string.alert_dialog_client)
                .setCancelable(false)
                .setView(EntryViewClient)
                .setPositiveButton("Save",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                EditText newClient = (EditText) EntryViewClient
                                        .findViewById(R.id.client_edit);
                                String newClientString = newClient
                                        .getText().toString();
                                if (checkForEmptyFields(newClientString)) {
                                    //If field is empty show toast and set error flag to true;
                                    Toast.makeText(getApplicationContext(),
                                            "Fields cant be empty",
                                            Toast.LENGTH_SHORT).show();
                                    add_client_error = true;
                                } else {
                                    //Here save the info and set the error flag to false
                                    add_client_error = false;
                                }
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {
                                add_client_error = false;
                                dialog.cancel();
                            }
                        });
        final AlertDialog alertClient = builderClient.create();
        alertClient.show();

        alertClient
                .setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        //If the error flag was set to true then show the dialog again
                        if (add_client_error == true) {
                            alertClient.show();
                        } else {
                            return;
                        }

                    }
                });
        return true;

How to disable right-click context-menu in JavaScript

Capture the onContextMenu event, and return false in the event handler.

You can also capture the click event and check which mouse button fired the event with event.button, in some browsers anyway.

UIButton title text color

In Swift:

Changing the label text color is quite different than changing it for a UIButton. To change the text color for a UIButton use this method:

self.headingButton.setTitleColor(UIColor(red: 107.0/255.0, green: 199.0/255.0, blue: 217.0/255.0), forState: UIControlState.Normal)

How to get element by classname or id

If you want to find the button only by its class name and using jQLite only, you can do like below:

var myListButton = $document.find('button').filter(function() {
    return angular.element(this).hasClass('multi-files');
});

Hope this helps. :)

Today's Date in Perl in MM/DD/YYYY format

Formating numbers with leading zero is done easily with "sprintf", a built-in function in perl (documentation with: perldoc perlfunc)

use strict;
use warnings;
use Date::Calc qw();
my ($y, $m, $d) = Date::Calc::Today();
my $ddmmyyyy = sprintf '%02d.%02d.%d', $d, $m, $y;
print $ddmmyyyy . "\n";

This gives you:

14.05.2014

Limiting double to 3 decimal places

double example = 3.1416789645;
double output = Convert.ToDouble(example.ToString("N3"));

How to change the CHARACTER SET (and COLLATION) throughout a database?

change database collation:

ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

change table collation:

ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

change column collation:

ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

What do the parts of utf8mb4_0900_ai_ci mean?

3 bytes -- utf8
4 bytes -- utf8mb4 (new)
v4.0 --   _unicode_
v5.20 --  _unicode_520_
v9.0 --   _0900_ (new)
_bin      -- just compare the bits; don't consider case folding, accents, etc
_ci       -- explicitly case insensitive (A=a) and implicitly accent insensitive (a=á)
_ai_ci    -- explicitly case insensitive and accent insensitive
_as (etc) -- accent-sensitive (etc)
_bin         -- simple, fast
_general_ci  -- fails to compare multiple letters; eg ss=ß, somewhat fast
...          -- slower
_0900_       -- (8.0) much faster because of a rewrite

More info:

HTML5 Email Validation

I know you are not after the Javascript solution however there are some things such as the customized validation message that, from my experience, can only be done using JS.

Also, by using JS, you can dynamically add the validation to all input fields of type email within your site instead of having to modify every single input field.

var validations ={
    email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
};
$(document).ready(function(){
    // Check all the input fields of type email. This function will handle all the email addresses validations
    $("input[type=email]").change( function(){
        // Set the regular expression to validate the email 
        validation = new RegExp(validations['email'][0]);
        // validate the email value against the regular expression
        if (!validation.test(this.value)){
            // If the validation fails then we show the custom error message
            this.setCustomValidity(validations['email'][1]);
            return false;
        } else {
            // This is really important. If the validation is successful you need to reset the custom error message
            this.setCustomValidity('');
        }
    });
})

byte array to pdf

Usually this happens if something is wrong with the byte array.

File.WriteAllBytes("filename.PDF", Byte[]);

This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.

Asynchronous implementation of this is also available.

public static System.Threading.Tasks.Task WriteAllBytesAsync 
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);

How can I output leading zeros in Ruby?

Use String#next as the counter.

>> n = "000"
>> 3.times { puts "file_#{n.next!}" }
file_001
file_002
file_003

next is relatively 'clever', meaning you can even go for

>> n = "file_000"
>> 3.times { puts n.next! }
file_001
file_002
file_003

How to get the children of the $(this) selector?

The direct children is

$('> .child-class', this)

python dictionary sorting in descending order based on values

Whenever one has a dictionary where the values are integers, the Counter data structure is often a better choice to represent the data than a dictionary.

If you already have a dictionary, a counter can easily be formed by:

c = Counter(d['123'])

as an example from your data.

The most_common function allows easy access to descending order of the items in the counter

The more complete writeup on the Counter data structure is at https://docs.python.org/2/library/collections.html

Returning a pointer to a vector element in c++

You can use the data function of the vector:

Returns a pointer to the first element in the vector.

If don't want the pointer to the first element, but by index, then you can try, for example:

//the index to the element that you want to receive its pointer:
int i = n; //(n is whatever integer you want)

std::vector<myObject> vec;
myObject* ptr_to_first = vec.data();

//or

std::vector<myObject>* vec;
myObject* ptr_to_first = vec->data();

//then

myObject element = ptr_to_first[i]; //element at index i
myObject* ptr_to_element = &element;

Does --disable-web-security Work In Chrome Anymore?

The new tag for recent Chrome and Chromium browsers is :

--disable-web-security --user-data-dir=c:\my\data

How to compare two vectors for equality element by element in C++?

Your code (vector1 == vector2) is correct C++ syntax. There is an == operator for vectors.

If you want to compare short vector with a portion of a longer vector, you can use theequal() operator for vectors. (documentation here)

Here's an example:

using namespace std;

if( equal(vector1.begin(), vector1.end(), vector2.begin()) )
    DoSomething();

Converting from byte to int in java

byte b = (byte)0xC8;
int v1 = b;       // v1 is -56 (0xFFFFFFC8)
int v2 = b & 0xFF // v2 is 200 (0x000000C8)

Most of the time v2 is the way you really need.

Tesseract OCR simple example

A simple example of testing Tesseract OCR in C#:

    public static string GetText(Bitmap imgsource)
    {
        var ocrtext = string.Empty;
        using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
        {
            using (var img = PixConverter.ToPix(imgsource))
            {
                using (var page = engine.Process(img))
                {
                    ocrtext = page.GetText();
                }
            }
        }

        return ocrtext;
    }

Info: The tessdata folder must exist in the repository: bin\Debug\

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

No.

If the user is sophisticated or determined enough to:

  1. Open the Excel VBA editor
  2. Use the object browser to see the list of all sheets, including VERYHIDDEN ones
  3. Change the property of the sheet to VISIBLE or just HIDDEN

then they are probably sophisticated or determined enough to:

  1. Search the internet for "remove Excel 2007 project password"
  2. Apply the instructions they find.

So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.

Convert String array to ArrayList

Using Collections#addAll()

String[] words = {"ace","boom","crew","dog","eon"};
List<String> arrayList = new ArrayList<>(); 
Collections.addAll(arrayList, words); 

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

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

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

Replace below line of code :

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

with

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

SQL Greater than, Equal to AND Less Than

Somthing like this should workL

SELECT BookingId, StartTime
FROM Booking
WHERE StartTime between dateadd(hour, -1, getdate()) and getdate()

Chosen Jquery Plugin - getting selected values

Like from any regular input/select/etc...:

$("form.my-form .chosen-select").val()

SQL Server date format yyyymmdd

You can do as follows:

Select Format(test.Time, 'yyyyMMdd')
From TableTest test

How to remove undefined and null values from an object using lodash?

For deep nested object and arrays. and exclude empty values from string and NaN

function isBlank(value) {
  return _.isEmpty(value) && !_.isNumber(value) || _.isNaN(value);
}
var removeObjectsWithNull = (obj) => {
  return _(obj).pickBy(_.isObject)
    .mapValues(removeObjectsWithNull)
    .assign(_.omitBy(obj, _.isObject))
    .assign(_.omitBy(obj, _.isArray))
    .omitBy(_.isNil).omitBy(isBlank)
    .value();
}
var obj = {
  teste: undefined,
  nullV: null,
  x: 10,
  name: 'Maria Sophia Moura',
  a: null,
  b: '',
  c: {
    a: [{
      n: 'Gleidson',
      i: 248
    }, {
      t: 'Marta'
    }],
    g: 'Teste',
    eager: {
      p: 'Palavra'
    }
  }
}
removeObjectsWithNull(obj)

result:

{
   "c": {
      "a": [
         {
            "n": "Gleidson",
            "i": 248
         },
         {
            "t": "Marta"
         }
      ],
      "g": "Teste",
      "eager": {
         "p": "Palavra"
      }
   },
   "x": 10,
   "name": "Maria Sophia Moura"
}

Swing/Java: How to use the getText and setText string properly

You are setting the label text before the button is clicked to "txt". Instead when the button is clicked call setText() on the label and pass it the text from the text field.

Example:

label1.setText(nameField.getText()); 

How do you dynamically allocate a matrix?

You can also use std::vectors for achieving this:

using std::vector< std::vector<int> >

Example:

std::vector< std::vector<int> > a;

  //m * n is the size of the matrix

    int m = 2, n = 4;
    //Grow rows by m
    a.resize(m);
    for(int i = 0 ; i < m ; ++i)
    {
        //Grow Columns by n
        a[i].resize(n);
    }
    //Now you have matrix m*n with default values

    //you can use the Matrix, now
    a[1][0]=1;
    a[1][1]=2;
    a[1][2]=3;
    a[1][3]=4;

//OR
for(i = 0 ; i < m ; ++i)
{
    for(int j = 0 ; j < n ; ++j)
    {      //modify matrix
        int x = a[i][j];
    }

}

How do I exit from a function?

Yo can simply google for "exit sub in c#".

Also why would you check every text box if it is empty. You can place requiredfieldvalidator for these text boxes if this is an asp.net app and check if(Page.IsValid)

Or another solution is to get not of these conditions:

private void button1_Click(object sender, EventArgs e)
{
    if (!(textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == ""))
    {
        //do events
    }
}

And better use String.IsNullOrEmpty:

private void button1_Click(object sender, EventArgs e)
{
    if (!(String.IsNullOrEmpty(textBox1.Text)
    || String.IsNullOrEmpty(textBox2.Text)
    || String.IsNullOrEmpty(textBox3.Text)))
    {
        //do events
    }
}

Regex to match URL end-of-line or "/" character

To match either / or end of content, use (/|\z)

This only applies if you are not using multi-line matching (i.e. you're matching a single URL, not a newline-delimited list of URLs).


To put that with an updated version of what you had:

/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|\z)

Note that I've changed the start to be a non-greedy match for non-whitespace ( \S+? ) rather than matching anything and everything ( .* )

MySQL FULL JOIN?

SELECT  p.LastName, p.FirstName, o.OrderNo
FROM    persons AS p
LEFT JOIN
        orders AS o
ON      o.orderNo = p.p_id
UNION ALL
SELECT  NULL, NULL, orderNo
FROM    orders
WHERE   orderNo NOT IN
        (
        SELECT  p_id
        FROM    persons
        )

Replacing blank values (white space) with NaN in pandas

print(df.isnull().sum()) # check numbers of null value in each column

modifiedDf=df.fillna("NaN") # Replace empty/null values with "NaN"

# modifiedDf = fd.dropna() # Remove rows with empty values

print(modifiedDf.isnull().sum()) # check numbers of null value in each column

Converting Array to List

The second one creates a new array of Integers (first pass), and then adds all the elements of this new array to the list (second pass). It will thus be less efficient than the first one, which makes a single pass and doesn't create an unnecessary array of Integers.

A better way to use streams would be

List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());

Which should have roughly the same performance as the first one.

Note that for such a small array, there won't be any significant difference. You should try to write correct, readable, maintainable code instead of focusing on performance.

How to change pivot table data source in Excel?

for MS excel 2000 office version, click on the pivot table you will find a tab above the ribon, called Pivottable tool - click on that You can change data source from Data tab

What is the difference between user and kernel modes in operating systems?

I'm going to take a stab in the dark and guess you're talking about Windows. In a nutshell, kernel mode has full access to hardware, but user mode doesn't. For instance, many if not most device drivers are written in kernel mode because they need to control finer details of their hardware.

See also this wikibook.

Could not find server 'server name' in sys.servers. SQL Server 2014

I had the problem due to an extra space in the name of the linked server. "SERVER1, 1234" instead of "SERVER1,1234"

Append an empty row in dataframe using pandas

You can add it by appending a Series to the dataframe as follows. I am assuming by blank you mean you want to add a row containing only "Nan". You can first create a Series object with Nan. Make sure you specify the columns while defining 'Series' object in the -Index parameter. The you can append it to the DF. Hope it helps!

from numpy import nan as Nan
import pandas as pd

>>> df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
...                     'B': ['B0', 'B1', 'B2', 'B3'],
...                     'C': ['C0', 'C1', 'C2', 'C3'],
...                     'D': ['D0', 'D1', 'D2', 'D3']},
...                     index=[0, 1, 2, 3])

>>> s2 = pd.Series([Nan,Nan,Nan,Nan], index=['A', 'B', 'C', 'D'])
>>> result = df1.append(s2)
>>> result
     A    B    C    D
0   A0   B0   C0   D0
1   A1   B1   C1   D1
2   A2   B2   C2   D2
3   A3   B3   C3   D3
4  NaN  NaN  NaN  NaN

Minimum and maximum date

As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.

new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

For anyone who may stumble across this thread while trying to fix this same error that results by running Enable-Migrations, chances are none of the solutions above will help you (I tried them all).

I encountered this same issue in Web API 2 after running this in PM console:

Enable-Migrations -EnableAutomaticMigrations -ConnectionString IdentityConnection -ConnectionProviderName System.Data.SqlClient -Force

I fixed it by changing it to actually use the ApplicationDbContext created in IdentityModels.

Enable-Migrations -ContextTypeName ApplicationDbContext -EnableAutomaticMigrations -Force

The interesting thing is not only does this reference the same exact connection string, but the constructor includes code that 4castle said was a potential fix (i.e., the throwIfV1Schema: false suggestion.

Note that the -Force parameter is only being used because the Configuration.cs file already exists.

Try reinstalling `node-sass` on node 0.12?

You need to use the right version. Try:

nvm use 0.12

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     }
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   }
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      }
      if (empty($this->Sender)) {
         $this->Sender = $address;
      }
   }
   return true;
}

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);
}

Thanks for your help everyone!

Iterate over elements of List and Map using JSTL <c:forEach> tag

Mark, this is already answered in your previous topic. But OK, here it is again:

Suppose ${list} points to a List<Object>, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".

CreateProcess: No such file or directory

I had the same problem (I'm running cygwin)

Starting a shell through cygwin.bat didn't help, but starting a shell through MingWShell did. Not quite sure why, but I think it had something to do with the extra layer that cygwin puts between the executing script and the underlying filesystem.

I was running pip install from within a virtual env's cygwin to install django sentry..

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

I know this post is a couple years old, but I keep running into this and I'm not happy with the service locator pattern.

Also, I know the OP is looking for an implementation which allows you to choose a concrete implementation based on a string. I also realize that the OP is specifically asking for an implementation of an identical interface. The solution I'm about to describe relies on adding a generic type parameter to your interface. The problem is that you don't have any real use for the type parameter other than service collection binding. I'll try to describe a situation which might require something like this.

Imagine configuration for such a scenario in appsettings.json which might look something like this (this is just for demonstration, your configuration can come from wherever you want as long as you have the correction configuration provider):

{
  "sqlDataSource": {
    "connectionString": "Data Source=localhost; Initial catalog=Foo; Connection Timeout=5; Encrypt=True;",
    "username": "foo",
    "password": "this normally comes from a secure source, but putting here for demonstration purposes"
  },
  "mongoDataSource": {
    "hostName": "uw1-mngo01-cl08.company.net",
    "port": 27026,
    "collection": "foo"
  }
}

You really need a type that represents each of your configuration options:

public class SqlDataSource
{
  public string ConnectionString { get;set; }
  public string Username { get;set; }
  public string Password { get;set; }
}

public class MongoDataSource
{
  public string HostName { get;set; }
  public string Port { get;set; }
  public string Collection { get;set; }
}

Now, I know that it might seem a little contrived to have two implementations of the same interface, but it I've definitely seen it in more than one case. The ones I usually come across are:

  1. When migrating from one data store to another, it's useful to be able to implement the same logical operations using the same interfaces so that you don't need to change the calling code. This also allows you to add configuration which swaps between different implementations at runtime (which can be useful for rollback).
  2. When using the decorator pattern. The reason you might use that pattern is that you want to add functionality without changing the interface and fall back to the existing functionality in certain cases (I've used it when adding caching to repository classes because I want circuit breaker-like logic around connections to the cache that fall back to the base repository -- this gives me optimal behavior when the cache is available, but behavior that still functions when it's not).

Anyway, you can reference them by adding a type parameter to your service interface so that you can implement the different implementations:

public interface IService<T> {
  void DoServiceOperation();
}

public class MongoService : IService<MongoDataSource> {
  private readonly MongoDataSource _options;

  public FooService(IOptionsMonitor<MongoDataSource> serviceOptions){
    _options = serviceOptions.CurrentValue
  }

  void DoServiceOperation(){
    //do something with your mongo data source options (connect to database)
    throw new NotImplementedException();
  }
}

public class SqlService : IService<SqlDataSource> {
  private readonly SqlDataSource_options;

  public SqlService (IOptionsMonitor<SqlDataSource> serviceOptions){
    _options = serviceOptions.CurrentValue
  }

  void DoServiceOperation(){
    //do something with your sql data source options (connect to database)
    throw new NotImplementedException();
  }
}

In startup, you'd register these with the following code:

services.Configure<SqlDataSource>(configurationSection.GetSection("sqlDataSource"));
services.Configure<MongoDataSource>(configurationSection.GetSection("mongoDataSource"));

services.AddTransient<IService<SqlDataSource>, SqlService>();
services.AddTransient<IService<MongoDataSource>, MongoService>();

Finally in the class which relies on the Service with a different connection, you just take a dependency on the service you need and the DI framework will take care of the rest:

[Route("api/v1)]
[ApiController]
public class ControllerWhichNeedsMongoService {  
  private readonly IService<MongoDataSource> _mongoService;
  private readonly IService<SqlDataSource> _sqlService ;

  public class ControllerWhichNeedsMongoService(
    IService<MongoDataSource> mongoService, 
    IService<SqlDataSource> sqlService
  )
  {
    _mongoService = mongoService;
    _sqlService = sqlService;
  }

  [HttpGet]
  [Route("demo")]
  public async Task GetStuff()
  {
    if(useMongo)
    {
       await _mongoService.DoServiceOperation();
    }
    await _sqlService.DoServiceOperation();
  }
}

These implementations can even take a dependency on each other. The other big benefit is that you get compile-time binding so any refactoring tools will work correctly.

Hope this helps someone in the future.

How to change a field name in JSON using Jackson

Have you tried using @JsonProperty?

@Entity
public class City {
   @id
   Long id;
   String name;

   @JsonProperty("label")
   public String getName() { return name; }

   public void setName(String name){ this.name = name; }

   @JsonProperty("value")
   public Long getId() { return id; }

   public void setId(Long id){ this.id = id; }
}

JavaScript array to CSV

for a simple csv one map() and a join() are enough:

var csv = test_array.map(function(d){
    return d.join();
}).join('\n');

/* Results in 
name1,2,3
name2,4,5
name3,6,7
name4,8,9
name5,10,11

This method also allows you to specify column separator other than a comma in the inner join. for example a tab: d.join('\t')

On the other hand if you want to do it properly and enclose strings in quotes "", then you can use some JSON magic:

var csv = test_array.map(function(d){
   return JSON.stringify(d);
})
.join('\n') 
.replace(/(^\[)|(\]$)/mg, ''); // remove opening [ and closing ] brackets from each line 

/* would produce
"name1",2,3
"name2",4,5
"name3",6,7
"name4",8,9
"name5",10,11

if you have array of objects like :

var data = [
  {"title": "Book title 1", "author": "Name1 Surname1"},
  {"title": "Book title 2", "author": "Name2 Surname2"},
  {"title": "Book title 3", "author": "Name3 Surname3"},
  {"title": "Book title 4", "author": "Name4 Surname4"}
];

// use
var csv = data.map(function(d){
    return JSON.stringify(Object.values(d));
})
.join('\n') 
.replace(/(^\[)|(\]$)/mg, '');

I need to convert an int variable to double

You have to cast one (or both) of the arguments to the division operator to double:

double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);

Since you are performing the same calculation twice I'd recommend refactoring your code:

double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;

This works in the same way, but now there is an implicit cast to double. This conversion from int to double is an example of a widening primitive conversion.

Difference between F5, Ctrl + F5 and click on refresh button?

F5 reloads the page from server, but it uses the browser's cache for page elements like scripts, image, CSS stylesheets, etc, etc. But Ctrl + F5, reloads the page from the server and also reloads its contents from server and doesn't use local cache at all.

So by pressing F5 on, say, the Yahoo homepage, it just reloads the main HTML frame and then loads all other elements like images from its cache. If a new element was added or changed then it gets it from the server. But Ctrl + F5 reloads everything from the server.

Values of disabled inputs will not be submitted

Yes, all browsers should not submit the disabled inputs, as they are read-only.

More information (section 17.12.1)

Attribute definitions

disabled [CI] When set for a form control, this Boolean attribute disables the control for user input. When set, the disabled attribute has the following effects on an element:

  • Disabled controls do not receive focus.
  • Disabled controls are skipped in tabbing navigation.
  • Disabled controls cannot be successful.

The following elements support the disabled attribute: BUTTON, INPUT, OPTGROUP, OPTION, SELECT, and TEXTAREA.

This attribute is inherited but local declarations override the inherited value.

How disabled elements are rendered depends on the user agent. For example, some user agents "gray out" disabled menu items, button labels, etc.

In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.

<INPUT disabled name="fred" value="stone">

Note. The only way to modify dynamically the value of the disabled attribute is through a script.

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

In most cases, it is enough just to hide the element, for example in this way:

export default class ErrorBoxComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isHidden: false
        }
    }

    dismiss() {
        this.setState({
            isHidden: true
        })
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className={ "alert-box error-box " + (this.state.isHidden ? 'DISPLAY-NONE-CLASS' : '') }>
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

Or you may render/rerender/not render via parent component like this

export default class ParentComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isErrorShown: true
        }
    }

    dismiss() {
        this.setState({
            isErrorShown: false
        })
    }

    showError() {
        if (this.state.isErrorShown) {
            return <ErrorBox 
                error={ this.state.error }
                dismiss={ this.dismiss.bind(this) }
            />
        }

        return null;
    }

    render() {

        return (
            <div>
                { this.showError() }
            </div>
        );
    }
}

export default class ErrorBoxComponent extends React.Component {
    dismiss() {
        this.props.dismiss();
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className="alert-box error-box">
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

Finally, there is a way to remove html node, but i really dont know is it a good idea. Maybe someone who knows React from internal will say something about this.

export default class ErrorBoxComponent extends React.Component {
    dismiss() {
        this.el.remove();
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className="alert-box error-box" ref={ (el) => { this.el = el} }>
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

I had this issue with AOSP (clang).

Add external\libcxx\include to includes and _LIBCPP_COMPILER_CLANG to symbols

What is the point of WORKDIR on Dockerfile?

Before applying WORKDIR. Here the WORKDIR is at the wrong place and is not used wisely.

FROM microsoft/aspnetcore:2
COPY --from=build-env /publish /publish
WORKDIR /publish
ENTRYPOINT ["dotnet", "/publish/api.dll"]

We corrected the above code to put WORKDIR at the right location and optimised the following statements by removing /Publish

FROM microsoft/aspnetcore:2
WORKDIR /publish
COPY --from=build-env /publish .
ENTRYPOINT ["dotnet", "api.dll"]

So it acts like a cd and sets the tone for the upcoming statements.

Redirect stdout to a file in Python?

You need a terminal multiplexer like either tmux or GNU screen

I'm surprised that a small comment by Ryan Amos' to the original question is the only mention of a solution far preferable to all the others on offer, no matter how clever the python trickery may be and how many upvotes they've received. Further to Ryan's comment, tmux is a nice alternative to GNU screen.

But the principle is the same: if you ever find yourself wanting to leave a terminal job running while you log-out, head to the cafe for a sandwich, pop to the bathroom, go home (etc) and then later, reconnect to your terminal session from anywhere or any computer as though you'd never been away, terminal multiplexers are the answer. Think of them as VNC or remote desktop for terminal sessions. Anything else is a workaround. As a bonus, when the boss and/or partner comes in and you inadvertently ctrl-w / cmd-w your terminal window instead of your browser window with its dodgy content, you won't have lost the last 18 hours-worth of processing!

Can't create project on Netbeans 8.2

Java SE Development Kit 9 is not compatible with the Netbeans IDE 8.2.

My Solution:

  1. Delete the current JDK 9
  2. Install this previous trust version of JDK: JDK 8
  3. Modify the following file: \Program Files\NetBeans 8.2\etc\netbeans.conf to the given folder path of the newly installed JDK 8: netbeans_jdkhome="C:\Program Files\Java\jdk1.8.0_151" (example)

Can't import Numpy in Python

Have you installed it?

On debian/ubuntu:

aptitude install python-numpy

On windows:

http://sourceforge.net/projects/numpy/files/NumPy/

On other systems:

http://sourceforge.net/projects/numpy/files/NumPy/

$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install

In Perl, how can I read an entire file into a string?

open f, "test.txt"
$file = join '', <f>

<f> - returns an array of lines from our file (if $/ has the default value "\n") and then join '' will stick this array into.

Equivalent to AssemblyInfo in dotnet core/csproj

Those settings has moved into the .csproj file.

By default they don't show up but you can discover them from Visual Studio 2017 in the project properties Package tab.

Project properties, tab Package

Once saved those values can be found in MyProject.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <Version>1.2.3.4</Version>
    <Authors>Author 1</Authors>
    <Company>Company XYZ</Company>
    <Product>Product 2</Product>
    <PackageId>MyApp</PackageId>
    <AssemblyVersion>2.0.0.0</AssemblyVersion>
    <FileVersion>3.0.0.0</FileVersion>
    <NeutralLanguage>en</NeutralLanguage>
    <Description>Description here</Description>
    <Copyright>Copyright</Copyright>
    <PackageLicenseUrl>License URL</PackageLicenseUrl>
    <PackageProjectUrl>Project URL</PackageProjectUrl>
    <PackageIconUrl>Icon URL</PackageIconUrl>
    <RepositoryUrl>Repo URL</RepositoryUrl>
    <RepositoryType>Repo type</RepositoryType>
    <PackageTags>Tags</PackageTags>
    <PackageReleaseNotes>Release</PackageReleaseNotes>
  </PropertyGroup>

In the file explorer properties information tab, FileVersion is shown as "File Version" and Version is shown as "Product version"

Installing NumPy via Anaconda in Windows

The above answers seem to resolve the issue. If it doesn't, then you may also try to update conda using the following command.

conda update conda

And then try to install numpy using

conda install numpy

How to round the corners of a button

Pushing to the limits corner radius up to get a circle:

    self.btnFoldButton.layer.cornerRadius = self.btnFoldButton.frame.height/2.0;

enter image description here

If button frame is an square it does not matter frame.height or frame.width. Otherwise use the largest of both ones.

List of Python format characters

In docs.python.org Topic = 5.6.2. String Formatting Operations http://docs.python.org/library/stdtypes.html#string-formatting then further down to the chart (text above chart is "The conversion types are:")

The chart lists 16 types and some following notes.

My comment: help does not include attitude which is a bonus. The attitude post enabled me to search further and find the info.

How to print a list of symbols exported from a dynamic library

Use nm -a your.dylib

It will print all the symbols including globals

Parsing Query String in node.js

You can use the parse method from the URL module in the request callback.

var http = require('http');
var url = require('url');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  var queryData = url.parse(request.url, true).query;
  response.writeHead(200, {"Content-Type": "text/plain"});

  if (queryData.name) {
    // user told us their name in the GET request, ex: http://host:8000/?name=Tom
    response.end('Hello ' + queryData.name + '\n');

  } else {
    response.end("Hello World\n");
  }
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

I suggest you read the HTTP module documentation to get an idea of what you get in the createServer callback. You should also take a look at sites like http://howtonode.org/ and checkout the Express framework to get started with Node faster.

What's the best way to do a backwards loop in C/C#/C++?

I'd use the code in the original question, but if you really wanted to use foreach and have an integer index in C#:

foreach (int i in Enumerable.Range(0, myArray.Length).Reverse())
{
    myArray[i] = 42; 
}

How to do a SUM() inside a case statement in SQL server

You could use a Common Table Expression to create the SUM first, join it to the table, and then use the WHEN to to get the value from the CTE or the original table as necessary.

WITH PercentageOfTotal (Id, Percentage) 
AS 
(
    SELECT Id, (cnt / SUM(AreaId)) FROM dbo.MyTable GROUP BY Id
)
SELECT 
    CASE
        WHEN o.TotalType = 'Average' THEN r.avgscore
        WHEN o.TotalType = 'PercentOfTot' THEN pt.Percentage
        ELSE o.cnt
    END AS [displayscore]
FROM PercentageOfTotal pt
    JOIN dbo.MyTable t ON pt.Id = t.Id

Show a PDF files in users browser via PHP/Perl

You can also use fpdf class available at: http://www.fpdf.org. It gives options for both outputting to a file and displaying on browser.

Convert string to decimal number with 2 decimal places in Java

Use BigDecimal:

new BigDecimal(theInputString);

It retains all decimal digits. And you are sure of the exact representation since it uses decimal base, not binary base, to store the precision/scale/etc.

And it is not subject to precision loss like float or double are, unless you explicitly ask it to.

How do you create a daemon in Python?

since python-daemon has not yet supported python 3.x, and from what can be read on the mailing list, it may never will, i have written a new implementation of PEP 3143: pep3143daemon

pep3143daemon should support at least python 2.6, 2.7 and 3.x

It also contains a PidFile class.

The library only depends on the standard library and on the six module.

It can be used as a drop in replacement for python-daemon.

Here is the documentation.

Why not use Double or Float to represent currency?

From Bloch, J., Effective Java, 2nd ed, Item 48:

The float and double types are particularly ill-suited for monetary calculations because it is impossible to represent 0.1 (or any other negative power of ten) as a float or double exactly.

For example, suppose you have $1.03 and you spend 42c. How much money do you have left?

System.out.println(1.03 - .42);

prints out 0.6100000000000001.

The right way to solve this problem is to use BigDecimal, int or long for monetary calculations.

Though BigDecimal has some caveats (please see currently accepted answer).

Using strtok with a std::string

Duplicate the string, tokenize it, then free it.

char *dup = strdup(str.c_str());
token = strtok(dup, " ");
free(dup);

iOS detect if user is on an iPad

UI_USER_INTERFACE_IDIOM() only returns iPad if the app is for iPad or Universal. If its an iPhone app running on an iPad then it won't. So you should instead check the model.

How can I get href links from HTML using Python?

Look at using the beautiful soup html parsing library.

http://www.crummy.com/software/BeautifulSoup/

You will do something like this:

import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(html)
for link in soup.findAll("a"):
    print link.get("href")

Android: Background Image Size (in Pixel) which Support All Devices

GIMP tool is exactly what you need to create the images for different pixel resolution devices.

Follow these steps:

  1. Open the existing image in GIMP tool.
  2. Go to "Image" menu, and select "Scale Image..."
  3. Use below pixel dimension that you need:

    xxxhdpi: 1280x1920 px

    xxhdpi: 960x1600 px

    xhdpi: 640x960 px

    hdpi: 480x800 px

    mdpi: 320x480 px

    ldpi: 240x320 px

  4. Then "Export" the image from "File" menu.

Reading from memory stream to string

If you'd checked the results of stream.Read, you'd have seen that it hadn't read anything - because you haven't rewound the stream. (You could do this with stream.Position = 0;.) However, it's easier to just call ToArray:

settingsString = LocalEncoding.GetString(stream.ToArray());

(You'll need to change the type of stream from Stream to MemoryStream, but that's okay as it's in the same method where you create it.)

Alternatively - and even more simply - just use StringWriter instead of StreamWriter. You'll need to create a subclass if you want to use UTF-8 instead of UTF-16, but that's pretty easy. See this answer for an example.

I'm concerned by the way you're just catching Exception and assuming that it means something harmless, by the way - without even logging anything. Note that using statements are generally cleaner than writing explicit finally blocks.

How to compare DateTime without time via LINQ?

Try

var q = db.Games.Where(t => t.StartDate.Date >= DateTime.Now.Date).OrderBy(d => d.StartDate);

How to convert list of numpy arrays into single numpy array?

I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.

Timing:

|------------|----------------|-------------------|
|            | shape (10000)  |  shape (1,10000)  |
|------------|----------------|-------------------|
| np.concat  |    0.18280     |      0.17960      |
|------------|----------------|-------------------|
|  np.stack  |    0.21501     |      0.16465      |
|------------|----------------|-------------------|
| np.vstack  |    0.21501     |      0.17181      |
|------------|----------------|-------------------|
|  np.array  |    0.21656     |      0.16833      |
|------------|----------------|-------------------|

As you can see I tried 2 experiments - using np.random.rand(10000) and np.random.rand(1, 10000) And if we use 2d arrays than np.stack and np.array create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.

Code:

from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
    new_np = np.random.rand(10000)
    l.append(new_np)



start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')

start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')

start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')

start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')

Parsing arguments to a Java command line program

Ok, thanks to Charles Goodwin for the concept. Here is the answer:

import java.util.*;
public class Test {

  public static void main(String[] args) {
     List<String> argsList  = new ArrayList<String>();  
     List<String> optsList  = new ArrayList<String>();
     List<String> doubleOptsList  = new ArrayList<String>();
     for (int i=0; i < args.length; i++) {
         switch (args[i].charAt(0)) {
         case '-':
             if (args[i].charAt(1) == '-') {
                 int len = 0;
                 String argstring = args[i].toString();
                 len = argstring.length();
                 System.out.println("Found double dash with command " +
                     argstring.substring(2, len) );
                 doubleOptsList.add(argstring.substring(2, len));           
             } else {
                 System.out.println("Found dash with command " + 
                   args[i].charAt(1) + " and value " + args[i+1] );   
                 i= i+1;
                 optsList.add(args[i]);      
             }           
         break;         
         default:            
         System.out.println("Add a default arg." );
         argsList.add(args[i]);
         break;         
         }     
     } 
  } 

}

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

my solution was - just remove '*' character from the expression ^__^

<div ngFor="let talk in talks">

How to pass multiple parameters from ajax to mvc controller?

Try this:

var req={StrContactDetails:'data',IsPrimary:'True'}

$.ajax({
                   type: 'POST',
                   data: req,
                   url: '@url.Action("SaveEmergencyContact","Dhp")',
                   contentType: "application/json; charset=utf-8",
                   dataType: "json",
                   data: JSON.stringify(req),
                   success: function (data) {
                       alert("Success");
                   },
                   error: function (ob, errStr) {
                       alert("An error occured.Please try after sometime.");
                   }
               });

http://api.jquery.com/jquery.ajax/

Sending arrays with Intent.putExtra

final static String EXTRA_MESSAGE = "edit.list.message";

Context context;
public void onClick (View view)
{   
    Intent intent = new Intent(this,display.class);
    RelativeLayout relativeLayout = (RelativeLayout) view.getParent();

    TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
    String message = textView.getText().toString();

    intent.putExtra(EXTRA_MESSAGE,message);
    startActivity(intent);
}

How to remove files from git staging area?

I tried all these method but none worked for me. I removed .git file using rm -rf .git form the local repository and then again did git init and git add and routine commands. It worked.

finished with non zero exit value

I had this same problem, and it only went away after a removed the .gradle folder from my project's root.

So make sure you:

  1. Close the project in Android Studio
  2. Open your file explorer, find the project's root directory
  3. Completely remove the folder .gradle

I hope this helps. Good luck!

LINQ query to return a Dictionary<string, string>

Look at the ToLookup and/or ToDictionary extension methods.

How to override a JavaScript function

var origParseFloat = parseFloat;
parseFloat = function(str) {
     alert("And I'm in your floats!");
     return origParseFloat(str);
}

HTML input fields does not get focus when clicked

I had the similar issue - could not figure out what was the reason, but I fixed it using following code. Somehow it could not focus only the blank inputs:

$('input').click(function () {
        var val = $(this).val();
        if (val == "") {
            this.select();
        }
    });

Location of my.cnf file on macOS

In case of Mac OS X Maverick when MySQL is installed via Homebrew it's located at /usr/local/opt/mysql/my.cnf

SQL Server Script to create a new user

If you want to create a generic script you can do it with an Execute statement with a Replace with your username and database name

Declare @userName as varchar(50); 
Declare @defaultDataBaseName as varchar(50);
Declare @LoginCreationScript as varchar(max);
Declare @UserCreationScript as varchar(max);
Declare @TempUserCreationScript as varchar(max);
set @defaultDataBaseName = 'data1';
set @userName = 'domain\userName';
set @LoginCreationScript ='CREATE LOGIN [{userName}]
FROM WINDOWS 
WITH DEFAULT_DATABASE ={dataBaseName}'

set @UserCreationScript ='
USE {dataBaseName}
CREATE User [{userName}] for LOGIN [{userName}];
EXEC sp_addrolemember ''db_datareader'', ''{userName}'';
EXEC sp_addrolemember ''db_datawriter'', ''{userName}'';
Grant Execute on Schema :: dbo TO [{userName}];'
/*Login creation*/
set @LoginCreationScript=Replace(Replace(@LoginCreationScript, '{userName}', @userName), '{dataBaseName}', @defaultDataBaseName)
set @UserCreationScript =Replace(@UserCreationScript, '{userName}', @userName)
Execute(@LoginCreationScript)

/*User creation and role assignment*/
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', @defaultDataBaseName)
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db2')
Execute(@TempUserCreationScript)
set @TempUserCreationScript =Replace(@UserCreationScript, '{dataBaseName}', 'db3')
Execute(@TempUserCreationScript)

Is there Selected Tab Changed Event in the standard WPF Tab Control

You could still use that event. Just check that the sender argument is the control you actually care about and if so, run the event code.

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

You might check Select2 plugin:

http://ivaynberg.github.io/select2/

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.

It's quite popular and very maintainable. It should cover most of your needs if not all.

How do you run a single query through mysql from the command line?

here's how you can do it with a cool shell trick:

mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'

'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.

use the -t flag to enable table-format output

How to convert a table to a data frame

While the results vary in this case because the column names are numbers, another way I've used is data.frame(rbind(mytable)). Using the example from @X.X:

> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)

> freq_t
   gear
cyl  3  4  5
  4  1  8  2
  6  2  4  1
  8 12  0  2

> data.frame(rbind(freq_t))
  X3 X4 X5
4  1  8  2
6  2  4  1
8 12  0  2

If the column names do not start with numbers, the X won't get added to the front of them.

Count records for every month in a year

select count(*) 
from table_emp 
 where DATEPART(YEAR, ARR_DATE) = '2012' AND DATEPART(MONTH, ARR_DATE) = '01'

Sort ArrayList of custom Objects by property

New since 1.8 is a List.sort() method instead of using the Collection.sort() so you directly call mylistcontainer.sort()

Here is a code snippet which demonstrates the List.sort() feature:

List<Fruit> fruits = new ArrayList<Fruit>();
fruits.add(new Fruit("Kiwi","green",40));
fruits.add(new Fruit("Banana","yellow",100));
fruits.add(new Fruit("Apple","mixed green,red",120));
fruits.add(new Fruit("Cherry","red",10));

// a) using an existing compareto() method
fruits.sort((Fruit f1,Fruit f2) -> f1.getFruitName().compareTo(f2.getFruitName()));
System.out.println("Using String.compareTo(): " + fruits);
//Using String.compareTo(): [Apple is: mixed green,red, Banana is: yellow, Cherry is: red, Kiwi is: green]

// b) Using a comparable class
fruits.sort((Fruit f1,Fruit f2) -> f1.compareTo(f2));  
System.out.println("Using a Comparable Fruit class (sort by color): " + fruits);
// Using a Comparable Fruit class (sort by color): [Kiwi is green, Apple is: mixed green,red, Cherry is: red, Banana is: yellow]

The Fruit class is:

public class Fruit implements Comparable<Fruit>
{
    private String name;
    private String color;
    private int quantity;

    public Fruit(String name,String color,int quantity)
    { this.name = name; this.color = color; this.quantity = quantity; }

    public String getFruitName() { return name; }        
    public String getColor() { return color; }  
    public int getQuantity() { return quantity; }

    @Override public final int compareTo(Fruit f) // sorting the color
    {
        return this.color.compareTo(f.color);
    }     
    @Override public String toString()
    {   
        return (name + " is: " + color);
    }
} // end of Fruit class   

force Maven to copy dependencies into target/lib

If you make your project a war or ear type maven will copy the dependencies.

Original purpose of <input type="hidden">?

I can only imagine of sending a value from the server to the client which is (unchanged) sent back to maintain a kind of a state.

Precisely. In fact, it's still being used for this purpose today because HTTP as we know it today is still, at least fundamentally, a stateless protocol.

This use case was actually first described in HTML 3.2 (I'm surprised HTML 2.0 didn't include such a description):

type=hidden
These fields should not be rendered and provide a means for servers to store state information with a form. This will be passed back to the server when the form is submitted, using the name/value pair defined by the corresponding attributes. This is a work around for the statelessness of HTTP. Another approach is to use HTTP "Cookies".

<input type=hidden name=customerid value="c2415-345-8563">

While it's worth mentioning that HTML 3.2 became a W3C Recommendation only after JavaScript's initial release, it's safe to assume that hidden fields have pretty much always served the same purpose.

Forcing label to flow inline with input that they label

<style>
.nowrap {
    white-space: nowrap;
}
</style>

...

<label for="id1" class="nowrap">label1:
    <input type="text" id="id1"/>
</label>

Wrap your inputs within the label tag

What is token-based authentication?

A token is a piece of data which only Server X could possibly have created, and which contains enough data to identify a particular user.

You might present your login information and ask Server X for a token; and then you might present your token and ask Server X to perform some user-specific action.

Tokens are created using various combinations of various techniques from the field of cryptography as well as with input from the wider field of security research. If you decide to go and create your own token system, you had best be really smart.

Stuck at ".android/repositories.cfg could not be loaded."

I had the same error on OSX Sierra, but in my case the ~/.android folder was owned by root (from a previous install) I changed the ownership to my User and now it works.

Amazon S3 and Cloudfront cache, how to clear cache or synchronize their cache

S3 is not used for real time development but if you really want to test your freshly deployed website use

http://yourdomain.com/index.html?v=2
http://yourdomain.com/init.js?v=2

Adding a version parameter in the end will stop using the cached version of the file and the browser will get a fresh copy of the file from the server bucket

Searching for file in directories recursively

I tried some of the other solutions listed here, but during unit testing the code would throw exceptions I wanted to ignore. I ended up creating the following recursive search method that will ignore certain exceptions like PathTooLongException and UnauthorizedAccessException.

    private IEnumerable<string> RecursiveFileSearch(string path, string pattern, ICollection<string> filePathCollector = null)
    {
        try
        {
            filePathCollector = filePathCollector ?? new LinkedList<string>();

            var matchingFilePaths = Directory.GetFiles(path, pattern);

            foreach(var matchingFile in matchingFilePaths)
            {
                filePathCollector.Add(matchingFile);
            }

            var subDirectories = Directory.EnumerateDirectories(path);

            foreach (var subDirectory in subDirectories)
            {
                RecursiveFileSearch(subDirectory, pattern, filePathCollector);
            }

            return filePathCollector;
        }
        catch (Exception error)
        {
            bool isIgnorableError = error is PathTooLongException ||
                error is UnauthorizedAccessException;

            if (isIgnorableError)
            {
                return Enumerable.Empty<string>();
            }

            throw error;
        }
    }

Determining complexity for recursive functions (Big O notation)

The key here is to visualise the call tree. Once done that, the complexity is:

nodes of the call tree * complexity of other code in the function

the latter term can be computed the same way we do for a normal iterative function.

Instead, the total nodes of a complete tree are computed as

                  C^L - 1
                  -------  , when C>1
               /   C - 1
              /
 # of nodes =
              \    
               \ 
                  L        , when C=1

Where C is number of children of each node and L is the number of levels of the tree (root included).

It is easy to visualise the tree. Start from the first call (root node) then draw a number of children same as the number of recursive calls in the function. It is also useful to write the parameter passed to the sub-call as "value of the node".

So, in the examples above:

  1. the call tree here is C = 1, L = n+1. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n+1) * O(1) = O(n)
n     level 1
n-1   level 2
n-2   level 3
n-3   level 4
... ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n/5) * O(1) = O(n)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5
  1. call tree here is C = 1, L = log(n). Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = log5(n) * O(1) = O(log(n))
n
n/5
n/5^2
n/5^3
... ~ log5(n) levels -> L = log5(n)
  1. call tree here is C = 2, L = n. Complexity of the rest of function is O(1). This time we use the full formula for the number of nodes in the call tree because C > 1. Therefore total complexity is (C^L-1)/(C-1) * O(1) = (2^n - 1) * O(1) = O(2^n).
               n                   level 1
      n-1             n-1          level 2
  n-2     n-2     n-2     n-2      ...
n-3 n-3 n-3 n-3 n-3 n-3 n-3 n-3    ...     
              ...                ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(n). Therefore total complexity is L * O(1) = (n/5) * O(n) = O(n^2)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5

How do I get rid of the "cannot empty the clipboard" error?

I have seen various answers which say when I uninstalled this or that it worked. I think that the uninstall is probably just sorting out an issue in the registry, rather it being an issue with the particular application that is being uninstalled.

I have also seen cases of people saying kill the RDP task but I don't have that and I still have the error.

I have seen cases of people saying clear the clipboard in Excel, but that doesn't work for me - nor does changing the settings in the Clipboard.

I believe that the issue is that an application has a lock on the clipboard and that application is not releasing it. The clipboard is a shared resource, so that implies that each application has to get a lock on it before changing it and then release the lock once it has completed the change, however, it looks like sometimes the lock is not released.

I found that the following cured it. Close down all MS applications including IE and Outlook. Check Task Manager processes to make sure that they are all gone.

Then restart the application where you had the Copy and Paste issue and it will probably then work.

Regards

Paul Simon