Programs & Examples On #Interceptor

The interceptor design pattern allows logic to be "inserted" before, during or after the execution of a piece of code, such as a method.

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

This can happens when one library is loaded into gradle several times. Most often through other connected libraries.

Remove a implementation this library in build.gradle

Then Build -> Clear project

and you can run the assembly)

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Your can use DataSourceBuilder for this purpose.

@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(Environment env) {
    final String datasourceUsername = env.getRequiredProperty("spring.datasource.username");
    final String datasourcePassword = env.getRequiredProperty("spring.datasource.password");
    final String datasourceUrl = env.getRequiredProperty("spring.datasource.url");
    final String datasourceDriver = env.getRequiredProperty("spring.datasource.driver-class-name");
    return DataSourceBuilder
            .create()
            .username(datasourceUsername)
            .password(datasourcePassword)
            .url(datasourceUrl)
            .driverClassName(datasourceDriver)
            .build();
}

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

Try updating your buildToolVersion to 27.0.2 instead of 27.0.3

The error probably occurring because of compatibility issue with build tools

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

For me this problem occurred because I had a some invalid character in my Groovy script. In our case this was an extra blank line after the closing bracket of the script.

No converter found capable of converting from type to type

You may already have this working, but the I created a test project with the classes below allowing you to retrieve the data into an entity, projection or dto.

Projection - this will return the code column twice, once named code and also named text (for example only). As you say above, you don't need the @Projection annotation

import org.springframework.beans.factory.annotation.Value;

public interface DeadlineTypeProjection {
    String getId();

    // can get code and or change name of getter below
    String getCode();

    // Points to the code attribute of entity class
    @Value(value = "#{target.code}")
    String getText();
}

DTO class - not sure why this was inheriting from your base class and then redefining the attributes. JsonProperty just an example of how you'd change the name of the field passed back to a REST end point

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class DeadlineType {
    String id;

    // Use this annotation if you need to change the name of the property that is passed back from controller
    // Needs to be called code to be used in Repository
    @JsonProperty(value = "text")
    String code;

}

Entity class

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@Entity
@Table(name = "deadline_type")
public class ABDeadlineType {

    @Id
    private String id;
    private String code;
}

Repository - your repository extends JpaRepository<ABDeadlineType, Long> but the Id is a String, so updated below to JpaRepository<ABDeadlineType, String>

import com.example.demo.entity.ABDeadlineType;
import com.example.demo.projection.DeadlineTypeProjection;
import com.example.demo.transfer.DeadlineType;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, String> {

    List<ABDeadlineType> findAll();

    List<DeadlineType> findAllDtoBy();

    List<DeadlineTypeProjection> findAllProjectionBy();

}

Example Controller - accesses the repository directly to simplify code

@RequestMapping(value = "deadlinetype")
@RestController
public class DeadlineTypeController {

    private final ABDeadlineTypeRepository abDeadlineTypeRepository;

    @Autowired
    public DeadlineTypeController(ABDeadlineTypeRepository abDeadlineTypeRepository) {
        this.abDeadlineTypeRepository = abDeadlineTypeRepository;
    }

    @GetMapping(value = "/list")
    public ResponseEntity<List<ABDeadlineType>> list() {

        List<ABDeadlineType> types = abDeadlineTypeRepository.findAll();
        return ResponseEntity.ok(types);
    }

    @GetMapping(value = "/listdto")
    public ResponseEntity<List<DeadlineType>> listDto() {

        List<DeadlineType> types = abDeadlineTypeRepository.findAllDtoBy();
        return ResponseEntity.ok(types);
    }

    @GetMapping(value = "/listprojection")
    public ResponseEntity<List<DeadlineTypeProjection>> listProjection() {

        List<DeadlineTypeProjection> types = abDeadlineTypeRepository.findAllProjectionBy();
        return ResponseEntity.ok(types);
    }
}

Hope that helps

Les

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

Use all the jackson dependencies(databind,core, annotations, scala(if you are using spark and scala)) with the same version.. and upgrade the versions to the latest releases..

<dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-scala_2.11</artifactId>
            <version>2.9.4</version>
        </dependency>

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.4</version>
    </dependency>

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

        </dependency>

Note: Use Scala dependency only if you are working with scala. Otherwise it is not needed.

Android dependency has different version for the compile and runtime

_x000D_
_x000D_
    configurations.all {_x000D_
        resolutionStrategy.force_x000D_
        //"com.android.support:appcompat-v7:25.3.1"_x000D_
        //here put the library that made the error with the version you want to use_x000D_
    }
_x000D_
_x000D_
_x000D_

add this to gradle (project) inside allprojects

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

How Spring Security Filter Chain works

Spring security is a filter based framework, it plants a WALL(HttpFireWall) before your application in terms of proxy filters or spring managed beans. Your request has to pass through multiple filters to reach your API.

Sequence of execution in Spring Security

  1. WebAsyncManagerIntegrationFilter Provides integration between the SecurityContext and Spring Web's WebAsyncManager.

  2. SecurityContextPersistenceFilter This filter will only execute once per request, Populates the SecurityContextHolder with information obtained from the configured SecurityContextRepository prior to the request and stores it back in the repository once the request has completed and clearing the context holder.
    Request is checked for existing session. If new request, SecurityContext will be created else if request has session then existing security-context will be obtained from respository.

  3. HeaderWriterFilter Filter implementation to add headers to the current response.

  4. LogoutFilter If request url is /logout(for default configuration) or if request url mathces RequestMatcher configured in LogoutConfigurer then

    • clears security context.
    • invalidates the session
    • deletes all the cookies with cookie names configured in LogoutConfigurer
    • Redirects to default logout success url / or logout success url configured or invokes logoutSuccessHandler configured.
  5. UsernamePasswordAuthenticationFilter

    • For any request url other than loginProcessingUrl this filter will not process further but filter chain just continues.
    • If requested URL is matches(must be HTTP POST) default /login or matches .loginProcessingUrl() configured in FormLoginConfigurer then UsernamePasswordAuthenticationFilter attempts authentication.
    • default login form parameters are username and password, can be overridden by usernameParameter(String), passwordParameter(String).
    • setting .loginPage() overrides defaults
    • While attempting authentication
      • an Authentication object(UsernamePasswordAuthenticationToken or any implementation of Authentication in case of your custom auth filter) is created.
      • and authenticationManager.authenticate(authToken) will be invoked
      • Note that we can configure any number of AuthenticationProvider authenticate method tries all auth providers and checks any of the auth provider supports authToken/authentication object, supporting auth provider will be used for authenticating. and returns Authentication object in case of successful authentication else throws AuthenticationException.
    • If authentication success session will be created and authenticationSuccessHandler will be invoked which redirects to the target url configured(default is /)
    • If authentication failed user becomes un-authenticated user and chain continues.
  6. SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  7. AnonymousAuthenticationFilter Detects if there is no Authentication object in the SecurityContextHolder, if no authentication object found, creates Authentication object (AnonymousAuthenticationToken) with granted authority ROLE_ANONYMOUS. Here AnonymousAuthenticationToken facilitates identifying un-authenticated users subsequent requests.

Debug logs
DEBUG - /app/admin/app-config at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@aeef7b36: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS' 
  1. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  2. FilterSecurityInterceptor
    There will be FilterSecurityInterceptor which comes almost last in the filter chain which gets Authentication object from SecurityContext and gets granted authorities list(roles granted) and it will make a decision whether to allow this request to reach the requested resource or not, decision is made by matching with the allowed AntMatchers configured in HttpSecurityConfiguration.

Consider the exceptions 401-UnAuthorized and 403-Forbidden. These decisions will be done at the last in the filter chain

  • Un authenticated user trying to access public resource - Allowed
  • Un authenticated user trying to access secured resource - 401-UnAuthorized
  • Authenticated user trying to access restricted resource(restricted for his role) - 403-Forbidden

Note: User Request flows not only in above mentioned filters, but there are others filters too not shown here.(ConcurrentSessionFilter,RequestCacheAwareFilter,SessionManagementFilter ...)
It will be different when you use your custom auth filter instead of UsernamePasswordAuthenticationFilter.
It will be different if you configure JWT auth filter and omit .formLogin() i.e, UsernamePasswordAuthenticationFilter it will become entirely different case.


Just For reference. Filters in spring-web and spring-security
Note: refer package name in pic, as there are some other filters from orm and my custom implemented filter.

enter image description here

From Documentation ordering of filters is given as

  • ChannelProcessingFilter
  • ConcurrentSessionFilter
  • SecurityContextPersistenceFilter
  • LogoutFilter
  • X509AuthenticationFilter
  • AbstractPreAuthenticatedProcessingFilter
  • CasAuthenticationFilter
  • UsernamePasswordAuthenticationFilter
  • ConcurrentSessionFilter
  • OpenIDAuthenticationFilter
  • DefaultLoginPageGeneratingFilter
  • DefaultLogoutPageGeneratingFilter
  • ConcurrentSessionFilter
  • DigestAuthenticationFilter
  • BearerTokenAuthenticationFilter
  • BasicAuthenticationFilter
  • RequestCacheAwareFilter
  • SecurityContextHolderAwareRequestFilter
  • JaasApiIntegrationFilter
  • RememberMeAuthenticationFilter
  • AnonymousAuthenticationFilter
  • SessionManagementFilter
  • ExceptionTranslationFilter
  • FilterSecurityInterceptor
  • SwitchUserFilter

You can also refer
most common way to authenticate a modern web app?
difference between authentication and authorization in context of Spring Security?

Spring security CORS Filter

  1. You don't need:

    @Configuration
    @ComponentScan("com.company.praktikant")
    

    @EnableWebSecurity already has @Configuration in it, and I cannot imagine why you put @ComponentScan there.

  2. About CORS filter, I would just put this:

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0); 
        return bean;
    }
    

    Into SecurityConfiguration class and remove configure and configure global methods. You don't need to set allowde orgins, headers and methods twice. Especially if you put different properties in filter and spring security config :)

  3. According to above, your "MyFilter" class is redundant.

  4. You can also remove those:

    final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
    annotationConfigApplicationContext.register(CORSConfig.class);
    annotationConfigApplicationContext.refresh();
    

    From Application class.

  5. At the end small advice - not connected to the question. You don't want to put verbs in URI. Instead of http://localhost:8080/getKunden you should use HTTP GET method on http://localhost:8080/kunden resource. You can learn about best practices for design RESTful api here: http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

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

In my case ; what solved my issue was.....

You may had json like this, the keys without " double quotations....

{ name: "test", phone: "2324234" }

So try any online Json Validator to make sure you have right syntax...

Json Validator Online

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

Quickfix

I had similar issue and I resolved it doing the following

  1. Navigate to jenkins > Manage jenkins > In-process Script Approval
  2. There was a pending command, which I had to approve.

In process approval link in Jenkins 2.61 Alternative 1: Disable sandbox

As this article explains in depth, groovy scripts are run in sandbox mode by default. This means that a subset of groovy methods are allowed to run without administrator approval. It's also possible to run scripts not in sandbox mode, which implies that the whole script needs to be approved by an administrator at once. This preventing users from approving each line at the time.

Running scripts without sandbox can be done by unchecking this checkbox in your project config just below your script: enter image description here

Alternative 2: Disable script security

As this article explains it also possible to disable script security completely. First install the permissive script security plugin and after that change your jenkins.xml file add this argument:

-Dpermissive-script-security.enabled=true

So you jenkins.xml will look something like this:

<executable>..bin\java</executable>
<arguments>-Dpermissive-script-security.enabled=true -Xrs -Xmx4096m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=80 --webroot="%BASE%\war"</arguments>

Make sure you know what you are doing if you implement this!

org.springframework.web.client.HttpClientErrorException: 400 Bad Request

This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.

MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
        headers);
JSONObject jsonObject = null;

try {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            "https://url", HttpMethod.POST, entity,
            String.class);

    if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
        try {
            jsonObject = new JSONObject(responseEntity.getBody());
        } catch (JSONException e) {
            throw new RuntimeException("JSONException occurred");
        }
    }
  } catch (final HttpClientErrorException httpClientErrorException) {
        throw new ExternalCallBadRequestException();
  } catch (HttpServerErrorException httpServerErrorException) {
        throw new ExternalCallServerErrorException(httpServerErrorException);
  } catch (Exception exception) {
        throw new ExternalCallServerErrorException(exception);
    } 

ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.

Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Limiting only to Swagger related resources:

.antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html", "/webjars/springfox-swagger-ui/**");

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

I found some issue about that kind of error

  1. Database username or password not match in the mysql or other other database. Please set application.properties like this

  

# =============================== # = DATA SOURCE # =============================== # Set here configurations for the database connection # Connection url for the database please let me know "[email protected]" spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc # Username and secret spring.datasource.username = root spring.datasource.password = # Keep the connection alive if idle for a long time (needed in production) spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 # =============================== # = JPA / HIBERNATE # =============================== # Use spring.jpa.properties.* for Hibernate native properties (the prefix is # stripped before adding them to the entity manager). # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update): with "update" the database # schema will be automatically updated accordingly to java entities found in # the project spring.jpa.hibernate.ddl-auto = update # Allows Hibernate to generate SQL optimized for a particular DBMS spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Issue no 2.

Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine

Difference between Interceptor and Filter in Spring MVC

Filter: - A filter as the name suggests is a Java class executed by the servlet container for each incoming HTTP request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.

Interceptor: - Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.

Spring Boot REST API - request timeout?

You can configure the Async thread executor for your Springboot REST services. The setKeepAliveSeconds() should consider the execution time for the requests chain. Set the ThreadPoolExecutor's keep-alive seconds. Default is 60. This setting can be modified at runtime, for example through JMX.

@Bean(name="asyncExec")
public Executor asyncExecutor()
{
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(3);
    executor.setMaxPoolSize(3);
    executor.setQueueCapacity(10);
    executor.setThreadNamePrefix("AsynchThread-");
    executor.setAllowCoreThreadTimeOut(true);
    executor.setKeepAliveSeconds(10);
    executor.initialize();

    return executor;
}

Then you can define your REST endpoint as follows

@Async("asyncExec")
@PostMapping("/delayedService")
public CompletableFuture<String> doDelay()
{ 
    String response = service.callDelayedService();
    return CompletableFuture.completedFuture(response);
}

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 !

Adding header to all request with Retrofit 2

In my case addInterceptor()didn't work to add HTTP headers to my request, I had to use addNetworkInterceptor(). Code is as follows:

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addNetworkInterceptor(new AddHeaderInterceptor());

And the interceptor code:

public class AddHeaderInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request.Builder builder = chain.request().newBuilder();
        builder.addHeader("Authorization", "MyauthHeaderContent");

        return chain.proceed(builder.build());
    }
}

This and more examples on this gist

Logging with Retrofit 2

You can also add Facebook's Stetho and look at the network traces in Chrome: http://facebook.github.io/stetho/

final OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
    builder.networkInterceptors().add(new StethoInterceptor());
}

Then open "chrome://inspect" in Chrome...

How to add headers to OkHttp request interceptor?

Kotlin version:

fun okHttpClientFactory(): OkHttpClient {
    return OkHttpClient().newBuilder()
        .addInterceptor { chain ->
            chain.request().newBuilder()
                .addHeader(HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION)
                .build()
                .let(chain::proceed)
        }
        .build()
}

Spring Boot Adding Http Request Interceptors

Since you're using Spring Boot, I assume you'd prefer to rely on Spring's auto configuration where possible. To add additional custom configuration like your interceptors, just provide a configuration or bean of WebMvcConfigurerAdapter.

Here's an example of a config class:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

  @Autowired 
  HandlerInterceptor yourInjectedInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(...)
    ...
    registry.addInterceptor(getYourInterceptor()); 
    registry.addInterceptor(yourInjectedInterceptor);
    // next two should be avoid -- tightly coupled and not very testable
    registry.addInterceptor(new YourInterceptor());
    registry.addInterceptor(new HandlerInterceptor() {
        ...
    });
  }
}

NOTE do not annotate this with @EnableWebMvc, if you want to keep Spring Boots auto configuration for mvc.

Sending cookies with postman

Even after toggling it did not work. I closed and restarted the browser after adding the postman plugin, logged into the site to generate cookies afresh and then it worked for me.

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

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

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

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

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

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

Okay, I got it working using Android Developers guide.

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

Multipart File Upload Using Spring Rest Template + Spring Web MVC

A correct file upload would like this:

HTTP header:

Content-Type: multipart/form-data; boundary=ABCDEFGHIJKLMNOPQ

Http body:

--ABCDEFGHIJKLMNOPQ

Content-Disposition: form-data; name="file"; filename="my.txt"

Content-Type: application/octet-stream

Content-Length: ...

<...file data in base 64...>

--ABCDEFGHIJKLMNOPQ--

and code is like this:

public void uploadFile(File file) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String url = "http://localhost:8080/file/user/upload";
            HttpMethod requestMethod = HttpMethod.POST;

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);


            MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
            ContentDisposition contentDisposition = ContentDisposition
                    .builder("form-data")
                    .name("file")
                    .filename(file.getName())
                    .build();

            fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
            HttpEntity<byte[]> fileEntity = new HttpEntity<>(Files.readAllBytes(file.toPath()), fileMap);

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", fileEntity);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            ResponseEntity<String> response = restTemplate.exchange(url, requestMethod, requestEntity, String.class);

            System.out.println("file upload status code: " + response.getStatusCode());

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

}

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

In my case, I had a OneToOne relation which I was using with @Column by mistake. I changed it to @JoinColumn and added @OneToOne annotation and it fixed the exception.

Launching Spring application Address already in use

You have another process that’s listening on port 8080 which is the default port that’s used by Spring Boot’s web support. You either need to stop that process or configure your app to listen on another port.

You can change the port configuration by adding server.port=4040 (for example) to src/main/resources/application.properties

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

In my case I had a typo (camel case) in my method name. I named it to "findbyLastName" and faced this exception. After I changed it to "findByLastName" exception was gone.

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

The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.

Conclusion

  • USE REQUIRES_NEW if you want to commit what did you do before exception (Local commit)
  • USE REQUIRED if you want to commit only when all processes are done (Global commit) And you just need to ignore "Transaction rolled back because it has been marked as rollback-only" exception. But you need to try-catch out side the caller processNextRegistrationMessage() to have a meaning log.

Let's me explain more detail:

Question: How many Transaction we have? Answer: Only one

Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.

Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction

  1. When persist() method has an exception
  2. Go to the catch outside

    Spring will set the rollBackOnly to true -> it determine we must 
    rollback the caller (processNextRegistrationMessage) also.
    
  3. The persist() will rollback itself first.

  4. Throw an UnexpectedRollbackException to inform that, we need to rollback the caller also.
  5. The try-catch in run() will catch UnexpectedRollbackException and print the stack trace

Question: Why we change PROPAGATION to REQUIRES_NEW, it works?

Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.

Thanks

Transaction marked as rollback only: How do I find the cause

Look for exceptions being thrown and caught in the ... sections of your code. Runtime and rollbacking application exceptions cause rollback when thrown out of a business method even if caught on some other place.

You can use context to find out whether the transaction is marked for rollback.

@Resource
private SessionContext context;

context.getRollbackOnly();

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

As pointed already by @Arun P Johny the root cause of the problem is that at the moment when AuthenticationSuccessEvent is processed SecurityContextHolder is not populated by Authentication object. So any declarative authorization checks (that must get user rights from SecurityContextHolder) will not work. I give you another idea how to solve this problem. There are two ways how you can run your custom code immidiately after successful authentication:

  1. Listen to AuthenticationSuccessEvent
  2. Provide your custom AuthenticationSuccessHandler implementation.

AuthenticationSuccessHandler has one important advantage over first way: SecurityContextHolder will be already populated. So just move your stateService.rowCount() call into loginsuccesshandler.LoginSuccessHandler#onAuthenticationSuccess(...) method and the problem will go away.

Spring Test & Security: How to mock authentication?

Here is an example for those who want to Test Spring MockMvc Security Config using Base64 basic authentication.

String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64(("<username>:<password>").getBytes()));
this.mockMvc.perform(get("</get/url>").header("Authorization", basicDigestHeaderValue).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());

Maven Dependency

    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.3</version>
    </dependency>

Non-static method requires a target

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.

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

The solution is to do exactly what the exception message tells you:

Caused by: org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations)

Remove the deleted object from an associations (sets, lists, or maps) that it is in. In particular, i suspect, from PlayList.PlaylistadMaps. It's not enough to just delete the object, you have to remove it from any cascading collections which refer to it.

In fact, since your collection has orphanRemoval = true, you don't need to delete it explicitly. You just need to remove it from the set.

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

When a servlet 3.0 application starts the container has to scan all the classes for annotations (unless metadata-complete=true). Tomcat uses a fork (no additions, just unused code removed) of Apache Commons BCEL to do this scanning. The web app is failing to start because BCEL has come across something it doesn't understand.

If the applications runs fine on Tomcat 6, adding metadata-complete="true" in your web.xml or declaring your application as a 2.5 application in web.xml will stop the annotation scanning.

At the moment, this looks like a problem in the class being scanned. However, until we know which class is causing the problem and take a closer look we won't know. I'll need to modify Tomcat to log a more useful error message that names the class in question. You can follow progress on this point at: https://issues.apache.org/bugzilla/show_bug.cgi?id=53161

Error creating bean with name

I think it comes from this line in your XML file:

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

Replace it by:

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

It is because your Autowired service is not scanned by Spring since it is not in the right package.

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

In my case, I was defining a bean and autowiring it in the constructor of the same class file.

@SpringBootApplication
public class MyApplication {
    private MyBean myBean;

    public MyApplication(MyBean myBean) {
        this.myBean = myBean;
    }

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

My solution was to move the bean definition to another class file.

@Configuration
public CustomConfig {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

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

I know this post is old, but i ran in the same problem, and i solved it by simply changing my configuration from Java 11 down to Java 8.

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

I also ran into this error when attempting to update an existing row after creating a new one, and spent ages scratching my head, digging through transaction and version logic, until I realised that I had used the wrong type for one of my primary key columns.

I used LocalDate when I should have been using LocalDateTime – I think this was causing hibernate to not be able to distinguish entities, leading to this error.

After changing the key to be a LocalDateTime, the error went away. Also, updating individual rows began to work as well – previously it would fail to find a row for updating, and testing this separate issue was actually what led me to my conclusions regarding the primary key mapping.

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?.

How to log Apache CXF Soap Request and Soap Response using Log4j?

Try this code:

EndpointImpl impl = (EndpointImpl)Endpoint.publish(address, implementor);
    impl.getServer().getEndpoint().getInInterceptors().add(new LoggingInInterceptor());
    impl.getServer().getEndpoint().getOutInterceptors().add(new LoggingOutInterceptor());

Inside the logback.xml you need to put the interface name for webservice:

<appender name="FILE" class="ch.qos.logback.classic.sift.SiftingAppender">
    <discriminator
        class="com.progressoft.ecc.integration.logging.ThreadNameDiscriminator">
        <key>threadName</key>
        <defaultValue>unknown</defaultValue>
    </discriminator>
    <filter class="ch.qos.logback.core.filter.EvaluatorFilter">
        <evaluator>
            <expression>logger.contains("InterfaceWebServiceSoap")</expression>
        </evaluator>
        <OnMismatch>DENY</OnMismatch>
        <OnMatch>NEUTRAL</OnMatch>
    </filter>
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>TRACE</level>
    </filter>
    <sift>
        <appender name="FILE-${threadName}"
            class="ch.qos.logback.core.rolling.RollingFileAppender">
            <File>${LOGGING_PATH}/${threadName}.log</File>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <FileNamePattern>${ARCHIVING_PATH}/%d{yyyy-MM-dd}.${threadName}%i.log.zip
                </FileNamePattern>
                <MaxHistory>30</MaxHistory>
                <TimeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                    <MaxFileSize>50MB</MaxFileSize>
                </TimeBasedFileNamingAndTriggeringPolicy>
            </rollingPolicy>
            <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
                <Pattern>%date{dd-MM-yyyy HH:mm:ss.SSS} | %5level | %-60([%logger{53}:%line]): %msg %ex{full} %n</Pattern>
            </encoder>
        </appender>
    </sift>
</appender>

<root>
    <level value="ALL" />
    <appender-ref ref="FILE" />
</root>

inject bean reference into a Quartz job in Spring?

This is a quite an old post which is still useful. All the solutions that proposes these two had little condition that not suite all:

  • SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); This assumes or requires it to be a spring - web based project
  • AutowiringSpringBeanJobFactory based approach mentioned in previous answer is very helpful, but the answer is specific to those who don't use pure vanilla quartz api but rather Spring's wrapper for the quartz to do the same.

If you want to remain with pure Quartz implementation for scheduling(Quartz with Autowiring capabilities with Spring), I was able to do it as follows:

I was looking to do it quartz way as much as possible and thus little hack proves helpful.

 public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory{

    private AutowireCapableBeanFactory beanFactory;

    public AutowiringSpringBeanJobFactory(final ApplicationContext applicationContext){
        beanFactory = applicationContext.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        beanFactory.initializeBean(job, job.getClass().getName());
        return job;
    }
}


@Configuration
public class SchedulerConfig {   
    @Autowired private ApplicationContext applicationContext;

    @Bean
    public AutowiringSpringBeanJobFactory getAutowiringSpringBeanJobFactory(){
        return new AutowiringSpringBeanJobFactory(applicationContext);
    }
}


private void initializeAndStartScheduler(final Properties quartzProperties)
            throws SchedulerException {
        //schedulerFactory.initialize(quartzProperties);
        Scheduler quartzScheduler = schedulerFactory.getScheduler();

        //Below one is the key here. Use the spring autowire capable job factory and inject here
        quartzScheduler.setJobFactory(autowiringSpringBeanJobFactory);
        quartzScheduler.start();
    }

quartzScheduler.setJobFactory(autowiringSpringBeanJobFactory); gives us an autowired job instance. Since AutowiringSpringBeanJobFactory implicitly implements a JobFactory, we now enabled an auto-wireable solution. Hope this helps!

CXF: No message body writer found for class - automatically mapping non-simple resources

It isn't quite out of the box but CXF does support JSON bindings to rest services. See cxf jax-rs json docs here. You'll still need to do some minimal configuration to have the provider available and you need to be familiar with jettison if you want to have more control over how the JSON is formed.

EDIT: Per comment request, here is some code. I don't have a lot of experience with this but the following code worked as an example in a quick test system.

//TestApi parts
@GET
@Path ( "test" )
@Produces ( "application/json" )
public Demo getDemo () {
    Demo d = new Demo ();
    d.id = 1;
    d.name = "test";
    return d;
}

//client config for a TestApi interface
List providers = new ArrayList ();
JSONProvider jsonProvider = new JSONProvider ();
Map<String, String> map = new HashMap<String, String> ();
map.put ( "http://www.myserviceapi.com", "myapi" );
jsonProvider.setNamespaceMap ( map );
providers.add ( jsonProvider );
TestApi proxy = JAXRSClientFactory.create ( url, TestApi.class, 
    providers, true );

Demo d = proxy.getDemo ();
if ( d != null ) {
    System.out.println ( d.id + ":" + d.name );
}

//the Demo class
@XmlRootElement ( name = "demo", namespace = "http://www.myserviceapi.com" )
@XmlType ( name = "demo", namespace = "http://www.myserviceapi.com", 
    propOrder = { "name", "id" } )
@XmlAccessorType ( XmlAccessType.FIELD )
public class Demo {

    public String name;
    public int id;
}

Notes:

  1. The providers list is where you code configure the JSON provider on the client. In particular, you see the namespace mapping. This needs to match what is on your server side configuration. I don't know much about Jettison options so I'm not much help on manipulating all of the various knobs for controlling the marshalling process.
  2. Jettison in CXF works by marshalling XML from a JAXB provider into JSON. So you have to ensure that the payload objects are all marked up (or otherwise configured) to marshall as application/xml before you can have them marshall as JSON. If you know of a way around this (other than writing your own message body writer), I'd love to hear about it.
  3. I use spring on the server so my configuration there is all xml stuff. Essentially, you need to go through the same process to add the JSONProvider to the service with the same namespace configuration. Don't have code for that handy but I imagine it will mirror the client side fairly well.

This is a bit dirty as an example but will hopefully get you going.

Edit2: An example of a message body writer that is based on xstream to avoid jaxb.

@Produces ( "application/json" )
@Consumes ( "application/json" )
@Provider
public class XstreamJsonProvider implements MessageBodyReader<Object>,
    MessageBodyWriter<Object> {

@Override
public boolean isWriteable ( Class<?> type, Type genericType, 
    Annotation[] annotations, MediaType mediaType ) {
    return MediaType.APPLICATION_JSON_TYPE.equals ( mediaType ) 
        && type.equals ( Demo.class );
}

@Override
public long getSize ( Object t, Class<?> type, Type genericType, 
    Annotation[] annotations, MediaType mediaType ) {
    // I'm being lazy - should compute the actual size
    return -1;
}

@Override
public void writeTo ( Object t, Class<?> type, Type genericType, 
    Annotation[] annotations, MediaType mediaType, 
    MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream ) 
    throws IOException, WebApplicationException {
    // deal with thread safe use of xstream, etc.
    XStream xstream = new XStream ( new JettisonMappedXmlDriver () );
    xstream.setMode ( XStream.NO_REFERENCES );
    // add safer encoding, error handling, etc.
    xstream.toXML ( t, entityStream );
}

@Override
public boolean isReadable ( Class<?> type, Type genericType, 
    Annotation[] annotations, MediaType mediaType ) {
    return MediaType.APPLICATION_JSON_TYPE.equals ( mediaType ) 
        && type.equals ( Demo.class );
}

@Override
public Object readFrom ( Class<Object> type, Type genericType, 
    Annotation[] annotations, MediaType mediaType, 
    MultivaluedMap<String, String> httpHeaders, InputStream entityStream ) 
    throws IOException, WebApplicationException {
    // add error handling, etc.
    XStream xstream = new XStream ( new JettisonMappedXmlDriver () );
    return xstream.fromXML ( entityStream );
}
}

//now your client just needs this
List providers = new ArrayList ();
XstreamJsonProvider jsonProvider = new XstreamJsonProvider ();
providers.add ( jsonProvider );
TestApi proxy = JAXRSClientFactory.create ( url, TestApi.class, 
    providers, true );

Demo d = proxy.getDemo ();
if ( d != null ) {
    System.out.println ( d.id + ":" + d.name );
}

The sample code is missing the parts for robust media type support, error handling, thread safety, etc. But, it ought to get you around the jaxb issue with minimal code.

EDIT 3 - sample server side configuration As I said before, my server side is spring configured. Here is a sample configuration that works to wire in the provider:

<?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:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
    http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">

<import resource="classpath:META-INF/cxf/cxf.xml" />

<jaxrs:server id="TestApi">
    <jaxrs:serviceBeans>
        <ref bean="testApi" />
    </jaxrs:serviceBeans>
    <jaxrs:providers>
        <bean id="xstreamJsonProvider" class="webtests.rest.XstreamJsonProvider" />
    </jaxrs:providers>
</jaxrs:server>

<bean id="testApi" class="webtests.rest.TestApi">
</bean>

</beans>

I have also noted that in the latest rev of cxf that I'm using there is a difference in the media types, so the example above on the xstream message body reader/writer needs a quick modification where isWritable/isReadable change to:

return MediaType.APPLICATION_JSON_TYPE.getType ().equals ( mediaType.getType () )
    && MediaType.APPLICATION_JSON_TYPE.getSubtype ().equals ( mediaType.getSubtype () )
    && type.equals ( Demo.class );

EDIT 4 - non-spring configuration Using your servlet container of choice, configure

org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet

with at least 2 init params of:

jaxrs.serviceClasses
jaxrs.providers

where the serviceClasses is a space separated list of the service implementations you want bound, such as the TestApi mentioned above and the providers is a space separated list of message body providers, such as the XstreamJsonProvider mentioned above. In tomcat you might add the following to web.xml:

<servlet>
    <servlet-name>cxfservlet</servlet-name>
    <servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
    <init-param>
        <param-name>jaxrs.serviceClasses</param-name>
        <param-value>webtests.rest.TestApi</param-value>
    </init-param>
    <init-param>
        <param-name>jaxrs.providers</param-name>
        <param-value>webtests.rest.XstreamJsonProvider</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

That is pretty much the quickest way to run it without spring. If you are not using a servlet container, you would need to configure the JAXRSServerFactoryBean.setProviders with an instance of XstreamJsonProvider and set the service implementation via the JAXRSServerFactoryBean.setResourceProvider method. Check the CXFNonSpringJaxrsServlet.init method to see how they do it when setup in a servlet container.

That ought to get you going no matter your scenario.

Configure hibernate to connect to database via JNDI Datasource

Apparently, you did it right. But here is a list of things you'll need with examples from a working application:

1) A context.xml file in META-INF, specifying your data source:

<Context>
    <Resource 
        name="jdbc/DsWebAppDB" 
        auth="Container" 
        type="javax.sql.DataSource" 
        username="sa" 
        password="" 
        driverClassName="org.h2.Driver" 
        url="jdbc:h2:mem:target/test/db/h2/hibernate" 
        maxActive="8" 
        maxIdle="4"/>
</Context>

2) web.xml which tells the container that you are using this resource:

<resource-env-ref>
    <resource-env-ref-name>jdbc/DsWebAppDB</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>

3) Hibernate configuration which consumes the data source. In this case, it's a persistence.xml, but it's similar in hibernate.cfg.xml

<persistence-unit name="dswebapp">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
        <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/DsWebAppDB"/>
    </properties>
</persistence-unit>

Gson: How to exclude specific fields from Serialization without annotations

This what I always use:

The default behaviour implemented in Gson is that null object fields are ignored.

Means Gson object does not serialize fields with null values to JSON. If a field in a Java object is null, Gson excludes it.

You can use this function to convert some object to null or well set by your own

     /**
   * convert object to json
   */
  public String toJson(Object obj) {
    // Convert emtpy string and objects to null so we don't serialze them
    setEmtpyStringsAndObjectsToNull(obj);
    return gson.toJson(obj);
  }

  /**
   * Sets all empty strings and objects (all fields null) including sets to null.
   *
   * @param obj any object
   */
  public void setEmtpyStringsAndObjectsToNull(Object obj) {
    for (Field field : obj.getClass().getDeclaredFields()) {
      field.setAccessible(true);
      try {
        Object fieldObj = field.get(obj);
        if (fieldObj != null) {
          Class fieldType = field.getType();
          if (fieldType.isAssignableFrom(String.class)) {
            if(fieldObj.equals("")) {
              field.set(obj, null);
            }
          } else if (fieldType.isAssignableFrom(Set.class)) {
            for (Object item : (Set) fieldObj) {
              setEmtpyStringsAndObjectsToNull(item);
            }
            boolean setFielToNull = true;
            for (Object item : (Set) field.get(obj)) {
              if(item != null) {
                setFielToNull = false;
                break;
              }
            }
            if(setFielToNull) {
              setFieldToNull(obj, field);
            }
          } else if (!isPrimitiveOrWrapper(fieldType)) {
            setEmtpyStringsAndObjectsToNull(fieldObj);
            boolean setFielToNull = true;
            for (Field f : fieldObj.getClass().getDeclaredFields()) {
              f.setAccessible(true);
              if(f.get(fieldObj) != null) {
                setFielToNull = false;
                break;
              }
            }
            if(setFielToNull) {
              setFieldToNull(obj, field);
            }
          }
        }
      } catch (IllegalAccessException e) {
        System.err.println("Error while setting empty string or object to null: " + e.getMessage());
      }
    }
  }

  private void setFieldToNull(Object obj, Field field) throws IllegalAccessException {
    if(!Modifier.isFinal(field.getModifiers())) {
      field.set(obj, null);
    }
  }

  private boolean isPrimitiveOrWrapper(Class fieldType)  {
    return fieldType.isPrimitive()
        || fieldType.isAssignableFrom(Integer.class)
        || fieldType.isAssignableFrom(Boolean.class)
        || fieldType.isAssignableFrom(Byte.class)
        || fieldType.isAssignableFrom(Character.class)
        || fieldType.isAssignableFrom(Float.class)
        || fieldType.isAssignableFrom(Long.class)
        || fieldType.isAssignableFrom(Double.class)
        || fieldType.isAssignableFrom(Short.class);
  }

Could not resolve Spring property placeholder

You may have more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer in your application. Try setting a breakpoint on the setLocations method of the superclass and see if it's called more than once at application startup. If there is more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer, you might need to look at configuring the ignoreUnresolvablePlaceholders property so that your application will start up cleanly.

How to manually set an authenticated user in Spring Security / SpringMVC

I had the same problem as you a while back. I can't remember the details but the following code got things working for me. This code is used within a Spring Webflow flow, hence the RequestContext and ExternalContext classes. But the part that is most relevant to you is the doAutoLogin method.

public String registerUser(UserRegistrationFormBean userRegistrationFormBean,
                           RequestContext requestContext,
                           ExternalContext externalContext) {

    try {
        Locale userLocale = requestContext.getExternalContext().getLocale();
        this.userService.createNewUser(userRegistrationFormBean, userLocale, Constants.SYSTEM_USER_ID);
        String emailAddress = userRegistrationFormBean.getChooseEmailAddressFormBean().getEmailAddress();
        String password = userRegistrationFormBean.getChoosePasswordFormBean().getPassword();
        doAutoLogin(emailAddress, password, (HttpServletRequest) externalContext.getNativeRequest());
        return "success";

    } catch (EmailAddressNotUniqueException e) {
        MessageResolver messageResolvable 
                = new MessageBuilder().error()
                                      .source(UserRegistrationFormBean.PROPERTYNAME_EMAIL_ADDRESS)
                                      .code("userRegistration.emailAddress.not.unique")
                                      .build();
        requestContext.getMessageContext().addMessage(messageResolvable);
        return "error";
    }

}


private void doAutoLogin(String username, String password, HttpServletRequest request) {

    try {
        // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = this.authenticationProvider.authenticate(token);
        logger.debug("Logging in with [{}]", authentication.getPrincipal());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (Exception e) {
        SecurityContextHolder.getContext().setAuthentication(null);
        logger.error("Failure in autoLogin", e);
    }

}

Redirect on Ajax Jquery Call

For ExpressJs router:

router.post('/login', async(req, res) => {
    return res.send({redirect: '/yoururl'});
})

Client-side:

    success: function (response) {
        if (response.redirect) {
            window.location = response.redirect
        }
    },

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

In our case we finally found out the root cause of StaleStateException.

In fact we were deleting the row twice in a single hibernate session. Earlier we were using ojdbc6 lib, and this was ok in this version.

But when we upgraded to odjc7 or ojdbc8, deleting records twice was throwing exception. There was bug in our code where we were deleting twice, but that was not evident in ojdbc6.

We were able to reproduce with this piece of code:

Detail detail = getDetail(Long.valueOf(1396451));
session.delete(detail);
session.flush();
session.delete(detail);
session.flush();

On first flush hibernate goes and makes changes in database. During 2nd flush hibernate compares session's object with actual table's record, but could not find one, hence the exception.

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

You have an incompatibility between the version of ASM required by Hibernate (asm-1.5.3.jar) and the one required by Spring. But, actually, I wonder why you have asm-2.2.3.jar on your classpath (ASM is bundled in spring.jar and spring-core.jar to avoid such problems AFAIK). See HHH-2222.

"NoClassDefFoundError: Could not initialize class" error

NoClassDefFound error is a nebulous error and is often hiding a more serious issue. It is not the same as ClassNotFoundException (which is thrown when the class is just plain not there).

NoClassDefFound may indicate the class is not there, as the javadocs indicate, but it is typically thrown when, after the classloader has loaded the bytes for the class and calls "defineClass" on them. Also carefully check your full stack trace for other clues or possible "cause" Exceptions (though your particular backtrace shows none).

The first place to look when you get a NoClassDefFoundError is in the static bits of your class i.e. any initialization that takes place during the defining of the class. If this fails it will throw a NoClassDefFoundError - it's supposed to throw an ExceptionInInitializerError and indicate the details of the problem but in my experience, these are rare. It will only do the ExceptionInInitializerError the first time it tries to define the class, after that it will just throw NoClassDefFound. So look at earlier logs.

I would thus suggest looking at the code in that HibernateTransactionInterceptor line and seeing what it is requiring. It seems that it is unable to define the class SpringFactory. So maybe check the initialization code in that class, that might help. If you can debug it, stop it at the last line above (17) and debug into so you can try find the exact line that is causing the exception. Also check higher up in the log, if you very lucky there might be an ExceptionInInitializerError.

How to delete all records from table in sqlite with Android?

db.delete(TABLE_NAME, null, null);

or, if you want the function to return the count of deleted rows,

db.delete(TABLE_NAME, "1", null);

From the documentation of SQLiteDatabase delete method:

To remove all rows and get a count pass "1" as the whereClause.

What JSON library to use in Scala?

Jawn is a very flexible JSON parser library in Scala. It also allows generation of custom ASTs; you just need to supply it with a small trait to map to the AST.

Worked great for a recent project that needed a little bit of JSON parsing.

Do standard windows .ini files allow comments?

I have seen comments in INI files, so yes. Please refer to this Wikipedia article. I could not find an official specification, but that is the correct syntax for comments, as many game INI files had this as I remember.

Edit

The API returns the Value and the Comment (forgot to mention this in my reply), just construct and example INI file and call the API on this (with comments) and you can see how this is returned.

Increment variable value by 1 ( shell programming)

you can use bc as it can also do floats

var=$(echo "1+2"|bc)

How to cancel a pull request on github?

If you sent a pull request on a repository where you don't have the rights to close it, you can delete the branch from where the pull request originated. That will cancel the pull request.

How to do vlookup and fill down (like in Excel) in R?

Starting with:

houses <- read.table(text="Semi            1
Single          2
Row             3
Single          2
Apartment       4
Apartment       4
Row             3",col.names=c("HouseType","HouseTypeNo"))

... you can use

as.numeric(factor(houses$HouseType))

... to give a unique number for each house type. You can see the result here:

> houses2 <- data.frame(houses,as.numeric(factor(houses$HouseType)))
> houses2
  HouseType HouseTypeNo as.numeric.factor.houses.HouseType..
1      Semi           1                                    3
2    Single           2                                    4
3       Row           3                                    2
4    Single           2                                    4
5 Apartment           4                                    1
6 Apartment           4                                    1
7       Row           3                                    2

... so you end up with different numbers on the rows (because the factors are ordered alphabetically) but the same pattern.

(EDIT: the remaining text in this answer is actually redundant. It occurred to me to check and it turned out that read.table() had already made houses$HouseType into a factor when it was read into the dataframe in the first place).

However, you may well be better just to convert HouseType to a factor, which would give you all the same benefits as HouseTypeNo, but would be easier to interpret because the house types are named rather than numbered, e.g.:

> houses3 <- houses
> houses3$HouseType <- factor(houses3$HouseType)
> houses3
  HouseType HouseTypeNo
1      Semi           1
2    Single           2
3       Row           3
4    Single           2
5 Apartment           4
6 Apartment           4
7       Row           3
> levels(houses3$HouseType)
[1] "Apartment" "Row"       "Semi"      "Single"  

Free Online Team Foundation Server

Readify used to run their TFSNow hosted TFS service, but I don't think it's going any longer. The only others I've heard of, apart from CodePlex, aren't free:

Print the data in ResultSet along with column names

1) Instead of PreparedStatement use Statement

2) After executing query in ResultSet, extract values with the help of rs.getString() as :

Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
    rs.getString(1); //or rs.getString("column name");
}

Set Date in a single line

You could use

new SimpleDateFormat( "yyyyMMdd" ).parse( "20100520" )

How to output git log with the first line only?

Have you tried this?

git log --pretty=oneline --abbrev-commit

The problem is probably that you are missing an empty line after the first line. The command above usually works for me, but I just tested on a commit without empty second line. I got the same result as you: the whole message on one line.

Empty second line is a standard in git commit messages. The behaviour you see was probably implemented on purpose.

The first line of a commit message is meant to be a short description. If you cannot make it in a single line you can use several, but git considers everything before the first empty line to be the "short description". oneline prints the whole short description, so all your 3 rows.

How to view log output using docker-compose run?

If you want to see output logs from all the services in your terminal.

docker-compose logs -t -f --tail <no of lines> 

Eg.: Say you would like to log output of last 5 lines from all service

docker-compose logs -t -f --tail 5

If you wish to log output from specific services then it can be done as below:

docker-compose logs -t -f --tail <no of lines> <name-of-service1> <name-of-service2> ... <name-of-service N>

Usage:

Eg. say you have API and portal services then you can do something like below :

docker-compose logs -t -f --tail 5 portal api

Where 5 represents last 5 lines from both logs.

Ref: https://docs.docker.com/v17.09/engine/admin/logging/view_container_logs/

Simple insecure two-way data "obfuscation"?

[EDIT] Years later, I've come back to say: don't do this! See What's wrong with XOR encryption? for details.

A very simple, easy two-way encrytpion is XOR encryption.

  1. Come up with a password. Let's have it be mypass.
  2. Convert the password into binary (according to ASCII). The password becomes 01101101 01111001 01110000 01100001 01110011 01110011.
  3. Take the message you want to encode. Convert that into binary, also.
  4. Look at the length of the message. If the message length is 400 bytes, turn the password into a 400 byte string by repeating it over and over again. It would become 01101101 01111001 01110000 01100001 01110011 01110011 01101101 01111001 01110000 01100001 01110011 01110011 01101101 01111001 01110000 01100001 01110011 01110011... (or mypassmypassmypass...)
  5. XOR the message with the long password.
  6. Send the result.
  7. Another time, XOR the encrypted message with the same password (mypassmypassmypass...).
  8. There's your message!

How to change the default charset of a MySQL table?

The ALTER TABLE MySQL command should do the trick. The following command will change the default character set of your table and the character set of all its columns to UTF8.

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

This command will convert all text-like columns in the table to the new character set. Character sets use different amounts of data per character, so MySQL will convert the type of some columns to ensure there's enough room to fit the same number of characters as the old column type.

I recommend you read the ALTER TABLE MySQL documentation before modifying any live data.

Display help message with python argparse when script is called without any arguments

Set your positional arguments with nargs, and check if positional args are empty.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?')
args = parser.parse_args()
if not args.file:
    parser.print_help()

Reference Python nargs

CSS Input Type Selectors - Possible to have an "or" or "not" syntax?

CSS3 has a pseudo-class called :not()

_x000D_
_x000D_
input:not([type='checkbox']) {    
    visibility: hidden;
}
_x000D_
<p>If <code>:not()</code> is supported, you'll only see the checkbox.</p>
                                      
<ul>
  <li>text: (<input type="text">)</li>  
  <li>password (<input type="password">)</li>       
  <li>checkbox (<input type="checkbox">)</li> 
 </ul>
_x000D_
_x000D_
_x000D_


Multiple selectors

As Vincent mentioned, it's possible to string multiple :not()s together:

input:not([type='checkbox']):not([type='submit'])

CSS4, which is supported in many of the latest browser releases, allows multiple selectors in a :not()

input:not([type='checkbox'],[type='submit'])

Legacy support

All modern browsers support the CSS3 syntax. At the time this question was asked, we needed a fall-back for IE7 and IE8. One option was to use a polyfill like IE9.js. Another was to exploit the cascade in CSS:

input {
   // styles for most inputs
}   

input[type=checkbox] {
  // revert back to the original style
} 

input.checkbox {
  // for completeness, this would have worked even in IE3!
} 

How do I suspend painting for a control and its children?

I usually use a little modified version of ngLink's answer.

public class MyControl : Control
{
    private int suspendCounter = 0;

    private void SuspendDrawing()
    {
        if(suspendCounter == 0) 
            SendMessage(this.Handle, WM_SETREDRAW, false, 0);
        suspendCounter++;
    }

    private void ResumeDrawing()
    {
        suspendCounter--; 
        if(suspendCounter == 0) 
        {
            SendMessage(this.Handle, WM_SETREDRAW, true, 0);
            this.Refresh();
        }
    }
}

This allows suspend/resume calls to be nested. You must make sure to match each SuspendDrawing with a ResumeDrawing. Hence, it wouldn't probably be a good idea to make them public.

Max length UITextField

You need to check whether the existing string plus the input is greater than 10.

   func textField(textField: UITextField!,shouldChangeCharactersInRange range: NSRange,    replacementString string: String!) -> Bool {
      NSUInteger newLength = textField.text.length + string.length - range.length;
      return !(newLength > 10)
   }

How to insert a column in a specific position in oracle without dropping and recreating the table?

Amit-

I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:

CREATE TABLE MY_TEMP_TABLE AS
SELECT *
FROM TABLE_TO_CHANGE;

Drop the table you want to add columns to:

DROP TABLE TABLE_TO_CHANGE;

It's at the point you could rebuild the existing table from scratch adding in the columns where you wish. Let's assume for this exercise you want to add the columns named "COL2 and COL3".

Now insert the data back into the new table:

INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4) 
SELECT COL1, 'Foo', 'Bar', COL4
FROM MY_TEMP_TABLE;

When the data is inserted into your "new-old" table, you can drop the temp table.

DROP TABLE MY_TEMP_TABLE;

This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.

-CJ

How to use Servlets and Ajax?

I will show you a whole example of servlet & how do ajax call.

Here, we are going to create the simple example to create the login form using servlet.

index.html

<form>  
   Name:<input type="text" name="username"/><br/><br/>  
   Password:<input type="password" name="userpass"/><br/><br/>  
   <input type="button" value="login"/>  
</form>  

Here is ajax Sample

       $.ajax
        ({
            type: "POST",           
            data: 'LoginServlet='+name+'&name='+type+'&pass='+password,
            url: url,
        success:function(content)
        {
                $('#center').html(content);           
            }           
        });

LoginServlet Servlet Code :-

    package abc.servlet;

import java.io.File;


public class AuthenticationServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {   
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        try{
        HttpSession session = request.getSession();
        String username = request.getParameter("name");
        String password = request.getParameter("pass");

                /// Your Code
out.println("sucess / failer")
        } catch (Exception ex) {
            // System.err.println("Initial SessionFactory creation failed.");
            ex.printStackTrace();
            System.exit(0);
        } 
    }
}

'Syntax Error: invalid syntax' for no apparent reason

I noticed that invalid syntax error for no apparent reason can be caused by using space in:

print(f'{something something}')

Python IDLE seems to jump and highlight a part of the first line for some reason (even if the first line happens to be a comment), which is misleading.

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

As help to anybody that had the same problem as me, I accidentally mistyped the implementation type instead of the interface e.g.

var mockFileBrowser = new Mock<FileBrowser>();

instead of

var mockFileBrowser = new Mock<IFileBrowser>();

Two dimensional array list

A 2d array is simply an array of arrays. The analog for lists is simply a List of Lists.

ArrayList<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();

I'll admit, it's not a pretty solution, especially if you go for a 3 or more dimensional structure.

Convert categorical data in pandas dataframe

For converting categorical data in column C of dataset data, we need to do the following:

from sklearn.preprocessing import LabelEncoder 
labelencoder= LabelEncoder() #initializing an object of class LabelEncoder
data['C'] = labelencoder.fit_transform(data['C']) #fitting and transforming the desired categorical column.

2D cross-platform game engine for Android and iOS?

LibGDX is one of the best engines I've ever used, works on almost all platforms, and performs twice as fast as cocos2d-x in most tests I've done. You can use any JVM language you like. Here's a 13 part tutorial in Java, and here's a bunch using jruby. There's a good skeletal animation tool that works with it here, and it has baked in support for tiled TMX maps as well. The ui framework is awesome, and it has a scene graph and actor style API similar to cocos2d scenes, sprites and actions. The community is awesome, updates are frequent, and the documentation is good. Don't let the java part scare you, it's fast, and you can use jruby or scala or whatever you like. I highly recommend it for 2d or 3d work, it supports both.

display HTML page after loading complete

put an overlay on the page

#loading-mask {
    background-color: white;
    height: 100%;
    left: 0;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 9999;
}

and then delete that element in a window.onload handler or, hide it

window.onload=function() {
    document.getElementById('loading-mask').style.display='none';
}

Of course you should use your javascript library (jquery,prototype..) specific onload handler if you are using a library.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

How to enable SOAP on CentOS

On CentOS 7, the following works:

yum install php-soap

This will automatically create a soap.ini under /etc/php.d.

The extension itself for me lives in /usr/lib64/php/modules. You can confirm your extension directory by doing:

php -i | grep extension_dir

Once this has been installed, you can simply restart Apache using the new service manager like so:

systemctl restart httpd

Thanks to Matt Browne for the info about /etc/php.d.

UILabel Align Text to center

In xamarin ios suppose your label name is title then do the following

title.TextAlignment = UITextAlignment.Center;

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

<a href="#"><button>Link Text</button></a>

You asked for a link that looks like a button, so use a link and a button :-) This will preserve default browser button styling. The button by itself does nothing, but clicking it activates its parent link.

Demo:

_x000D_
_x000D_
<a href="http://stackoverflow.com"><button>Link Text</button></a>
_x000D_
_x000D_
_x000D_

moment.js - UTC gives wrong date

Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.

The correct way to parse an input moment as UTC in the format you provided would be like this:

moment.utc('07-18-2013', 'MM-DD-YYYY')

Refer to this documentation.

If you want to then format it differently for output, you would do this:

moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')

You do not need to call toString explicitly.

Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

There is no way to retrieve localStorage, sessionStorage or cookie values via javascript in the browser after they've been deleted via javascript.

If what you're really asking is if there is some other way (from outside the browser) to recover that data, that's a different question and the answer will entirely depend upon the specific browser and how it implements the storage of each of those types of data.

For example, Firefox stores cookies as individual files. When a cookie is deleted, its file is deleted. That means that the cookie can no longer be accessed via the browser. But, we know that from outside the browser, using system tools, the contents of deleted files can sometimes be retrieved.

If you wanted to look into this further, you'd have to discover how each browser stores each data type on each platform of interest and then explore if that type of storage has any recovery strategy.

Illegal Escape Character "\"

The character '\' is a special character and needs to be escaped when used as part of a String, e.g., "\". Here is an example of a string comparison using the '\' character:

if (invName.substring(j,k).equals("\\")) {...}

You can also perform direct character comparisons using logic similar to the following:

if (invName.charAt(j) == '\\') {...}

Prevent HTML5 video from being downloaded (right-click saved)?

We ended up using AWS CloudFront with expiring URLs. The video will load, but by the time the user right clicks and chooses Save As the video url they initially received has expired. Do a search for CloudFront Origin Access Identity.

Producing the video url requires a key pair which can be created in the AWS CLI. FYI this is not my code but it works great!

$resource = 'http://cdn.yourwebsite.com/videos/yourvideourl.mp4';
$timeout = 4;

//This comes from key pair you generated for cloudfront
$keyPairId = "AKAJSDHFKASWERASDF";

$expires = time() + $timeout; //Time out in seconds
$json = '{"Statement":[{"Resource":"'.$resource.'","Condition" {"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';     

//Read Cloudfront Private Key Pair
$fp=fopen("/absolute/path/to/your/cloudfront_privatekey.pem","r"); 
$priv_key=fread($fp,8192); 
fclose($fp); 

//Create the private key
$key = openssl_get_privatekey($priv_key);
if(!$key)
{
    echo "<p>Failed to load private key!</p>";
    return;
}

//Sign the policy with the private key
if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
{
    echo '<p>Failed to sign policy: '.openssl_error_string().'</p>';
    return;
}

//Create url safe signed policy
$base64_signed_policy = base64_encode($signed_policy);
$signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy);

//Construct the URL
$url = $resource.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;

return '<div class="videowrapper" ><video autoplay controls style="width:100%!important;height:auto!important;"><source src="'.$url.'" type="video/mp4">Your browser does not support the video tag.</video></div>';

How to post object and List using postman

I also had a similar question, sharing the below example if it helps.

My Controller:

@RequestMapping(value = {"/batchDeleteIndex"}, method = RequestMethod.POST)
@ResponseBody
public BaseResponse batchDeleteIndex(@RequestBody List<String> datasetQnames)

Postman: Set the Body type to raw and add header Content-Type: application/json

["aaa","bbb","ccc"]

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

Updated Answer

Trying to open multiple panels of a collapse control that is setup as an accordion i.e. with the data-parent attribute set, can prove quite problematic and buggy (see this question on multiple panels open after programmatically opening a panel)

Instead, the best approach would be to:

  1. Allow each panel to toggle individually
  2. Then, enforce the accordion behavior manually where appropriate.

To allow each panel to toggle individually, on the data-toggle="collapse" element, set the data-target attribute to the .collapse panel ID selector (instead of setting the data-parent attribute to the parent control. You can read more about this in the question Modify Twitter Bootstrap collapse plugin to keep accordions open.

Roughly, each panel should look like this:

<div class="panel panel-default">
   <div class="panel-heading">
         <h4 class="panel-title"
             data-toggle="collapse" 
             data-target="#collapseOne">
             Collapsible Group Item #1
         </h4>
    </div>
    <div id="collapseOne" 
         class="panel-collapse collapse">
        <div class="panel-body"></div>
    </div>
</div>

To manually enforce the accordion behavior, you can create a handler for the collapse show event which occurs just before any panels are displayed. Use this to ensure any other open panels are closed before the selected one is shown (see this answer to multiple panels open). You'll also only want the code to execute when the panels are active. To do all that, add the following code:

$('#accordion').on('show.bs.collapse', function () {
    if (active) $('#accordion .in').collapse('hide');
});

Then use show and hide to toggle the visibility of each of the panels and data-toggle to enable and disable the controls.

$('#collapse-init').click(function () {
    if (active) {
        active = false;
        $('.panel-collapse').collapse('show');
        $('.panel-title').attr('data-toggle', '');
        $(this).text('Enable accordion behavior');
    } else {
        active = true;
        $('.panel-collapse').collapse('hide');
        $('.panel-title').attr('data-toggle', 'collapse');
        $(this).text('Disable accordion behavior');
    }
});

Working demo in jsFiddle

Win32Exception (0x80004005): The wait operation timed out

My Table didn't have primary key then I had time out error. after set key sloved.

How does one generate a random number in Apple's Swift language?

Details

xCode 9.1, Swift 4

Math oriented solution (1)

import Foundation

class Random {

    subscript<T>(_ min: T, _ max: T) -> T where T : BinaryInteger {
        get {
            return rand(min-1, max+1)
        }
    }
}

let rand = Random()

func rand<T>(_ min: T, _ max: T) -> T where T : BinaryInteger {
    let _min = min + 1
    let difference = max - _min
    return T(arc4random_uniform(UInt32(difference))) + _min
}

Usage of solution (1)

let x = rand(-5, 5)       // x = [-4, -3, -2, -1, 0, 1, 2, 3, 4]
let x = rand[0, 10]       // x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Programmers oriented solution (2)

Do not forget to add Math oriented solution (1) code here

import Foundation

extension CountableRange where Bound : BinaryInteger {

    var random: Bound {
        return rand(lowerBound-1, upperBound)
    }
}

extension CountableClosedRange where Bound : BinaryInteger {

    var random: Bound {
        return rand[lowerBound, upperBound]
    }
}

Usage of solution (2)

let x = (-8..<2).random           // x = [-8, -7, -6, -5, -4, -3, -2, -1, 0, 1]
let x = (0..<10).random           // x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let x = (-10 ... -2).random       // x = [-10, -9, -8, -7, -6, -5, -4, -3, -2]

Full Sample

Do not forget to add solution (1) and solution (2) codes here

private func generateRandNums(closure:()->(Int)) {

    var allNums = Set<Int>()
    for _ in 0..<100 {
        allNums.insert(closure())
    }
    print(allNums.sorted{ $0 < $1 })
}

generateRandNums {
    (-8..<2).random
}

generateRandNums {
    (0..<10).random
}

generateRandNums {
    (-10 ... -2).random
}

generateRandNums {
    rand(-5, 5)
}
generateRandNums {
    rand[0, 10]
}

Sample result

enter image description here

What MySQL data type should be used for Latitude/Longitude with 8 decimal places?

Using migrate ruby on rails

class CreateNeighborhoods < ActiveRecord::Migration[5.0]
  def change
    create_table :neighborhoods do |t|
      t.string :name
      t.decimal :latitude, precision: 15, scale: 13
      t.decimal :longitude, precision: 15, scale: 13
      t.references :country, foreign_key: true
      t.references :state, foreign_key: true
      t.references :city, foreign_key: true

      t.timestamps
    end
  end
end

Navigation drawer: How do I set the selected item at startup?

Make a selector for Individaual item of Nav Drawer

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/darkBlue" android:state_pressed="true"/>
    <item android:drawable="@color/darkBlue" android:state_checked="true"/>
    <item android:drawable="@color/textBlue" />
</selector>

Make a few changes in your NavigationView

<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:itemBackground="@drawable/drawer_item"
        android:background="@color/textBlue"
        app:itemIconTint="@color/white"
        app:itemTextColor="@color/white"
        app:menu="@menu/activity_main_drawer"
        />

Blur the edges of an image or background image with CSS

I'm not entirely sure what visual end result you're after, but here's an easy way to blur an image's edge: place a div with the image inside another div with the blurred image.

Working example here: http://jsfiddle.net/ZY5hn/1/

Screenshot

HTML:

<div class="placeholder">
     <!-- blurred background image for blurred edge -->
     <div class="bg-image-blur"></div>
     <!-- same image, no blur -->
     <div class="bg-image"></div>
     <!-- content -->
     <div class="content">Blurred Image Edges</div>
</div>

CSS:

.placeholder {
    margin-right: auto;
    margin-left:auto;
    margin-top: 20px;
    width: 200px;
    height: 200px;
    position: relative;
    /* this is the only relevant part for the example */
}
/* both DIVs have the same image */
 .bg-image-blur, .bg-image {
    background-image: url('http://lorempixel.com/200/200/city/9');
    position:absolute;
    top:0;
    left:0;
    width: 100%;
    height:100%;
}
/* blur the background, to make blurred edges that overflow the unblurred image that is on top */
 .bg-image-blur {
    -webkit-filter: blur(20px);
    -moz-filter: blur(20px);
    -o-filter: blur(20px);
    -ms-filter: blur(20px);
    filter: blur(20px);
}
/* I added this DIV in case you need to place content inside */
 .content {
    position: absolute;
    top:0;
    left:0;
    width: 100%;
    height: 100%;
    color: #fff;
    text-shadow: 0 0 3px #000;
    text-align: center;
    font-size: 30px;
}

Notice the blurred effect is using the image, so it changes with the image color.

I hope this helps.

Maven dependency for Servlet 3.0 API?

A convenient way (JBoss recommended) to include Java EE 6 dependencies is demonstrated below. As a result dependencies are placed separately (not all in one jar as in javaee-web-api), source files and javadocs of the libraries are available to download from maven repository.

<properties>
    <jboss.javaee6.spec.version>2.0.0.Final</jboss.javaee6.spec.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.jboss.spec</groupId>
        <artifactId>jboss-javaee-web-6.0</artifactId>
        <version>${jboss.javaee6.spec.version}</version>
        <scope>provided</scope>
        <type>pom</type>
    </dependency>
</dependencies>

To include individual dependencies only, dependencyManagement section and scope import can be used:

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.jboss.spec</groupId>
                <artifactId>jboss-javaee6-specs-bom</artifactId>
                <version>${jboss.javaee6.spec.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <!-- No need specifying version and scope. It is defaulted to version and scope from Bill of Materials (bom) imported pom. -->
        <dependency>
            <groupId>org.jboss.spec.javax.servlet</groupId>
            <artifactId>jboss-servlet-api_3.0_spec</artifactId>
        </dependency>
    </dependencies>

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

Firstly create app.js file in the directory you want to publish.

var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
    if (req.url != '/app.js') {
    var url = __dirname + req.url;
        fs.stat(url,function(err,stat){
            if (err) {
            res.writeHead(404,{'Content-Type':'text/html'});
            res.end('Your requested URI('+req.url+') wasn\'t found on our server');
            } else {
            var type = mime.getType(url);
            var fileSize = stat.size;
            var range = req.headers.range;
                if (range) {
                    var parts = range.replace(/bytes=/, "").split("-");
                var start = parseInt(parts[0], 10);
                    var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
                    var chunksize = (end-start)+1;
                    var file = fs.createReadStream(url, {start, end});
                    var head = {
                'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': chunksize,
                'Content-Type': type
                }
                    res.writeHead(206, head);
                    file.pipe(res);
                    } else {    
                    var head = {
                'Content-Length': fileSize,
                'Content-Type': type
                    }
                res.writeHead(200, head);
                fs.createReadStream(url).pipe(res);
                    }
            }
        });
    } else {
    res.writeHead(403,{'Content-Type':'text/html'});
    res.end('Sorry, access to that file is Forbidden');
    }
}).listen(8080);

Simply run node app.js and your server shall be running on port 8080. Besides video it can stream all kinds of files.

How to run ssh-add on windows?

The Git GUI for Windows has a window-based application that allows you to paste in locations for ssh keys and repo url etc:

https://gitforwindows.org/

parent & child with position fixed, parent overflow:hidden bug

If you want to hide overflow on fixed-position elements, the simplest approach I've found is to place the element inside a container element, and apply position:fixed and overflow:hidden to that element instead of the contained element (you must remove position:fixed from the contained element for this to work). The content of the fixed container should then be clipped as expected.

In my case I was having trouble with using object-fit:cover on a fixed-position element (it was spilling outside the bounds of the page body, regardless of overflow:hidden). Placing it inside a fixed container with overflow:hidden on the container fixed the issue.

Write to .txt file?

Well, you need to first get a good book on C and understand the language.

FILE *fp;
fp = fopen("c:\\test.txt", "wb");
if(fp == null)
   return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);

UICollectionView Self Sizing Cells with Auto Layout

Updated for Swift 5

preferredLayoutAttributesFittingAttributes renamed to preferredLayoutAttributesFitting and use auto sizing


Updated for Swift 4

systemLayoutSizeFittingSize renamed to systemLayoutSizeFitting


Updated for iOS 9

After seeing my GitHub solution break under iOS 9 I finally got the time to investigate the issue fully. I have now updated the repo to include several examples of different configurations for self sizing cells. My conclusion is that self sizing cells are great in theory but messy in practice. A word of caution when proceeding with self sizing cells.

TL;DR

Check out my GitHub project


Self sizing cells are only supported with flow layout so make sure thats what you are using.

There are two things you need to setup for self sizing cells to work.

1. Set estimatedItemSize on UICollectionViewFlowLayout

Flow layout will become dynamic in nature once you set the estimatedItemSize property.

self.flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize

2. Add support for sizing on your cell subclass

This comes in 2 flavours; Auto-Layout or custom override of preferredLayoutAttributesFittingAttributes.

Create and configure cells with Auto Layout

I won't go to in to detail about this as there's a brilliant SO post about configuring constraints for a cell. Just be wary that Xcode 6 broke a bunch of stuff with iOS 7 so, if you support iOS 7, you will need to do stuff like ensure the autoresizingMask is set on the cell's contentView and that the contentView's bounds is set as the cell's bounds when the cell is loaded (i.e. awakeFromNib).

Things you do need to be aware of is that your cell needs to be more seriously constrained than a Table View Cell. For instance, if you want your width to be dynamic then your cell needs a height constraint. Likewise, if you want the height to be dynamic then you will need a width constraint to your cell.

Implement preferredLayoutAttributesFittingAttributes in your custom cell

When this function is called your view has already been configured with content (i.e. cellForItem has been called). Assuming your constraints have been appropriately set you could have an implementation like this:

//forces the system to do one layout pass
var isHeightCalculated: Bool = false

override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    //Exhibit A - We need to cache our calculation to prevent a crash.
    if !isHeightCalculated {
        setNeedsLayout()
        layoutIfNeeded()
        let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
        var newFrame = layoutAttributes.frame
        newFrame.size.width = CGFloat(ceilf(Float(size.width)))
        layoutAttributes.frame = newFrame
        isHeightCalculated = true
    }
    return layoutAttributes
}

NOTE On iOS 9 the behaviour changed a bit that could cause crashes on your implementation if you are not careful (See more here). When you implement preferredLayoutAttributesFittingAttributes you need to ensure that you only change the frame of your layout attributes once. If you don't do this the layout will call your implementation indefinitely and eventually crash. One solution is to cache the calculated size in your cell and invalidate this anytime you reuse the cell or change its content as I have done with the isHeightCalculated property.

Experience your layout

At this point you should have 'functioning' dynamic cells in your collectionView. I haven't yet found the out-of-the box solution sufficient during my tests so feel free to comment if you have. It still feels like UITableView wins the battle for dynamic sizing IMHO.

Caveats

Be very mindful that if you are using prototype cells to calculate the estimatedItemSize - this will break if your XIB uses size classes. The reason for this is that when you load your cell from a XIB its size class will be configured with Undefined. This will only be broken on iOS 8 and up since on iOS 7 the size class will be loaded based on the device (iPad = Regular-Any, iPhone = Compact-Any). You can either set the estimatedItemSize without loading the XIB, or you can load the cell from the XIB, add it to the collectionView (this will set the traitCollection), perform the layout, and then remove it from the superview. Alternatively you could also make your cell override the traitCollection getter and return the appropriate traits. It's up to you.

Let me know if I missed anything, hope I helped and good luck coding


Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

Are you looking for the SQL used to generate a table? For that, you can query the sqlite_master table:

sqlite> CREATE TABLE foo (bar INT, quux TEXT);
sqlite> SELECT * FROM sqlite_master;
table|foo|foo|2|CREATE TABLE foo (bar INT, quux TEXT)
sqlite> SELECT sql FROM sqlite_master WHERE name = 'foo';
CREATE TABLE foo (bar INT, quux TEXT)

lexers vs parsers

There are a number of reasons why the analysis portion of a compiler is normally separated into lexical analysis and parsing ( syntax analysis) phases.

  1. Simplicity of design is the most important consideration. The separation of lexical and syntactic analysis often allows us to simplify at least one of these tasks. For example, a parser that had to deal with comments and white space as syntactic units would be. Considerably more complex than one that can assume comments and white space have already been removed by the lexical analyzer. If we are designing a new language, separating lexical and syntactic concerns can lead to a cleaner overall language design.
  2. Compiler efficiency is improved. A separate lexical analyzer allows us to apply specialized techniques that serve only the lexical task, not the job of parsing. In addition, specialized buffering techniques for reading input characters can speed up the compiler significantly.
  3. Compiler portability is enhanced. Input-device-specific peculiarities can be restricted to the lexical analyzer.

resource___Compilers (2nd Edition) written by- Alfred V. Abo Columbia University Monica S. Lam Stanford University Ravi Sethi Avaya Jeffrey D. Ullman Stanford University

Print all key/value pairs in a Java ConcurrentHashMap

Work 100% sure try this code for the get all hashmap key and value

static HashMap<String, String> map = new HashMap<>();

map.put("one"  " a " );
map.put("two"  " b " );
map.put("three"  " c " );
map.put("four"  " d " );

just call this method whenever you want to show the HashMap value

 private void ShowHashMapValue() {

        /**
         * get the Set Of keys from HashMap
         */
        Set setOfKeys = map.keySet();

/**
 * get the Iterator instance from Set
 */
        Iterator iterator = setOfKeys.iterator();

/**
 * Loop the iterator until we reach the last element of the HashMap
 */
        while (iterator.hasNext()) {
/**
 * next() method returns the next key from Iterator instance.
 * return type of next() method is Object so we need to do DownCasting to String
 */
            String key = (String) iterator.next();

/**
 * once we know the 'key', we can get the value from the HashMap
 * by calling get() method
 */
            String value = map.get(key);

            System.out.println("Key: " + key + ", Value: " + value);
        }
    } 

Cannot find mysql.sock

The socket file should be created automatically when the MySQL daemon starts.

If it isn't found, most likely the directory which is supposed to contain it doesn't exist, or some other file system problem is preventing the socket from being created.

To find out where the file should be, use:

% mysqld --verbose --help | grep ^socket

iterating and filtering two lists using java 8

// produce the filter set by streaming the items from list 2
// assume list2 has elements of type MyClass where getStr gets the
// string that might appear in list1
Set<String> unavailableItems = list2.stream()
    .map(MyClass::getStr)
    .collect(Collectors.toSet());

// stream the list and use the set to filter it
List<String> unavailable = list1.stream()
            .filter(e -> unavailableItems.contains(e))
            .collect(Collectors.toList());

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

Every Driver service in selenium calls the similar code(following is the firefox specific code) while creating the driver object

 @Override
 protected File findDefaultExecutable() {
      return findExecutable(
        "geckodriver", GECKO_DRIVER_EXE_PROPERTY,
        "https://github.com/mozilla/geckodriver",
        "https://github.com/mozilla/geckodriver/releases");
    }

now for the driver that you want to use, you have to set the system property with the value of path to the driver executable.

for firefox GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver" and this can be set before creating the driver object as below

System.setProperty("webdriver.gecko.driver", "./libs/geckodriver.exe");
WebDriver driver = new FirefoxDriver();

Location of the mongodb database on mac

If mongodb is installed via Homebrew the default location is:

/usr/local/var/mongodb

See the answer from @simonbogarde for the location of other interesting files that are different when using Homebrew.

How to execute a program or call a system command from Python

There is also Plumbum

>>> from plumbum import local
>>> ls = local["ls"]
>>> ls
LocalCommand(<LocalPath /bin/ls>)
>>> ls()
u'build.py\ndist\ndocs\nLICENSE\nplumbum\nREADME.rst\nsetup.py\ntests\ntodo.txt\n'
>>> notepad = local["c:\\windows\\notepad.exe"]
>>> notepad()                                   # Notepad window pops up
u''                                             # Notepad window is closed by user, command returns

IIS - 401.3 - Unauthorized

If you are working with Application Pool authentication (instead of IUSR), which you should, then this list of checks by Jean Sun is the very best I could find to deal with 401 errors in IIS:


Open IIS Manager, navigate to your website or application folder where the site is deployed to.

  1. Open Advanced Settings (it's on the right hand Actions pane).
  2. Note down the Application Pool name then close this window
  3. Double click on the Authentication icon to open the authentication settings
  4. Disable Windows Authentication
  5. Right click on Anonymous Authentication and click Edit
  6. Choose the Application pool identity radio button the click OK
  7. Select the Application Pools node from IIS manager tree on left and select the Application Pool name you noted down in step 3
  8. Right click and select Advanced Settings
  9. Expand the Process Model settings and choose ApplicationPoolIdentityfrom the "Built-in account" drop down list then click OK.
  10. Click OK again to save and dismiss the Application Pool advanced settings page
  11. Open an Administrator command line (right click on the CMD icon and select "Run As Administrator". It'll be somewhere on your start menu, probably under Accessories.
  12. Run the following command:

    icacls <path_to_site> /grant "IIS APPPOOL\<app_pool_name>"(CI)(OI)(M)
    

    For example:

    icacls C:\inetpub\wwwroot\mysite\ /grant "IIS APPPOOL\DEFAULTAPPPOOL":(CI)(OI)(M)
    

Especially steps 5. & 6. are often overlooked and rarely mentioned on the web.

How do I block or restrict special characters from input fields with jquery?

I was looking for an answer that restricted input to only alphanumeric characters, but still allowed for the use of control characters (e.g., backspace, delete, tab) and copy+paste. None of the provided answers that I tried satisfied all of these requirements, so I came up with the following using the input event.

$('input').on('input', function() {
  $(this).val($(this).val().replace(/[^a-z0-9]/gi, ''));
});

Edit:
As rinogo pointed out in the comments, the above code snippet forces the cursor to the end of the input when typing in the middle of the input text. I believe the code snippet below solves this problem.

$('input').on('input', function() {
  var c = this.selectionStart,
      r = /[^a-z0-9]/gi,
      v = $(this).val();
  if(r.test(v)) {
    $(this).val(v.replace(r, ''));
    c--;
  }
  this.setSelectionRange(c, c);
});

Oracle query execution time

I'd recommend looking at consistent gets/logical reads as a better proxy for 'work' than run time. The run time can be skewed by what else is happening on the database server, how much stuff is in the cache etc.

But if you REALLY want SQL executing time, the V$SQL view has both CPU_TIME and ELAPSED_TIME.

What is the difference between Serialization and Marshaling?

Here's more specific examples of both:

Serialization Example:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef struct {
    char value[11];
} SerializedInt32;

SerializedInt32 SerializeInt32(int32_t x) 
{
    SerializedInt32 result;

    itoa(x, result.value, 10);

    return result;
}

int32_t DeserializeInt32(SerializedInt32 x) 
{
    int32_t result;

    result = atoi(x.value);

    return result;
}

int main(int argc, char **argv)
{    
    int x;   
    SerializedInt32 data;
    int32_t result;

    x = -268435455;

    data = SerializeInt32(x);
    result = DeserializeInt32(data);

    printf("x = %s.\n", data.value);

    return result;
}

In serialization, data is flattened in a way that can be stored and unflattened later.

Marshalling Demo:

(MarshalDemoLib.cpp)

#include <iostream>
#include <string>

extern "C"
__declspec(dllexport)
void *StdCoutStdString(void *s)
{
    std::string *str = (std::string *)s;
    std::cout << *str;
}

extern "C"
__declspec(dllexport)
void *MarshalCStringToStdString(char *s)
{
    std::string *str(new std::string(s));

    std::cout << "string was successfully constructed.\n";

    return str;
}

extern "C"
__declspec(dllexport)
void DestroyStdString(void *s)
{
    std::string *str((std::string *)s);
    delete str;

    std::cout << "string was successfully destroyed.\n";
}

(MarshalDemo.c)

#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main(int argc, char **argv)
{
    void *myStdString;

    LoadLibrary("MarshalDemoLib");

    myStdString = ((void *(*)(char *))GetProcAddress (
        GetModuleHandleA("MarshalDemoLib"),
        "MarshalCStringToStdString"
    ))("Hello, World!\n");

    ((void (*)(void *))GetProcAddress (
        GetModuleHandleA("MarshalDemoLib"),
        "StdCoutStdString"
    ))(myStdString);

    ((void (*)(void *))GetProcAddress (
        GetModuleHandleA("MarshalDemoLib"),
        "DestroyStdString"
    ))(myStdString);    
}

In marshaling, data does not necessarily need to be flattened, but it needs to be transformed to another alternative representation. all casting is marshaling, but not all marshaling is casting.

Marshaling doesn't require dynamic allocation to be involved, it can also just be transformation between structs. For example, you might have a pair, but the function expects the pair's first and second elements to be other way around; you casting/memcpy one pair to another won't do the job because fst and snd will get flipped.

#include <stdio.h>

typedef struct {
    int fst;
    int snd;
} pair1;

typedef struct {
    int snd;
    int fst;
} pair2;

void pair2_dump(pair2 p)
{
    printf("%d %d\n", p.fst, p.snd);
}

pair2 marshal_pair1_to_pair2(pair1 p)
{
    pair2 result;
    result.fst = p.fst;
    result.snd = p.snd;
    return result;
}

pair1 given = {3, 7};

int main(int argc, char **argv)
{    
    pair2_dump(marshal_pair1_to_pair2(given));

    return 0;
}

The concept of marshaling becomes especially important when you start dealing with tagged unions of many types. For example, you might find it difficult to get a JavaScript engine to print a "c string" for you, but you can ask it to print a wrapped c string for you. Or if you want to print a string from JavaScript runtime in a Lua or Python runtime. They are all strings, but often won't get along without marshaling.

An annoyance I had recently was that JScript arrays marshal to C# as "__ComObject", and has no documented way to play with this object. I can find the address of where it is, but I really don't know anything else about it, so the only way to really figure it out is to poke at it in any way possible and hopefully find useful information about it. So it becomes easier to create a new object with a friendlier interface like Scripting.Dictionary, copy the data from the JScript array object into it, and pass that object to C# instead of JScript's default array.

test.js:

var x = new ActiveXObject("Dmitry.YetAnotherTestObject.YetAnotherTestObject");

x.send([1, 2, 3, 4]);

YetAnotherTestObject.cs

using System;
using System.Runtime.InteropServices;

namespace Dmitry.YetAnotherTestObject
{
    [Guid("C612BD9B-74E0-4176-AAB8-C53EB24C2B29"), ComVisible(true)]
    public class YetAnotherTestObject
    {
        public void send(object x)
        {
            System.Console.WriteLine(x.GetType().Name);
        }
    }
}

above prints "__ComObject", which is somewhat of a black box from the point of view of C#.

Another interesting concept is that you might have the understanding how to write code, and a computer that knows how to execute instructions, so as a programmer, you are effectively marshaling the concept of what you want the computer to do from your brain to the program image. If we had good enough marshallers, we could just think of what we want to do/change, and the program would change that way without typing on the keyboard. So, if you could have a way to store all the physical changes in your brain for the few seconds where you really want to write a semicolon, you could marshal that data into a signal to print a semicolon, but that's an extreme.

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

Despite the plethora of wrong answers here that attempt to circumvent the error by numerically manipulating the predictions, the root cause of your error is a theoretical and not computational issue: you are trying to use a classification metric (accuracy) in a regression (i.e. numeric prediction) model (LinearRegression), which is meaningless.

Just like the majority of performance metrics, accuracy compares apples to apples (i.e true labels of 0/1 with predictions again of 0/1); so, when you ask the function to compare binary true labels (apples) with continuous predictions (oranges), you get an expected error, where the message tells you exactly what the problem is from a computational point of view:

Classification metrics can't handle a mix of binary and continuous target

Despite that the message doesn't tell you directly that you are trying to compute a metric that is invalid for your problem (and we shouldn't actually expect it to go that far), it is certainly a good thing that scikit-learn at least gives you a direct and explicit warning that you are attempting something wrong; this is not necessarily the case with other frameworks - see for example the behavior of Keras in a very similar situation, where you get no warning at all, and one just ends up complaining for low "accuracy" in a regression setting...

I am super-surprised with all the other answers here (including the accepted & highly upvoted one) effectively suggesting to manipulate the predictions in order to simply get rid of the error; it's true that, once we end up with a set of numbers, we can certainly start mingling with them in various ways (rounding, thresholding etc) in order to make our code behave, but this of course does not mean that our numeric manipulations are meaningful in the specific context of the ML problem we are trying to solve.

So, to wrap up: the problem is that you are applying a metric (accuracy) that is inappropriate for your model (LinearRegression): if you are in a classification setting, you should change your model (e.g. use LogisticRegression instead); if you are in a regression (i.e. numeric prediction) setting, you should change the metric. Check the list of metrics available in scikit-learn, where you can confirm that accuracy is used only in classification.

Compare also the situation with a recent SO question, where the OP is trying to get the accuracy of a list of models:

models = []
models.append(('SVM', svm.SVC()))
models.append(('LR', LogisticRegression()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
#models.append(('SGDRegressor', linear_model.SGDRegressor())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('BayesianRidge', linear_model.BayesianRidge())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('LassoLars', linear_model.LassoLars())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('ARDRegression', linear_model.ARDRegression())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('PassiveAggressiveRegressor', linear_model.PassiveAggressiveRegressor())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('TheilSenRegressor', linear_model.TheilSenRegressor())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('LinearRegression', linear_model.LinearRegression())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets

where the first 6 models work OK, while all the rest (commented-out) ones give the same error. By now, you should be able to convince yourself that all the commented-out models are regression (and not classification) ones, hence the justified error.

A last important note: it may sound legitimate for someone to claim:

OK, but I want to use linear regression and then just round/threshold the outputs, effectively treating the predictions as "probabilities" and thus converting the model into a classifier

Actually, this has already been suggested in several other answers here, implicitly or not; again, this is an invalid approach (and the fact that you have negative predictions should have already alerted you that they cannot be interpreted as probabilities). Andrew Ng, in his popular Machine Learning course at Coursera, explains why this is a bad idea - see his Lecture 6.1 - Logistic Regression | Classification at Youtube (explanation starts at ~ 3:00), as well as section 4.2 Why Not Linear Regression [for classification]? of the (highly recommended and freely available) textbook An Introduction to Statistical Learning by Hastie, Tibshirani and coworkers...

Python Linked List

I did also write a Single Linked List based on some tutorial, which has the basic two Node and Linked List classes, and some additional methods for insertion, delete, reverse, sorting, and such.

It's not the best or easiest, works OK though.

"""


Single Linked List (SLL):
A simple object-oriented implementation of Single Linked List (SLL) 
with some associated methods, such as create list, count nodes, delete nodes, and such. 


"""

class Node:
    """
    Instantiates a node
    """
    def __init__(self, value):
        """
        Node class constructor which sets the value and link of the node

        """
        self.info = value
        self.link = None

class SingleLinkedList:
    """
    Instantiates the SLL class
    """
    def __init__(self):
        """
        SLL class constructor which sets the value and link of the node

        """
        self.start = None

    def create_single_linked_list(self):
        """
        Reads values from stdin and appends them to this list and creates a SLL with integer nodes

        """
        try:
            number_of_nodes = int(input("   Enter a positive integer between 1-50 for the number of nodes you wish to have in the list: "))
            if number_of_nodes <= 0 or number_of_nodes > 51:
                print(" The number of nodes though must be an integer between 1 to 50!")
                self.create_single_linked_list()

        except Exception as e:
            print(" Error: ", e)
            self.create_single_linked_list()


        try:
            for _ in range(number_of_nodes):
                try:
                    data = int(input("   Enter an integer for the node to be inserted: "))
                    self.insert_node_at_end(data)
                except Exception as e:
                    print(" Error: ", e)
        except Exception as e:
            print(" Error: ", e)

    def count_sll_nodes(self):
        """
        Counts the nodes of the linked list

        """
        try:
            p = self.start
            n = 0
            while p is not None:
                n += 1
                p = p.link

            if n >= 1:
                print(f" The number of nodes in the linked list is {n}")
            else:
                print(f" The SLL does not have a node!")
        except Exception as e: 
            print(" Error: ", e)

    def search_sll_nodes(self, x):
        """
        Searches the x integer in the linked list
        """
        try:
            position =  1
            p = self.start
            while p is not None:
                if p.info == x:
                    print(f" YAAAY! We found {x} at position {position}")
                    return True

                #Increment the position
                position += 1 
                #Assign the next node to the current node
                p = p.link
            else:
                print(f" Sorry! We couldn't find {x} at any position. Maybe, you might want to use option 9 and try again later!")
                return False
        except Exception as e:
            print(" Error: ", e)

    def display_sll(self):
        """
        Displays the list
        """
        try:
            if self.start is None:
                print(" Single linked list is empty!")
                return

            display_sll = " Single linked list nodes are: "
            p = self.start
            while p is not None:
                display_sll += str(p.info) + "\t"
                p = p.link

            print(display_sll)

        except Exception as e:
            print(" Error: ", e) 

    def insert_node_in_beginning(self, data):
        """
        Inserts an integer in the beginning of the linked list

        """
        try:
            temp = Node(data)
            temp.link = self.start
            self.start = temp
        except Exception as e:
            print(" Error: ", e)

    def insert_node_at_end(self, data):
        """
        Inserts an integer at the end of the linked list

        """
        try:            
            temp = Node(data)
            if self.start is None:
                self.start = temp
                return

            p = self.start  
            while p.link is not None:
                p = p.link
            p.link = temp
        except Exception as e:
            print(" Error: ", e)


    def insert_node_after_another(self, data, x):
        """
        Inserts an integer after the x node

        """
        try:
            p = self.start

            while p is not None:
                if p.info == x:
                    break
                p = p.link

            if p is None:
                print(f" Sorry! {x} is not in the list.")
            else:
                temp = Node(data)
                temp.link = p.link
                p.link = temp
        except Exception as e: 
            print(" Error: ", e)


    def insert_node_before_another(self, data, x):
        """
        Inserts an integer before the x node

        """

        try:

            # If list is empty
            if self.start is None:
                print(" Sorry! The list is empty.")
                return 
            # If x is the first node, and new node should be inserted before the first node
            if x == self.start.info:
                temp = Node(data)
                temp.link = p.link
                p.link = temp

            # Finding the reference to the prior node containing x
            p = self.start
            while p.link is not None:
                if p.link.info == x:
                    break
                p = p.link

            if p.link is not None:
                print(f" Sorry! {x} is not in the list.")
            else:
                temp = Node(data)
                temp.link = p.link
                p.link = temp           

        except Exception as e:
            print(" Error: ", e)

    def insert_node_at_position(self, data, k):
        """
        Inserts an integer in k position of the linked list

        """
        try:
            # if we wish to insert at the first node
            if k == 1:
                temp = Node(data)
                temp.link = self.start
                self.start = temp
                return

            p = self.start
            i = 1

            while i < k-1 and p is not None:
                p = p.link
                i += 1

            if p is None:
                print(f" The max position is {i}") 
            else:    
                temp = Node(data)
                temp.link = self.start
                self.start = temp

        except Exception as e:
            print(" Error: ", e)

    def delete_a_node(self, x):
        """
        Deletes a node of a linked list

        """
        try:
            # If list is empty
            if self.start is None:
                print(" Sorry! The list is empty.")
                return

            # If there is only one node
            if self.start.info == x:
                self.start = self.start.link

            # If more than one node exists
            p = self.start
            while p.link is not None:
                if p.link.info == x:
                    break   
                p = p.link

            if p.link is None:
                print(f" Sorry! {x} is not in the list.")
            else:
                p.link = p.link.link

        except Exception as e:
            print(" Error: ", e)

    def delete_sll_first_node(self):
        """
        Deletes the first node of a linked list

        """
        try:
            if self.start is None:
                return
            self.start = self.start.link

        except Exception as e:
            print(" Error: ", e)


    def delete_sll_last_node(self):
        """
        Deletes the last node of a linked list

        """
        try:

            # If the list is empty
            if self.start is None:
                return

            # If there is only one node
            if self.start.link is None:
                self.start = None
                return

            # If there is more than one node    
            p = self.start

            # Increment until we find the node prior to the last node 
            while p.link.link is not None:
                p = p.link

            p.link = None   

        except Exception as e:
            print(" Error: ", e)


    def reverse_sll(self):
        """
        Reverses the linked list

        """

        try:

            prev = None
            p = self.start
            while p is not None:
                next = p.link
                p.link = prev
                prev = p
                p = next
            self.start = prev

        except Exception as e:
            print(" Error: ", e)


    def bubble_sort_sll_nodes_data(self):
        """
        Bubble sorts the linked list on integer values

        """

        try:

            # If the list is empty or there is only one node
            if self.start is None or self.start.link is None:
                print(" The list has no or only one node and sorting is not required.")
            end = None

            while end != self.start.link:
                p = self.start
                while p.link != end:
                    q = p.link
                    if p.info > q.info:
                        p.info, q.info = q.info, p.info
                    p = p.link
                end = p

        except Exception as e:
            print(" Error: ", e)


    def bubble_sort_sll(self):
        """
        Bubble sorts the linked list

        """

        try:

            # If the list is empty or there is only one node
            if self.start is None or self.start.link is None:
                print(" The list has no or only one node and sorting is not required.")
            end = None

            while end != self.start.link:
                r = p = self.start
                while p.link != end:
                    q = p.link
                    if p.info > q.info:
                        p.link = q.link
                        q.link = p
                    if  p != self.start:
                        r.link = q.link
                    else:
                        self.start = q
                    p, q = q, p
                    r = p
                    p = p.link
                end = p

        except Exception as e:
            print(" Error: ", e)


    def sll_has_cycle(self):
        """
        Tests the list for cycles using Tortoise and Hare Algorithm (Floyd's cycle detection algorithm)
        """

        try:

            if self.find_sll_cycle() is None:
                return False
            else:
                return True


        except Exception as e:
            print(" Error: ", e)


    def find_sll_cycle(self):
        """
        Finds cycles in the list, if any
        """

        try:

            # If there is one node or none, there is no cycle
            if self.start is None or self.start.link is None:
                return None

            # Otherwise, 
            slowR = self.start
            fastR = self.start

            while slowR is not None and fastR is not None:
                slowR = slowR.link
                fastR = fastR.link.link
                if slowR == fastR: 
                    return slowR

            return None

        except Exception as e:
            print(" Error: ", e)


    def remove_cycle_from_sll(self):
        """
        Removes the cycles
        """

        try:

            c = self.find_sll_cycle()

            # If there is no cycle
            if c is None:
                return

            print(f" There is a cycle at node: ", c.info)

            p = c
            q = c
            len_cycles = 0
            while True:
                len_cycles += 1
                q = q.link

                if p == q:
                    break

            print(f" The cycle length is {len_cycles}")

            len_rem_list = 0
            p = self.start

            while p != q:
                len_rem_list += 1
                p = p.link
                q = q.link

            print(f" The number of nodes not included in the cycle is {len_rem_list}")

            length_list = len_rem_list + len_cycles

            print(f" The SLL length is {length_list}")

            # This for loop goes to the end of the SLL, and set the last node to None and the cycle is removed. 
            p = self.start
            for _ in range(length_list-1):
                p = p.link
            p.link = None


        except Exception as e:
            print(" Error: ", e)


    def insert_cycle_in_sll(self, x):
        """
        Inserts a cycle at a node that contains x

        """

        try:

            if self.start is None:
                return False

            p = self.start
            px = None
            prev = None


            while p is not None:
                if p.info == x:
                    px = p
                prev = p
                p = p.link

            if px is not None:
                prev.link = px
            else:
                print(f" Sorry! {x} is not in the list.")


        except Exception as e:
            print(" Error: ", e)


    def merge_using_new_list(self, list2):
        """
        Merges two already sorted SLLs by creating new lists
        """
        merge_list = SingleLinkedList()
        merge_list.start = self._merge_using_new_list(self.start, list2.start)
        return merge_list

    def _merge_using_new_list(self, p1, p2):
        """
        Private method of merge_using_new_list
        """
        if p1.info <= p2.info:
            Start_merge = Node(p1.info)
            p1 = p1.link
        else:
            Start_merge = Node(p2.info)
            p2 = p2.link            
        pM = Start_merge

        while p1 is not None and p2 is not None:
            if p1.info <= p2.info:
                pM.link = Node(p1.info)
                p1 = p1.link
            else:
                pM.link = Node(p2.info)
                p2 = p2.link
            pM = pM.link

        #If the second list is finished, yet the first list has some nodes
        while p1 is not None:
            pM.link = Node(p1.info)
            p1 = p1.link
            pM = pM.link

        #If the second list is finished, yet the first list has some nodes
        while p2 is not None:
            pM.link = Node(p2.info)
            p2 = p2.link
            pM = pM.link

        return Start_merge

    def merge_inplace(self, list2):
        """
        Merges two already sorted SLLs in place in O(1) of space
        """
        merge_list = SingleLinkedList()
        merge_list.start = self._merge_inplace(self.start, list2.start)
        return merge_list

    def _merge_inplace(self, p1, p2):
        """
        Merges two already sorted SLLs in place in O(1) of space
        """
        if p1.info <= p2.info:
            Start_merge = p1
            p1 = p1.link
        else:
            Start_merge = p2
            p2 = p2.link
        pM = Start_merge

        while p1 is not None and p2 is not None:
            if p1.info <= p2.info:
                pM.link = p1
                pM = pM.link
                p1 = p1.link
            else:
                pM.link = p2
                pM = pM.link
                p2 = p2.link

        if p1 is None:
            pM.link = p2
        else:
            pM.link = p1

        return Start_merge

    def merge_sort_sll(self):
        """
        Sorts the linked list using merge sort algorithm
        """
        self.start = self._merge_sort_recursive(self.start)


    def _merge_sort_recursive(self, list_start):
        """
        Recursively calls the merge sort algorithm for two divided lists
        """

        # If the list is empty or has only one node
        if list_start is None or list_start.link is None:
            return list_start

        # If the list has two nodes or more
        start_one = list_start
        start_two = self._divide_list(self_start)
        start_one = self._merge_sort_recursive(start_one)
        start_two = self._merge_sort_recursive(start_two)
        start_merge = self._merge_inplace(start_one, start_two)

        return start_merge

    def _divide_list(self, p):
        """
        Divides the linked list into two almost equally sized lists
        """

        # Refers to the third nodes of the list
        q = p.link.link

        while q is not None and p is not None:
            # Increments p one node at the time
            p = p.link
            # Increments q two nodes at the time
            q = q.link.link

        start_two = p.link
        p.link = None

        return start_two

    def concat_second_list_to_sll(self, list2):
        """
        Concatenates another SLL to an existing SLL
        """

        # If the second SLL has no node
        if list2.start is None:
            return

        # If the original SLL has no node
        if self.start is None:
            self.start = list2.start
            return

        # Otherwise traverse the original SLL
        p = self.start
        while p.link is not None:
            p = p.link

        # Link the last node to the first node of the second SLL
        p.link = list2.start



    def test_merge_using_new_list_and_inplace(self):
        """

        """

        LIST_ONE = SingleLinkedList()
        LIST_TWO = SingleLinkedList()

        LIST_ONE.create_single_linked_list()
        LIST_TWO.create_single_linked_list()

        print("1??  The unsorted first list is: ")
        LIST_ONE.display_sll()

        print("2??  The unsorted second list is: ")
        LIST_TWO.display_sll()


        LIST_ONE.bubble_sort_sll_nodes_data()
        LIST_TWO.bubble_sort_sll_nodes_data()

        print("1??  The sorted first list is: ")
        LIST_ONE.display_sll()

        print("2??  The sorted second list is: ")
        LIST_TWO.display_sll()

        LIST_THREE = LIST_ONE.merge_using_new_list(LIST_TWO)

        print("The merged list by creating a new list is: ")
        LIST_THREE.display_sll()


        LIST_FOUR = LIST_ONE.merge_inplace(LIST_TWO)

        print("The in-place merged list is: ")
        LIST_FOUR.display_sll()     


    def test_all_methods(self):
        """
        Tests all methods of the SLL class
        """

        OPTIONS_HELP = """

    Select a method from 1-19:                                                          

        ??   (1)      Create a single liked list (SLL).
        ??   (2)      Display the SLL.                            
        ??   (3)      Count the nodes of SLL. 
        ??   (4)      Search the SLL.
        ??   (5)      Insert a node at the beginning of the SLL.
        ??   (6)      Insert a node at the end of the SLL.
        ??   (7)      Insert a node after a specified node of the SLL.
        ??   (8)      Insert a node before a specified node of the SLL.
        ??   (9)      Delete the first node of SLL.
        ??   (10)     Delete the last node of the SLL.
        ??   (11)     Delete a node you wish to remove.                           
        ??   (12)     Reverse the SLL.
        ??   (13)     Bubble sort the SLL by only exchanging the integer values.  
        ??   (14)     Bubble sort the SLL by exchanging links.                    
        ??   (15)     Merge sort the SLL.
        ??   (16)     Insert a cycle in the SLL.
        ??   (17)     Detect if the SLL has a cycle.
        ??   (18)     Remove cycle in the SLL.
        ??   (19)     Test merging two bubble-sorted SLLs.
        ??   (20)     Concatenate a second list to the SLL. 
        ??   (21)     Exit.

        """


        self.create_single_linked_list()

        while True:

            print(OPTIONS_HELP)

            UI_OPTION = int(input("   Enter an integer for the method you wish to run using the above help: "))

            if UI_OPTION == 1:
                data = int(input("   Enter an integer to be inserted at the end of the list: "))
                x = int(input("   Enter an integer to be inserted after that: "))
                self.insert_node_after_another(data, x)
            elif UI_OPTION == 2:
                self.display_sll()
            elif UI_OPTION == 3:
                self.count_sll_nodes()
            elif UI_OPTION == 4:
                data = int(input("   Enter an integer to be searched: "))
                self.search_sll_nodes(data)
            elif UI_OPTION == 5:
                data = int(input("   Enter an integer to be inserted at the beginning: "))
                self.insert_node_in_beginning(data)
            elif UI_OPTION == 6:
                data = int(input("   Enter an integer to be inserted at the end: "))
                self.insert_node_at_end(data)
            elif UI_OPTION == 7:
                data = int(input("   Enter an integer to be inserted: "))
                x = int(input("   Enter an integer to be inserted before that: "))
                self.insert_node_before_another(data, x)
            elif UI_OPTION == 8:
                data = int(input("   Enter an integer for the node to be inserted: "))
                k = int(input("   Enter an integer for the position at which you wish to insert the node: "))
                self.insert_node_before_another(data, k)
            elif UI_OPTION == 9:
                self.delete_sll_first_node()
            elif UI_OPTION == 10:
                self.delete_sll_last_node()
            elif UI_OPTION == 11:
                data = int(input("   Enter an integer for the node you wish to remove: "))
                self.delete_a_node(data)
            elif UI_OPTION == 12:
                self.reverse_sll()
            elif UI_OPTION == 13:
                self.bubble_sort_sll_nodes_data()
            elif UI_OPTION == 14:
                self.bubble_sort_sll()
            elif UI_OPTION == 15:
                self.merge_sort_sll()
            elif UI_OPTION == 16:
                data = int(input("   Enter an integer at which a cycle has to be formed: "))
                self.insert_cycle_in_sll(data)
            elif UI_OPTION == 17:
                if self.sll_has_cycle():
                    print(" The linked list has a cycle. ")
                else:
                    print(" YAAAY! The linked list does not have a cycle. ")
            elif UI_OPTION == 18:
                self.remove_cycle_from_sll()
            elif UI_OPTION == 19:
                self.test_merge_using_new_list_and_inplace()
            elif UI_OPTION == 20:
                list2 = self.create_single_linked_list()
                self.concat_second_list_to_sll(list2)
            elif UI_OPTION == 21:
                break
            else:
                print(" Option must be an integer, between 1 to 21.")

            print()     



if __name__ == '__main__':
    # Instantiates a new SLL object
    SLL_OBJECT = SingleLinkedList()
    SLL_OBJECT.test_all_methods()

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

If your text will be consumed by non-browsers then it's safer to type the character with the keyboard-combo option shift right bracket because &rsquo; will not be transformed into an apostrophe by a regular XML or JSON parser. (e.g. if you are serving this content to native Android/iOS apps).

iPhone hide Navigation Bar only on first page

Another approach I found is to set a delegate for the NavigationController:

navigationController.delegate = self;

and use setNavigationBarHidden in navigationController:willShowViewController:animated:

- (void)navigationController:(UINavigationController *)navigationController 
      willShowViewController:(UIViewController *)viewController 
                    animated:(BOOL)animated 
{   
    // Hide the nav bar if going home.
    BOOL hide = viewController != homeViewController;
    [navigationController setNavigationBarHidden:hide animated:animated];
}

Easy way to customize the behavior for each ViewController all in one place.

How can I set a website image that will show as preview on Facebook?

Note also that if you have wordpress just scroll down to the bottom of the webpage when in edit mode, and select "featured image" (bottom right side of screen).

How to make a TextBox accept only alphabetic characters?

        if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z]+$"))
        { 
        }
        else
        {
            textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
            MessageBox.Show("Enter only Alphabets");


        }

Please Try this

Make virtualenv inherit specific packages from your global site-packages

Create the environment with virtualenv --system-site-packages . Then, activate the virtualenv and when you want things installed in the virtualenv rather than the system python, use pip install --ignore-installed or pip install -I . That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first in the virtualenv's package directory, so those packages should shadow the global ones.

What does InitializeComponent() do, and how does it work in WPF?

The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

Hope this helps!

How can you determine a point is between two other points on a line segment?

Check if the cross product of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned.

But, as you want to know if c is between a and b, you also have to check that the dot product of (b-a) and (c-a) is positive and is less than the square of the distance between a and b.

In non-optimized pseudocode:

def isBetween(a, b, c):
    crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)

    # compare versus epsilon for floating point values, or != 0 if using integers
    if abs(crossproduct) > epsilon:
        return False

    dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
    if dotproduct < 0:
        return False

    squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
    if dotproduct > squaredlengthba:
        return False

    return True

integrating barcode scanner into php application?

You can use AJAX for that. Whenever you scan a barcode, your scanner will act as if it is a keyboard typing into your input type="text" components. With JavaScript, capture the corresponding event, and send HTTP REQUEST and process responses accordingly.

automating telnet session using bash scripts

Telnet is often used when you learn HTTP protocol. I used to use that script as a part of my web-scraper:

echo "open www.example.com 80" 
sleep 2 
echo "GET /index.html HTTP/1.1" 
echo "Host: www.example.com" 
echo 
echo 
sleep 2

let's say the name of the script is get-page.sh then:

get-page.sh | telnet

will give you a html document.

Hope it will be helpful to someone ;)

How to get package name from anywhere?

If you use the gradle-android-plugin to build your app, then you can use

BuildConfig.APPLICATION_ID

to retrieve the package name from any scope, incl. a static one.

Why is vertical-align: middle not working on my span or div?

Using CSS3:

<div class="outer">
   <div class="inner"/>
</div>

Css:

.outer {
  display : flex;
  align-items : center;
}

use "justify-content: center;" to align elements horizontally

Note: This might not work in old IE's

AngularJS ng-repeat handle empty list case

And if you want to use this with a filtered list here's a neat trick:

<ul>
    <li ng-repeat="item in filteredItems  = (items | filter:keyword)">
        ...
    </li>
</ul>
<div ng-hide="filteredItems.length">No items found</div>

JavaFX FXML controller - constructor vs initialize method

In a few words: The constructor is called first, then any @FXML annotated fields are populated, then initialize() is called.

This means the constructor does not have access to @FXML fields referring to components defined in the .fxml file, while initialize() does have access to them.

Quoting from the Introduction to FXML:

[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.

Converting file into Base64String and back again

If you want for some reason to convert your file to base-64 string. Like if you want to pass it via internet, etc... you can do this

Byte[] bytes = File.ReadAllBytes("path");
String file = Convert.ToBase64String(bytes);

And correspondingly, read back to file:

Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);

Compare two objects in Java with possible null values

Using Java 8:

private static Comparator<String> nullSafeStringComparator = Comparator
        .nullsFirst(String::compareToIgnoreCase); 

private static Comparator<Metadata> metadataComparator = Comparator
        .comparing(Metadata::getName, nullSafeStringComparator)
        .thenComparing(Metadata::getValue, nullSafeStringComparator);

public int compareTo(Metadata that) {
    return metadataComparator.compare(this, that);
}

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

Find files in a folder using Java

As of Java 1.8, you can use Files.list to get a stream:

Path findFile(Path targetDir, String fileName) throws IOException {
    return Files.list(targetDir).filter( (p) -> {
        if (Files.isRegularFile(p)) {
            return p.getFileName().toString().equals(fileName);
        } else {
            return false;
        }
    }).findFirst().orElse(null);
}

Module not found: Error: Can't resolve 'core-js/es6'

Change all "es6" and "es7" to "es" in your polyfills.ts and polyfills.ts (Optional).

  • From: import 'core-js/es6/symbol';
  • To: import 'core-js/es/symbol';

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Process GET parameters

The <f:viewParam> manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>, but then for GET parameters.

The following example

<f:metadata>
    <f:viewParam name="id" value="#{bean.id}" />
</f:metadata>

does basically the following:

  • Get the request parameter value by name id.
  • Convert and validate it if necessary (you can use required, validator and converter attributes and nest a <f:converter> and <f:validator> in it like as with <h:inputText>)
  • If conversion and validation succeeds, then set it as a bean property represented by #{bean.id} value, or if the value attribute is absent, then set it as request attribtue on name id so that it's available by #{id} in the view.

So when you open the page as foo.xhtml?id=10 then the parameter value 10 get set in the bean this way, right before the view is rendered.

As to validation, the following example sets the param to required="true" and allows only values between 10 and 20. Any validation failure will result in a message being displayed.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
</f:metadata>
<h:message for="id" />

Performing business action on GET parameters

You can use the <f:viewAction> for this.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
    <f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />

with

public void onload() {
    // ...
}

The <f:viewAction> is however new since JSF 2.2 (the <f:viewParam> already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event> instead.

<f:event type="preRenderView" listener="#{bean.onload}" />

This is however invoked on every request. You need to explicitly check if the request isn't a postback:

public void onload() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // ...
    }
}

When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:

public void onload() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
        // ...
    }
}

Using <f:event> this way is in essence a workaround/hack, that's exactly why the <f:viewAction> was introduced in JSF 2.2.


Pass view parameters to next view

You can "pass-through" the view parameters in navigation links by setting includeViewParams attribute to true or by adding includeViewParams=true request parameter.

<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">

which generates with the above <f:metadata> example basically the following link

<a href="next.xhtml?id=10">

with the original parameter value.

This approach only requires that next.xhtml has also a <f:viewParam> on the very same parameter, otherwise it won't be passed through.


Use GET forms in JSF

The <f:viewParam> can also be used in combination with "plain HTML" GET forms.

<f:metadata>
    <f:viewParam id="query" name="query" value="#{bean.query}" />
    <f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
    <label for="query">Query</label>
    <input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
    <input type="submit" value="Search" />
    <h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
     ...
</h:dataTable>

With basically this @RequestScoped bean:

private String query;
private List<Result> results;

public void search() {
    results = service.search(query);
}

Note that the <h:message> is for the <f:viewParam>, not the plain HTML <input type="text">! Also note that the input value displays #{param.query} when #{bean.query} is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).


See also:

How to explain callbacks in plain english? How are they different from calling one function from another function?

I'm stunned to see so many intelligent people failing to stress the reality that the word "callback" has come to be used in two inconsistent ways.

Both ways involve the customization of a function by passing additional functionality (a function definition, anonymous or named) to an existing function. ie.

customizableFunc(customFunctionality)

If the custom functionality is simply plugged into the code block, you have customized the function, like so.

    customizableFucn(customFunctionality) {
      var data = doSomthing();
      customFunctionality(data);
      ...
    }

Though this kind of injected functionality is often called a "callback", there is nothing contingent about it. A very obvious example is the forEach method in which a custom function is supplied as an argument to be applied to each element in an array to modify the array.

But this is fundamentally distinct from the use of "callback" functions for asynchronous programming, as in AJAX or node.js or simply in assigning functionality to user interaction events (like mouse clicks). In this case, the whole idea is to wait for a contingent event to occur before executing the custom functionality. This is obvious in the case of user interaction, but is also important in i/o (input/output) processes that can take time, like reading files from disk. This is where the term "callback" makes the most obvious sense. Once an i/o process is started (like asking for a file to be read from disk or a server to return data from an http request) an asynchronous program doesn't wait around for it to finish. It can go ahead with whatever tasks are scheduled next, and only respond with the custom functionality after it has been notified that the read file or http request is completed (or that it failed) and that the data is available to the custom functionality. It's like calling a business on the phone and leaving your "callback" number, so they can call you when someone is available to get back to you. That's better than hanging on the line for who knows how long and not being able to attend to other affairs.

Asynchronous use inherently involves some means of listening for the desired event (e.g, the completion of the i/o process) so that, when it occurs (and only when it occurs) the custom "callback" functionality is executed. In the obvious AJAX example, when the data actually arrives from the server, the "callback" function is triggered to use that data to modify the DOM and therefore redraw the browser window to that extent.

To recap. Some people use the word "callback" to refer to any kind of custom functionality that can be injected into an existing function as an argument. But, at least to me, the most appropriate use of the word is where the injected "callback" function is used asynchronously -- to be executed only upon the occurrence of an event that it is waiting to be notified of.

How to use the divide function in the query?

Assuming all of these columns are int, then the first thing to sort out is converting one or more of them to a better data type - int division performs truncation, so anything less than 100% would give you a result of 0:

select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)
from 
CSPGI09_OVERSHIPMENT 

Here, I've mutiplied one of the numbers by 100.0 which will force the result of the calculation to be done with floats rather than ints. By choosing 100, I'm also getting it ready to be treated as a %.

I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (- and /) at the same level, and so were relying on the precedence rules to define which operator applied first.

Multiline editing in Visual Studio Code

I think it depends on your Visual Studio Code version.

Mine is Linux version Visual Studio Code 1.7.2.

{ "key": "ctrl+shift+up",         "command": "editor.action.insertCursorAbove",
                                     "when": "editorTextFocus" },
{ "key": "shift+alt+up",          "command": "editor.action.insertCursorAbove",
                                     "when": "editorTextFocus" },
{ "key": "ctrl+shift+down",       "command": "editor.action.insertCursorBelow",
                                     "when": "editorTextFocus" },
{ "key": "shift+alt+down",        "command": "editor.action.insertCursorBelow",
                                     "when": "editorTextFocus" }

The point is the shortcuts are not same in all machines, so you should check your configuration. Go to menu:

Menu File ? Preferences ? Keyboard Shortcuts

Search for editor.action.insertCursorAbove and editor.action.insertCursorBelow and see your current configurations. You may change them if they conflict with operating system's shortcut keys.

You have not accepted the license agreements of the following SDK components

I have resolve the problem by using the command:

  1. Go to: C:\Users\ [PC NAME] \AppData\Local\Android\sdk\tools\bin\ (If the folder is not available then download the android SDK first, or you can install it from the android studio installation process.)
  2. Shift+Left click and Press W,then Enter to open CMD on the folder path
  3. Type in the cmd: sdkmanager --licenses
  4. Once press enter, you need to accept all the licenses by pressing y

CHECKING THE LICENSES

  1. Go to: C:\Users[PC NAME]\AppData\Local\Android\sdk\
  2. Check the folder named licenses
android-googletv-license
android-sdk-license
android-sdk-preview-license
google-gdk-license
intel-android-extra-license
mips-android-sysimage-license

WAS TESTED ON CORDOVA USING THE COMMAND:

cordova build android

-- UPDATE NEW FOLDER PATH --

Open Android Studio, Tools > Sdk Manager > Android SDK Command-Line Tools (Just Opt-in)

enter image description here

SDKManager will be store in :

  1. Go to C:\Users\ [PC NAME] \AppData\Local\Android\Sdk\cmdline-tools\latest\bin
  2. Type in the cmd: sdkmanager --licenses

Documentation to using the Android SDK: https://developer.android.com/studio/command-line/sdkmanager.html

No module named 'openpyxl' - Python 3.4 - Ubuntu

In order to keep track of dependency issues, I like to use the conda installer, which simply boils down to:

conda install openpyxl

Bi-directional Map in Java?

Use Google's BiMap

It is more convenient.

How to combine paths in Java?

In Java 7, you should use resolve:

Path newPath = path.resolve(childPath);

While the NIO2 Path class may seem a bit redundant to File with an unnecessarily different API, it is in fact subtly more elegant and robust.

Note that Paths.get() (as suggested by someone else) doesn't have an overload taking a Path, and doing Paths.get(path.toString(), childPath) is NOT the same thing as resolve(). From the Paths.get() docs:

Note that while this method is very convenient, using it will imply an assumed reference to the default FileSystem and limit the utility of the calling code. Hence it should not be used in library code intended for flexible reuse. A more flexible alternative is to use an existing Path instance as an anchor, such as:

Path dir = ...
Path path = dir.resolve("file");

The sister function to resolve is the excellent relativize:

Path childPath = path.relativize(newPath);

Why did I get the compile error "Use of unassigned local variable"?

Local variables are not automatically initialized. That only happens with instance-level variables.

You need to explicitly initialize local variables if you want them to be initialized. In this case, (as the linked documentation explains) either by setting the value of 0 or using the new operator.

The code you've shown does indeed attempt to use the value of the variable tmpCnt before it is initialized to anything, and the compiler rightly warns about it.

How to ignore a property in class if null, using json.net

In .Net Core this is much easier now. In your startup.cs just add json options and you can configure the settings there.


public void ConfigureServices(IServiceCollection services)

....

services.AddMvc().AddJsonOptions(options =>
{
   options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;               
});

C++ "was not declared in this scope" compile error

fix function declaration on

int nonrecursivecountcells(color grid[ROW_SIZE][COL_SIZE], int row, int column)

I want to load another HTML page after a specific amount of time

<script>
    setTimeout(function(){
        window.location.href = 'form2.html';
    }, 5000);
</script>

And for home page add only '/'

<script>
    setTimeout(function(){
        window.location.href = '/';
    }, 5000);
</script>

how to implement Interfaces in C++?

C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.

An example would be something like this -

class Interface
{
public:
    Interface(){}
    virtual ~Interface(){}
    virtual void method1() = 0;    // "= 0" part makes this method pure virtual, and
                                   // also makes this class abstract.
    virtual void method2() = 0;
};

class Concrete : public Interface
{
private:
    int myMember;

public:
    Concrete(){}
    ~Concrete(){}
    void method1();
    void method2();
};

// Provide implementation for the first method
void Concrete::method1()
{
    // Your implementation
}

// Provide implementation for the second method
void Concrete::method2()
{
    // Your implementation
}

int main(void)
{
    Interface *f = new Concrete();

    f->method1();
    f->method2();

    delete f;

    return 0;
}

jQuery - Illegal invocation

In My case I have't define all variables which I am passing to data in ajax.

var page = 1;

$.ajax({
    url: 'your_url',
    type: "post",
    data: { 'page' : page, 'search_candidate' : search_candidate }
    success: function(result){
        alert('function called');
    }
)}

I have just defined variable var search_candidate = "candidate name"; and its working.

var page = 1;
var search_candidate = "candidate name"; // defined
$.ajax({
    url: 'your_url',
    type: "post",
    data: { 'page' : page, 'search_candidate' : search_candidate }
    success: function(result){
        alert('function called');
    }
)}

Get the difference between dates in terms of weeks, months, quarters, and years

For weeks, you can use function difftime:

date1 <- strptime("14.01.2013", format="%d.%m.%Y")
date2 <- strptime("26.03.2014", format="%d.%m.%Y")
difftime(date2,date1,units="weeks")
Time difference of 62.28571 weeks

But difftime doesn't work with duration over weeks.
The following is a very suboptimal solution using cut.POSIXt for those durations but you can work around it:

seq1 <- seq(date1,date2, by="days")
nlevels(cut(seq1,"months"))
15
nlevels(cut(seq1,"quarters"))
5
nlevels(cut(seq1,"years"))
2

This is however the number of months, quarters or years spanned by your time interval and not the duration of your time interval expressed in months, quarters, years (since those do not have a constant duration). Considering the comment you made on @SvenHohenstein answer I would think you can use nlevels(cut(seq1,"months")) - 1 for what you're trying to achieve.

PHP Curl And Cookies

Here you can find some useful info about cURL & cookies http://docstore.mik.ua/orelly/webprog/pcook/ch11_04.htm .

You can also use this well done method https://github.com/alixaxel/phunction/blob/master/phunction/Net.php#L89 like a function:

function CURL($url, $data = null, $method = 'GET', $cookie = null, $options = null, $retries = 3)
{
    $result = false;

    if ((extension_loaded('curl') === true) && (is_resource($curl = curl_init()) === true))
    {
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FAILONERROR, true);
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        if (preg_match('~^(?:DELETE|GET|HEAD|OPTIONS|POST|PUT)$~i', $method) > 0)
        {
            if (preg_match('~^(?:HEAD|OPTIONS)$~i', $method) > 0)
            {
                curl_setopt_array($curl, array(CURLOPT_HEADER => true, CURLOPT_NOBODY => true));
            }

            else if (preg_match('~^(?:POST|PUT)$~i', $method) > 0)
            {
                if (is_array($data) === true)
                {
                    foreach (preg_grep('~^@~', $data) as $key => $value)
                    {
                        $data[$key] = sprintf('@%s', rtrim(str_replace('\\', '/', realpath(ltrim($value, '@'))), '/') . (is_dir(ltrim($value, '@')) ? '/' : ''));
                    }

                    if (count($data) != count($data, COUNT_RECURSIVE))
                    {
                        $data = http_build_query($data, '', '&');
                    }
                }

                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }

            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, strtoupper($method));

            if (isset($cookie) === true)
            {
                curl_setopt_array($curl, array_fill_keys(array(CURLOPT_COOKIEJAR, CURLOPT_COOKIEFILE), strval($cookie)));
            }

            if ((intval(ini_get('safe_mode')) == 0) && (ini_set('open_basedir', null) !== false))
            {
                curl_setopt_array($curl, array(CURLOPT_MAXREDIRS => 5, CURLOPT_FOLLOWLOCATION => true));
            }

            if (is_array($options) === true)
            {
                curl_setopt_array($curl, $options);
            }

            for ($i = 1; $i <= $retries; ++$i)
            {
                $result = curl_exec($curl);

                if (($i == $retries) || ($result !== false))
                {
                    break;
                }

                usleep(pow(2, $i - 2) * 1000000);
            }
        }

        curl_close($curl);
    }

    return $result;
}

And pass this as $cookie parameter:

$cookie_jar = tempnam('/tmp','cookie');

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.

Windows equivalent of linux cksum command

It looks as if there is an unsupported tool for checksums from MS. It's light on features but appears to do what you're asking for. It was published in August of 2012. It's called "Microsoft File Checksum Integrity Verifier".

http://www.microsoft.com/en-us/download/details.aspx?id=11533

How to sort with lambda in Python

You're trying to use key functions with lambda functions.

Python and other languages like C# or F# use lambda functions.

Also, when it comes to key functions and according to the documentation

Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.

...

The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.

So, key functions have a parameter key and it can indeed receive a lambda function.

In Real Python there's a nice example of its usage. Let's say you have the following list

ids = ['id1', 'id100', 'id2', 'id22', 'id3', 'id30']

and want to sort through its "integers". Then, you'd do something like

sorted_ids = sorted(ids, key=lambda x: int(x[2:])) # Integer sort

and printing it would give

['id1', 'id2', 'id3', 'id22', 'id30', 'id100']

In your particular case, you're only missing to write key= before lambda. So, you'd want to use the following

a = sorted(a, key=lambda x: x.modified, reverse=True)

How to get only the date value from a Windows Forms DateTimePicker control?

Following that this question has been already given a good answer, in WinForms we can also set a Custom Format to the DateTimePicker Format property as Vivek said, this allow us to display the date/time in the specified format string within the DateTimePicker, then, it will be simple just as we do to get text from a TextBox.

// Set the Format type and the CustomFormat string.
dateTimePicker1.Format = DateTimePickerFormat.Custom;    
dateTimePicker1.CustomFormat = "yyyy/MM/dd";

dateTimePicker1

We are now able to get Date only easily by getting the Text from the DateTimePicker:

MessageBox.Show("Selected Date: " + dateTimePicker1.Text, "DateTimePicker", MessageBoxButtons.OK, MessageBoxIcon.Information);

enter image description here

NOTE: If you are planning to insert Date only data to a date column type in SQL, see this documentation related to the supported String Literal Formats for date. You can not insert a date in the format string ydm because is not supported:

dateTimePicker1.CustomFormat = "yyyy/dd/MM";  
var qr = "INSERT INTO tbl VALUES (@dtp)";
using (var insertCommand = new SqlCommand..
{
   try
   {
     insertCommand.Parameters.AddWithValue("@dtp", dateTimePicker1.Text);
     con.Open();
     insertCommand.ExecuteScalar();
   }
   catch (Exception ex)
   {
      MessageBox.Show("Exception message: " + ex.Message, "DateTimePicker", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }

the above code ends in the following Exception: enter image description here

Be aware. Cheers.

jQuery get the location of an element relative to window

function getWindowRelativeOffset(parentWindow, elem) {
        var offset = {
            left : 0,
            top : 0
        };
        // relative to the target field's document
        offset.left = elem.getBoundingClientRect().left;
        offset.top = elem.getBoundingClientRect().top;
        // now we will calculate according to the current document, this current
        // document might be same as the document of target field or it may be
        // parent of the document of the target field
        var childWindow = elem.document.frames.window;
        while (childWindow != parentWindow) {
            offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
            offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
            childWindow = childWindow.parent;
        }
        return offset;
    };

you can call it like this

getWindowRelativeOffset(top, inputElement);

I focus for IE only as per my requirement but similar can be done for other browsers

Graph implementation C++

Below is a implementation of Graph Data Structure in C++ as Adjacency List.

I have used STL vector for representation of vertices and STL pair for denoting edge and destination vertex.

#include <iostream>
#include <vector>
#include <map>
#include <string>

using namespace std;

struct vertex {
    typedef pair<int, vertex*> ve;
    vector<ve> adj; //cost of edge, destination vertex
    string name;
    vertex(string s) : name(s) {}
};

class graph
{
public:
    typedef map<string, vertex *> vmap;
    vmap work;
    void addvertex(const string&);
    void addedge(const string& from, const string& to, double cost);
};

void graph::addvertex(const string &name)
{
    vmap::iterator itr = work.find(name);
    if (itr == work.end())
    {
        vertex *v;
        v = new vertex(name);
        work[name] = v;
        return;
    }
    cout << "\nVertex already exists!";
}

void graph::addedge(const string& from, const string& to, double cost)
{
    vertex *f = (work.find(from)->second);
    vertex *t = (work.find(to)->second);
    pair<int, vertex *> edge = make_pair(cost, t);
    f->adj.push_back(edge);
}

set option "selected" attribute from dynamic created option

// Get <select> object
var sel = $('country');

// Loop through and look for value match, then break
for(i=0;i<sel.length;i++) { if(sel.value=="ID") { break; } }

// Select index 
sel.options.selectedIndex = i;

Begitu loh.

Resizing image in Java

Resize image with high quality:

private static InputStream resizeImage(InputStream uploadedInputStream, String fileName, int width, int height) {

        try {
            BufferedImage image = ImageIO.read(uploadedInputStream);
            Image originalImage= image.getScaledInstance(width, height, Image.SCALE_DEFAULT);

            int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
            BufferedImage resizedImage = new BufferedImage(width, height, type);

            Graphics2D g2d = resizedImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, width, height, null);
            g2d.dispose();
            g2d.setComposite(AlphaComposite.Src);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            ImageIO.write(resizedImage, fileName.split("\\.")[1], byteArrayOutputStream);
            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            // Something is going wrong while resizing image
            return uploadedInputStream;
        }
    }

Token Authentication vs. Cookies

A typical web app is mostly stateless, because of its request/response nature. The HTTP protocol is the best example of a stateless protocol. But since most web apps need state, in order to hold the state between server and client, cookies are used such that the server can send a cookie in every response back to the client. This means the next request made from the client will include this cookie and will thus be recognized by the server. This way the server can maintain a session with the stateless client, knowing mostly everything about the app's state, but stored in the server. In this scenario at no moment does the client hold state, which is not how Ember.js works.

In Ember.js things are different. Ember.js makes the programmer's job easier because it holds indeed the state for you, in the client, knowing at every moment about its state without having to make a request to the server asking for state data.

However, holding state in the client can also sometimes introduce concurrency issues that are simply not present in stateless situations. Ember.js, however, deals also with these issues for you; specifically ember-data is built with this in mind. In conclusion, Ember.js is a framework designed for stateful clients.

Ember.js does not work like a typical stateless web app where the session, the state and the corresponding cookies are handled almost completely by the server. Ember.js holds its state completely in Javascript (in the client's memory, and not in the DOM like some other frameworks) and does not need the server to manage the session. This results in Ember.js being more versatile in many situations, e.g. when your app is in offline mode.

Obviously, for security reasons, it does need some kind of token or unique key to be sent to the server everytime a request is made in order to be authenticated. This way the server can look up the send token (which was initially issued by the server) and verify if it's valid before sending a response back to the client.

In my opinion, the main reason why to use an authentication token instead of cookies as stated in Ember Auth FAQ is primarily because of the nature of the Ember.js framework and also because it fits more with the stateful web app paradigm. Therefore the cookie mechanism is not the best approach when building an Ember.js app.

I hope my answer will give more meaning to your question.

Object comparison in JavaScript

Here is my ES3 commented solution (gory details after the code):

function object_equals( x, y ) {
  if ( x === y ) return true;
    // if both x and y are null or undefined and exactly the same

  if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false;
    // if they are not strictly equal, they both need to be Objects

  if ( x.constructor !== y.constructor ) return false;
    // they must have the exact same prototype chain, the closest we can do is
    // test there constructor.

  for ( var p in x ) {
    if ( ! x.hasOwnProperty( p ) ) continue;
      // other properties were tested using x.constructor === y.constructor

    if ( ! y.hasOwnProperty( p ) ) return false;
      // allows to compare x[ p ] and y[ p ] when set to undefined

    if ( x[ p ] === y[ p ] ) continue;
      // if they have the same strict value or identity then they are equal

    if ( typeof( x[ p ] ) !== "object" ) return false;
      // Numbers, Strings, Functions, Booleans must be strictly equal

    if ( ! object_equals( x[ p ],  y[ p ] ) ) return false;
      // Objects and Arrays must be tested recursively
  }

  for ( p in y )
    if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) )
      return false;
        // allows x[ p ] to be set to undefined

  return true;
}

In developing this solution, I took a particular look at corner cases, efficiency, yet trying to yield a simple solution that works, hopefully with some elegance. JavaScript allows both null and undefined properties and objects have prototypes chains that can lead to very different behaviors if not checked.

First I have chosen to not extend Object.prototype, mostly because null could not be one of the objects of the comparison and that I believe that null should be a valid object to compare with another. There are also other legitimate concerns noted by others regarding the extension of Object.prototype regarding possible side effects on other's code.

Special care must taken to deal the possibility that JavaScript allows object properties can be set to undefined, i.e. there exists properties which values are set to undefined. The above solution verifies that both objects have the same properties set to undefined to report equality. This can only be accomplished by checking the existence of properties using Object.hasOwnProperty( property_name ). Also note that JSON.stringify() removes properties that are set to undefined, and that therefore comparisons using this form will ignore properties set to the value undefined.

Functions should be considered equal only if they share the same reference, not just the same code, because this would not take into account these functions prototype. So comparing the code string does not work to guaranty that they have the same prototype object.

The two objects should have the same prototype chain, not just the same properties. This can only be tested cross-browser by comparing the constructor of both objects for strict equality. ECMAScript 5 would allow to test their actual prototype using Object.getPrototypeOf(). Some web browsers also offer a __proto__ property that does the same thing. A possible improvement of the above code would allow to use one of these methods whenever available.

The use of strict comparisons is paramount here because 2 should not be considered equal to "2.0000", nor false should be considered equal to null, undefined, or 0.

Efficiency considerations lead me to compare for equality of properties as soon as possible. Then, only if that failed, look for the typeof these properties. The speed boost could be significant on large objects with lots of scalar properties.

No more that two loops are required, the first to check properties from the left object, the second to check properties from the right and verify only existence (not value), to catch these properties which are defined with the undefined value.

Overall this code handles most corner cases in only 16 lines of code (without comments).


Update (8/13/2015). I have implemented a better version, as the function value_equals() that is faster, handles properly corner cases such as NaN and 0 different than -0, optionally enforcing objects' properties order and testing for cyclic references, backed by more than 100 automated tests as part of the Toubkal project test suite.

warning: assignment makes integer from pointer without a cast

What Jeremiah said, plus the compiler issues the warning because the production:

*src ="anotherstring";

says: take the address of "anotherstring" -- "anotherstring" IS a char pointer -- and store that pointer indirect through src (*src = ... ) into the first char of the string "abcdef..." The warning might be baffling because there is nowhere in your code any mention of any integer: the warning seems nonsensical. But, out of sight behind the curtain, is the rule that "int" and "char" are synonymous in terms of storage: both occupy the same number of bits. The compiler doesn't differentiate when it issues the warning that you are storing into an integer. Which, BTW, is perfectly OK and legal but probably not exactly what you want in this code.

-- pete

Java : How to determine the correct charset encoding of a stream

Here are my favorites:

TikaEncodingDetector

Dependency:

<dependency>
  <groupId>org.apache.any23</groupId>
  <artifactId>apache-any23-encoding</artifactId>
  <version>1.1</version>
</dependency>

Sample:

public static Charset guessCharset(InputStream is) throws IOException {
  return Charset.forName(new TikaEncodingDetector().guessEncoding(is));    
}

GuessEncoding

Dependency:

<dependency>
  <groupId>org.codehaus.guessencoding</groupId>
  <artifactId>guessencoding</artifactId>
  <version>1.4</version>
  <type>jar</type>
</dependency>

Sample:

  public static Charset guessCharset2(File file) throws IOException {
    return CharsetToolkit.guessEncoding(file, 4096, StandardCharsets.UTF_8);
  }

Set textbox to readonly and background color to grey in jquery

there are 2 solutions:

visit this jsfiddle

in your css you can add this:
     .input-disabled{background-color:#EBEBE4;border:1px solid #ABADB3;padding:2px 1px;}

in your js do something like this:
     $('#test').attr('readonly', true);
     $('#test').addClass('input-disabled');

Hope this help.

Another way is using hidden input field as mentioned by some of the comments. However bear in mind that, in the backend code, you need to make sure you validate this newly hidden input at correct scenario. Hence I'm not recommend this way as it will create more bugs if its not handle properly.

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

There is a simple trick for this. After you constructed the frame with all it buttons do this:

frame.getRootPane().setDefaultButton(submitButton);

For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked.


And the problem with your code as far as I see is that your dialog pops up every time you hit a key, because you didn't put it in the if-body. Try changing it to this:

@Override
public void keyPressed(KeyEvent e) {
    if (e.getKeyCode()==KeyEvent.VK_ENTER){
        System.out.println("Hello");

        JOptionPane.showMessageDialog(null , "You've Submitted the name " + nameInput.getText());
    }

}

UPDATE: I found what is wrong with your code. You are adding the key listener to the Submit button instead of to the TextField. Change your code to this:

SubmitButton listener = new SubmitButton(textBoxToEnterName);
textBoxToEnterName.addActionListener(listener);
submit.addKeyListener(listener);

Get GMT Time in Java

This is pretty simple and straight forward.

Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
date = cal.getTime();

Now date will contain the current GMT time.

JavaScript - Get Portion of URL Path

There is a property of the built-in window.location object that will provide that for the current window.

// If URL is http://www.somedomain.com/account/search?filter=a#top

window.location.pathname // /account/search

// For reference:

window.location.host     // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash     // #top
window.location.href     // http://www.somedomain.com/account/search?filter=a#top
window.location.port     // (empty string)
window.location.protocol // http:
window.location.search   // ?filter=a  


Update, use the same properties for any URL:

It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location object and anchor elements implement the interface.

So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:

var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";

el.host        // www.somedomain.com (includes port if there is one[1])
el.hostname    // www.somedomain.com
el.hash        // #top
el.href        // http://www.somedomain.com/account/search?filter=a#top
el.pathname    // /account/search
el.port        // (port if there is one[1])
el.protocol    // http:
el.search      // ?filter=a

[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right

This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.

JSFiddle example

There's also a coming URL object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.

CocoaPods Errors on Project Build

I think it has a bug here.
For me, I delete Pods folder and Podfile.lock and do the pod install again to solve the problem.
This message is ignoring..:(

HTTP GET in VB.NET

Public Function getLoginresponce(ByVal email As String, ByVal password As String) As String
    Dim requestUrl As String = "your api"
    Dim request As HttpWebRequest = TryCast(WebRequest.Create(requestUrl), HttpWebRequest)
    Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
    Dim dataStream As Stream = response.GetResponseStream()
    Dim reader As New StreamReader(dataStream)
    Dim responseFromServer As String = reader.ReadToEnd()
    Dim result = responseFromServer
    reader.Close()
    response.Close()
    Return result
End Function

Pandas - Get first row value of a given column

To access a single value you can use the method iat that is much faster than iloc:

df['Btime'].iat[0]

Output:

1.2

Pyspark: display a spark data frame in a table format

As mentioned by @Brent in the comment of @maxymoo's answer, you can try

df.limit(10).toPandas()

to get a prettier table in Jupyter. But this can take some time to run if you are not caching the spark dataframe. Also, .limit() will not keep the order of original spark dataframe.

How can I check if two segments intersect?

Since you do not mention that you want to find the intersection point of the line, the problem becomes simpler to solve. If you need the intersection point, then the answer by OMG_peanuts is a faster approach. However, if you just want to find whether the lines intersect or not, you can do so by using the line equation (ax + by + c = 0). The approach is as follows:

  1. Let's start with two line segments: segment 1 and segment 2.

    segment1 = [[x1,y1], [x2,y2]]
    segment2 = [[x3,y3], [x4,y4]]
    
  2. Check if the two line segments are non zero length line and distinct segments.

  3. From hereon, I assume that the two segments are non-zero length and distinct. For each line segment, compute the slope of the line and then obtain the equation of a line in the form of ax + by + c = 0. Now, compute the value of f = ax + by + c for the two points of the other line segment (repeat this for the other line segment as well).

    a2 = (y3-y4)/(x3-x4);
    b1 = -1;
    b2 = -1;
    c1 = y1 - a1*x1;
    c2 = y3 - a2*x3;
    // using the sign function from numpy
    f1_1 = sign(a1*x3 + b1*y3 + c1);
    f1_2 = sign(a1*x4 + b1*y4 + c1);
    f2_1 = sign(a2*x1 + b2*y1 + c2);
    f2_2 = sign(a2*x2 + b2*y2 + c2);
    
  4. Now all that is left is the different cases. If f = 0 for any point, then the two lines touch at a point. If f1_1 and f1_2 are equal or f2_1 and f2_2 are equal, then the lines do not intersect. If f1_1 and f1_2 are unequal and f2_1 and f2_2 are unequal, then the line segments intersect. Depending on whether you want to consider the lines which touch as "intersecting" or not, you can adapt your conditions.

How to put a jpg or png image into a button in HTML

<input type= "image" id=" " onclick=" " src=" " />

it works.

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

In your cshtml,

<tr ng-repeat="value in Results">                
 <td>{{value.FileReceivedOn | mydate | date : 'dd-MM-yyyy'}} </td>
</tr>

In Your JS File, maybe app.js,

Outside of app.controller, add the below filter.

Here the "mydate" is the function which you are calling for parsing the date. Here the "app" is the variable which contains the angular.module

app.filter("mydate", function () {
    var re = /\/Date\(([0-9]*)\)\//;
    return function (x) {
        var m = x.match(re);
        if (m) return new Date(parseInt(m[1]));
        else return null;
    };
});

Jetty: HTTP ERROR: 503/ Service Unavailable

I had the same problem. I solved it by removing the line break from the xml file. I did

<operationBindings>
    <OperationBinding>
        <operationType>update</operationType>
        <operationId>makePdf</operationId>
        <serverObject>
            <className>com.myclass</className>
            <lookupStyle>new</lookupStyle>
        </serverObject>
        <serverMethod>makePdf</serverMethod>
    </OperationBinding>
</operationBindings>

instead of ...

<serverObject>
            <className>com.myclass
</className>
            <lookupStyle>new</lookupStyle>
</serverObject>

angularjs getting previous route path

In your html :

<a href="javascript:void(0);" ng-click="go_back()">Go Back</a>

On your main controller :

$scope.go_back = function() { 
  $window.history.back();
};

When user click on Go Back link the controller function is called and it will go back to previous route.

Unable to add window -- token null is not valid; is your activity running?

You need to pass your activity in the constructor

 PopupWindow popupWindow = new PopupWindow(YourActivity.this)

How can I change Eclipse theme?

The best way to Install new themes in any Eclipse platform is to use the Eclipse Marketplace.

1.Go to Help > Eclipse Marketplace

2.Search for "Color Themes"

3.Install and Restart

4.Go to Window > Preferences > General > Appearance > Color Themes

5.Select anyone and Apply. Restart.

Jquery href click - how can I fire up an event?

If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:

<a id="sign_up" class="sign_new">Sign up</a>

And jQuery:

$(document).ready(function(){
    $('#sign_up').click(function(){
        alert('Sign new href executed.');
    });
});

If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).

$(document).ready(function(){
    $('#sign_up').click(function(event){
        alert('Sign new href executed.');
        event.stopPropagation();
    });
});

Excel formula to display ONLY month and year?

Very easy, trial and error. Go to the cell you want the month in. Type the Month, go to the next cell and type the year, something weird will come up but then go to your number section click on the little arrow in the right bottom and highlight text and it will change to the year you originally typed

Fastest way to check a string is alphanumeric in Java

Use String.matches(), like:

String myString = "qwerty123456";
System.out.println(myString.matches("[A-Za-z0-9]+"));

That may not be the absolute "fastest" possible approach. But in general there's not much point in trying to compete with the people who write the language's "standard library" in terms of performance.

Setting property 'source' to 'org.eclipse.jst.jee.server:JSFTut' did not find a matching property

This is simple solution for this warning:

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. There is a server Option Tab. inside that tab click check Box to activate "Publish module contents to separate XML files".

Finally, restart your server, the message must disappear.

GitHub relative link in Markdown file

GitHub could make this a lot better with minimal work. Here is a work-around.

I think you want something more like

[Your Title](your-project-name/tree/master/your-subfolder)

or to point to the README itself

[README](your-project-name/blob/master/your-subfolder/README.md)

Add to python path mac os x

Modifications to sys.path only apply for the life of that Python interpreter. If you want to do it permanently you need to modify the PYTHONPATH environment variable:

PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"
export PYTHONPATH

Note that PATH is the system path for executables, which is completely separate.

**You can write the above in ~/.bash_profile and the source it using source ~/.bash_profile

encapsulation vs abstraction real world example

The wording of your question is odd - Abstraction vs Encapsulation? It should be - someone explain abstraction and encapsulation...

Abstraction is understanding the essence of the thing.

A real world example is abstract art. The artists of this style try to capture/paint the essence of the thing that still allows it to be the thing. This brown smear of 4 lines captures the essence of what a bull is.

Encapsulation is black boxing.

A cell phone is a great example. I have no idea how the cell phone connects to a satellite, tower, or another phone. I have no idea how the damn thing understands my key presses or how it takes and sends pictures to an email address or another phone number. I have no idea about the intricate details of most of how a modern smart phone works. But, I can use it! The phones have standard interfaces (yes - both literal and software design) that allows someone who understand the basics of one to use almost all of them.

How are the two related?

Both abstraction and encapsulation are underlying foundations of object oriented thought and design. So, in our cell phone example. The notion of a smart phone is an abstraction, within which certain features and services are encapsulated. The iPhone and Galaxy are further abstractions of the higher level abstraction. Your physical iPhone or Galaxy are concrete examples of multiple layers of abstractions which contain encapsulated features and services.

What is the difference between HTTP_HOST and SERVER_NAME in PHP?

Assuming one has a simple setup (CentOS 7, Apache 2.4.x, and PHP 5.6.20) and only one website (not assuming virtual hosting) ...

In the PHP sense, $_SERVER['SERVER_NAME'] is an element PHP registers in the $_SERVER superglobal based on your Apache configuration (**ServerName** directive with UseCanonicalName On ) in httpd.conf (be it from an included virtual host configuration file, whatever, etc ...). HTTP_HOST is derived from the HTTP host header. Treat this as user input. Filter and validate before using.

Here is an example of where I use $_SERVER['SERVER_NAME'] as the basis for a comparison. The following method is from a concrete child class I made named ServerValidator (child of Validator). ServerValidator checks six or seven elements in $_SERVER before using them.

In determining if the HTTP request is POST, I use this method.

public function isPOST()
{
    return (($this->requestMethod === 'POST')    &&  // Ignore
            $this->hasTokenTimeLeft()            &&  // Ignore
            $this->hasSameGETandPOSTIdentities() &&  // Ingore
            ($this->httpHost === filter_input(INPUT_SERVER, 'SERVER_NAME')));
}

By the time this method is called, all filtering and validating of relevant $_SERVER elements would have occurred (and relevant properties set).

The line ...

($this->httpHost === filter_input(INPUT_SERVER, 'SERVER_NAME')

... checks that the $_SERVER['HTTP_HOST'] value (ultimately derived from the requested host HTTP header) matches $_SERVER['SERVER_NAME'].

Now, I am using superglobal speak to explain my example, but that is just because some people are unfamiliar with INPUT_GET, INPUT_POST, and INPUT_SERVER in regards to filter_input_array().

The bottom line is, I do not handle POST requests on my server unless all four conditions are met. Hence, in terms of POST requests, failure to provide an HTTP host header (presence tested for earlier) spells doom for strict HTTP 1.0 browsers. Moreover, the requested host must match the value for ServerName in the httpd.conf, and, by extention, the value for $_SERVER('SERVER_NAME') in the $_SERVER superglobal. Again, I would be using INPUT_SERVER with the PHP filter functions, but you catch my drift.

Keep in mind that Apache frequently uses ServerName in standard redirects (such as leaving the trailing slash off a URL: Example, http://www.example.com becoming http://www.example.com/), even if you are not using URL rewriting.

I use $_SERVER['SERVER_NAME'] as the standard, not $_SERVER['HTTP_HOST']. There is a lot of back and forth on this issue. $_SERVER['HTTP_HOST'] could be empty, so this should not be the basis for creating code conventions such as my public method above. But, just because both may be set does not guarantee they will be equal. Testing is the best way to know for sure (bearing in mind Apache version and PHP version).

Quickest way to clear all sheet contents VBA

You can use the .Clear method:

Sheets("Zeros").UsedRange.Clear

Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.

How to check if a table exists in a given schema

Perhaps use information_schema:

SELECT EXISTS(
    SELECT * 
    FROM information_schema.tables 
    WHERE 
      table_schema = 'company3' AND 
      table_name = 'tableincompany3schema'
);

Export a list into a CSV or TXT file in R

Check out in here, worked well for me, with no limits in the output size, no omitted elements, even beyond 1000

Exporting large lists in R as .txt or .csv

ENOENT, no such file or directory

__dirname 

Gives you the current node application's rooth directory.

In your case, you'd use

__dirname + '/Desktop/MyApp/newversion/partials/navigation.jade';

See this answer:

App base path from a module in NodeJS

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

If ALL ELSE fails and your running locally on the MEAN stack like me with gulp...just stop and serve again! I was pulling my hear out meticulously checking everything from all of your posts to no avail till I simply re-ran gulp serve.

Javascript: getFullyear() is not a function

Try this...

 var start = new Date(document.getElementById('Stardate').value);
 var y = start.getFullYear();

Use a.empty, a.bool(), a.item(), a.any() or a.all()

As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &. That also requires using parentheses so that & wouldn't take precedence.

It would go something like this:

mask = ((50  < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...

In order to avoid that, you can build series for lower and upper limits:

low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)

Now you can slice it as follows:

mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out: 
     dyastolic blood pressure  heart rate  pulse oximetry  respiratory rate  \
17                        136          62              97                15   
69                        110          85              96                18   
72                        105          85              97                16   
161                       126          57              99                16   
286                       127          84              99                12   
435                        92          67              96                13   
499                       110          66              97                15   

     systolic blood pressure  temperature  
17                       141           37  
69                       155           38  
72                       154           36  
161                      153           36  
286                      156           37  
435                      155           36  
499                      149           36  

And for assignment you can use np.where:

df['class'] = np.where(mask, 'excellent', 'critical')

Can I force a UITableView to hide the separator between empty cells?

The following worked very well for me for this problem:

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

CGRect frame = [self.view frame];
frame.size.height =  frame.size.height - (kTableRowHeight * numberOfRowsInTable);

UIView *footerView = [[UIView alloc] initWithFrame:frame];
return footerView; }

Where kTableRowHeight is the height of my row cells and numberOfRowsInTable is the number of rows I had in the table.

Hope that helps,

Brenton.

There is already an open DataReader associated with this Command which must be closed first

It appears that you're calling DateLastUpdated from within an active query using the same EF context and DateLastUpdate issues a command to the data store itself. Entity Framework only supports one active command per context at a time.

You can refactor your above two queries into one like this:

return accounts.AsEnumerable()
        .Select((account, index) => new AccountsReport()
        {
          RecordNumber = FormattedRowNumber(account, index + 1),
          CreditRegistryId = account.CreditRegistryId,
          DateLastUpdated = (
                                                from h in context.AccountHistory 
                                                where h.CreditorRegistryId == creditorRegistryId 
                              && h.AccountNo == accountNo 
                                                select h.LastUpdated).Max(),
          AccountNumber = FormattedAccountNumber(account.AccountType, account.AccountNumber)
        })
        .OrderBy(c=>c.FormattedRecordNumber)
        .ThenByDescending(c => c.StateChangeDate);

I also noticed you're calling functions like FormattedAccountNumber and FormattedRecordNumber in the queries. Unless these are stored procs or functions you've imported from your database into the entity data model and mapped correct, these will also throw excepts as EF will not know how to translate those functions in to statements it can send to the data store.

Also note, calling AsEnumerable doesn't force the query to execute. Until the query execution is deferred until enumerated. You can force enumeration with ToList or ToArray if you so desire.

Using setDate in PreparedStatement

The problem you're having is that you're passing incompatible formats from a formatted java.util.Date to construct an instance of java.sql.Date, which don't behave in the same way when using valueOf() since they use different formats.

I also can see that you're aiming to persist hours and minutes, and I think that you'd better change the data type to java.sql.Timestamp, which supports hours and minutes, along with changing your database field to DATETIME or similar (depending on your database vendor).

Anyways, if you want to change from java.util.Date to java.sql.Date, I suggest to use

java.util.Date date = Calendar.getInstance().getTime();
java.sql.Date sqlDate = new java.sql.Date(date.getTime()); 
// ... more code here
prs.setDate(sqlDate);

CSS Circle with border

You forgot to set the width of the border! Change border: red; to border:1px solid red;

Here the full code to get the circle:

_x000D_
_x000D_
.circle {_x000D_
    background-color:#fff;_x000D_
    border:1px solid red;    _x000D_
    height:100px;_x000D_
    border-radius:50%;_x000D_
    -moz-border-radius:50%;_x000D_
    -webkit-border-radius:50%;_x000D_
    width:100px;_x000D_
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_

How to get the scroll bar with CSS overflow on iOS

make sure your body and divs have not a

  position:fixed

else it would not work

How to clone git repository with specific revision/changeset?

# clone special tag/branch without history
git clone  --branch=<tag/branch> --depth=1 <repository>


# clone special revision with minimal histories
git clone --branch <branch> <repository> --shallow-since=yyyy-MM-ddTHH:mm:ss  # get the commit time
cd <dir>
git reset --hard <revision> 

you can't get a revision without histories if not set uploadpack.allowReachableSHA1InWant=true on server side, while you can create a tag for it and clone the special tag instead.

PyCharm error: 'No Module' when trying to import own module (python script)

So if you go to

-> Setting -> Project:My_project -> Project Structure,

Just the directory in which the source code is available and mark it as "Sources" (You can see it on the same window). The directory with source code should turn blue. Now u can import in modules residing in same directory.

jQuery: how to scroll to certain anchor/div on page load?

Use the following simple example

function scrollToElement(ele) {
    $(window).scrollTop(ele.offset().top).scrollLeft(ele.offset().left);
}

where ele is your element (jQuery) .. for example : scrollToElement($('#myid'));

What are all the common ways to read a file in Ruby?

I usually do this:

open(path_in_string, &:read)

This will give you the whole text as a string object. It works only under Ruby 1.9.

How to print object array in JavaScript?

Not sure about the subelements, but all browsers should support this now:

for (val of lineChartData) {
  document.write(val);
}

This might give you some ideas For-each over an array in JavaScript?

Strip first and last character from C string

The most efficient way:

//Note destroys the original string by removing it's last char
// Do not pass in a string literal.
char * getAllButFirstAndLast(char *input)
{
  int len = strlen(input); 
  if(len > 0)
    input++;//Go past the first char
  if(len > 1)
    input[len - 2] = '\0';//Replace the last char with a null termination
  return input;
}


//...
//Call it like so
char str[512];
strcpy(str, "hello world");
char *pMod = getAllButFirstAndLast(str);

The safest way:

void getAllButFirstAndLast(const char *input, char *output)
{
  int len = strlen(input);
  if(len > 0)
    strcpy(output, ++input);
  if(len > 1)
    output[len - 2] = '\0';
}


//...
//Call it like so
char mod[512];
getAllButFirstAndLast("hello world", mod);

The second way is less efficient but it is safer because you can pass in string literals into input. You could also use strdup for the second way if you didn't want to implement it yourself.

What is the best way to convert an array to a hash in Ruby

Not sure if it's the best way, but this works:

a = ["apple", 1, "banana", 2]
m1 = {}
for x in (a.length / 2).times
  m1[a[x*2]] = a[x*2 + 1]
end

b = [["apple", 1], ["banana", 2]]
m2 = {}
for x,y in b
  m2[x] = y
end

Python list / sublist selection -1 weirdness

If you want to get a sub list including the last element, you leave blank after colon:

>>> ll=range(10)
>>> ll
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ll[5:]
[5, 6, 7, 8, 9]
>>> ll[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Length of a JavaScript object

Here's a different version of James Cogan's answer. Instead of passing an argument, just prototype out the Object class and make the code cleaner.

Object.prototype.size = function () {
    var size = 0,
        key;
    for (key in this) {
        if (this.hasOwnProperty(key)) size++;
    }
    return size;
};

var x = {
    one: 1,
    two: 2,
    three: 3
};

x.size() === 3;

jsfiddle example: http://jsfiddle.net/qar4j/1/

Avoid printStackTrace(); use a logger call instead

Let's talk in from company concept. Log gives you flexible levels (see Difference between logger.info and logger.debug). Different people want to see different levels, like QAs, developers, business people. But e.printStackTrace() will print out everything. Also, like if this method will be restful called, this same error may print several times. Then the Devops or Tech-Ops people in your company may be crazy because they will receive the same error reminders. I think a better replacement could be log.error("errors happend in XXX", e) This will also print out whole information which is easy reading than e.printStackTrace()

Is there an easy way to check the .NET Framework version?

Something like this should do it. Just grab the value from the registry

For .NET 1-4:

Framework is the highest installed version, SP is the service pack for that version.

RegistryKey installed_versions = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
string[] version_names = installed_versions.GetSubKeyNames();
//version names start with 'v', eg, 'v3.5' which needs to be trimmed off before conversion
double Framework = Convert.ToDouble(version_names[version_names.Length - 1].Remove(0, 1), CultureInfo.InvariantCulture);
int SP = Convert.ToInt32(installed_versions.OpenSubKey(version_names[version_names.Length - 1]).GetValue("SP", 0));

For .NET 4.5+ (from official documentation):

using System;
using Microsoft.Win32;


...


private static void Get45or451FromRegistry()
{
    using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\")) {
        int releaseKey = Convert.ToInt32(ndpKey.GetValue("Release"));
        if (true) {
            Console.WriteLine("Version: " + CheckFor45DotVersion(releaseKey));
        }
    }
}


...


// Checking the version using >= will enable forward compatibility,  
// however you should always compile your code on newer versions of 
// the framework to ensure your app works the same. 
private static string CheckFor45DotVersion(int releaseKey)
{
    if (releaseKey >= 461808) {
        return "4.7.2 or later";
    }
    if (releaseKey >= 461308) {
        return "4.7.1 or later";
    }
    if (releaseKey >= 460798) {
        return "4.7 or later";
    }
    if (releaseKey >= 394802) {
        return "4.6.2 or later";
    }
    if (releaseKey >= 394254) {
        return "4.6.1 or later";
    }
    if (releaseKey >= 393295) {
        return "4.6 or later";
    }
    if (releaseKey >= 393273) {
        return "4.6 RC or later";
    }
    if ((releaseKey >= 379893)) {
        return "4.5.2 or later";
    }
    if ((releaseKey >= 378675)) {
        return "4.5.1 or later";
    }
    if ((releaseKey >= 378389)) {
        return "4.5 or later";
    }
    // This line should never execute. A non-null release key should mean 
    // that 4.5 or later is installed. 
    return "No 4.5 or later version detected";
}

Display curl output in readable JSON format in Unix shell script

python -m json.tool
Curl http://127.0.0.1:5000/people/api.json | python -m json.tool

can also help.

Git push failed, "Non-fast forward updates were rejected"

Sometimes, while taking a pull from your git, the HEAD gets detached. You can check this by entering the command:

git branch 
  • (HEAD detached from 8790704)

    master

    develop

It's better to move to your branch and take a fresh pull from your respective branch.

git checkout develop

git pull origin develop

git push origin develop

How can I make my layout scroll both horizontally and vertically?

its too late but i hope your issue will be solve quickly with this code. nothing to do more just put your code in below scrollview.

<HorizontalScrollView
        android:id="@+id/scrollView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

      <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            //xml code
      </ScrollView>
</HorizontalScrollView>

Fling gesture detection on grid layout

My version of solution proposed by Thomas Fankhauser and Marek Sebera (does not handle vertical swipes):

SwipeInterface.java

import android.view.View;

public interface SwipeInterface {

    public void onLeftToRight(View v);

    public void onRightToLeft(View v);
}

ActivitySwipeDetector.java

import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

public class ActivitySwipeDetector implements View.OnTouchListener {

    static final String logTag = "ActivitySwipeDetector";
    private SwipeInterface activity;
    private float downX, downY;
    private long timeDown;
    private final float MIN_DISTANCE;
    private final int VELOCITY;
    private final float MAX_OFF_PATH;

    public ActivitySwipeDetector(Context context, SwipeInterface activity){
        this.activity = activity;
        final ViewConfiguration vc = ViewConfiguration.get(context);
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        MIN_DISTANCE = vc.getScaledPagingTouchSlop() * dm.density;
        VELOCITY = vc.getScaledMinimumFlingVelocity();
        MAX_OFF_PATH = MIN_DISTANCE * 2;            
    }

    public void onRightToLeftSwipe(View v){
        Log.i(logTag, "RightToLeftSwipe!");
        activity.onRightToLeft(v);
    }

    public void onLeftToRightSwipe(View v){
        Log.i(logTag, "LeftToRightSwipe!");
        activity.onLeftToRight(v);
    }

    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()){
        case MotionEvent.ACTION_DOWN: {
            Log.d("onTouch", "ACTION_DOWN");
            timeDown = System.currentTimeMillis();
            downX = event.getX();
            downY = event.getY();
            return true;
        }
        case MotionEvent.ACTION_UP: {
            Log.d("onTouch", "ACTION_UP");
            long timeUp = System.currentTimeMillis();
            float upX = event.getX();
            float upY = event.getY();

            float deltaX = downX - upX;
            float absDeltaX = Math.abs(deltaX); 
            float deltaY = downY - upY;
            float absDeltaY = Math.abs(deltaY);

            long time = timeUp - timeDown;

            if (absDeltaY > MAX_OFF_PATH) {
                Log.i(logTag, String.format("absDeltaY=%.2f, MAX_OFF_PATH=%.2f", absDeltaY, MAX_OFF_PATH));
                return v.performClick();
            }

            final long M_SEC = 1000;
            if (absDeltaX > MIN_DISTANCE && absDeltaX > time * VELOCITY / M_SEC) {
                if(deltaX < 0) { this.onLeftToRightSwipe(v); return true; }
                if(deltaX > 0) { this.onRightToLeftSwipe(v); return true; }
            } else {
                Log.i(logTag, String.format("absDeltaX=%.2f, MIN_DISTANCE=%.2f, absDeltaX > MIN_DISTANCE=%b", absDeltaX, MIN_DISTANCE, (absDeltaX > MIN_DISTANCE)));
                Log.i(logTag, String.format("absDeltaX=%.2f, time=%d, VELOCITY=%d, time*VELOCITY/M_SEC=%d, absDeltaX > time * VELOCITY / M_SEC=%b", absDeltaX, time, VELOCITY, time * VELOCITY / M_SEC, (absDeltaX > time * VELOCITY / M_SEC)));
            }

        }
        }
        return false;
    }

}

How to remove the border highlight on an input text element

This was confusing me for some time until I discovered the line was neither a border or an outline, it was a shadow. So to remove it I had to use this:

input:focus, input.form-control:focus {

    outline:none !important;
    outline-width: 0 !important;
    box-shadow: none;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
}

What is the difference between 'E', 'T', and '?' for Java generics?

Well there's no difference between the first two - they're just using different names for the type parameter (E or T).

The third isn't a valid declaration - ? is used as a wildcard which is used when providing a type argument, e.g. List<?> foo = ... means that foo refers to a list of some type, but we don't know what.

All of this is generics, which is a pretty huge topic. You may wish to learn about it through the following resources, although there are more available of course:

Google Chrome display JSON AJAX response as tree and not as a plain text

To see a tree view in recent versions of Chrome:

Navigate to Developer Tools > Network > the given response > Preview

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

How to Compare two strings using a if in a stored procedure in sql server 2008?

Two things:

  1. Only need one (1) equals sign to evaluate
  2. You need to specify a length on the VARCHAR - the default is a single character.

Use:

DECLARE @temp VARCHAR(10)
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

VARCHAR(10) means the VARCHAR will accommodate up to 10 characters. More examples of the behavior -

DECLARE @temp VARCHAR
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "yes"

DECLARE @temp VARCHAR
    SET @temp = 'mtest'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "no".

In Go's http package, how do I get the query string on a POST request?

Below words come from the official document.

Form contains the parsed form data, including both the URL field's query parameters and the POST or PUT form data. This field is only available after ParseForm is called.

So, sample codes as below would work.

func parseRequest(req *http.Request) error {
    var err error

    if err = req.ParseForm(); err != nil {
        log.Error("Error parsing form: %s", err)
        return err
    }

    _ = req.Form.Get("xxx")

    return nil
}

What is the canonical way to check for errors using the CUDA runtime API?

talonmies' answer above is a fine way to abort an application in an assert-style manner.

Occasionally we may wish to report and recover from an error condition in a C++ context as part of a larger application.

Here's a reasonably terse way to do that by throwing a C++ exception derived from std::runtime_error using thrust::system_error:

#include <thrust/system_error.h>
#include <thrust/system/cuda/error.h>
#include <sstream>

void throw_on_cuda_error(cudaError_t code, const char *file, int line)
{
  if(code != cudaSuccess)
  {
    std::stringstream ss;
    ss << file << "(" << line << ")";
    std::string file_and_line;
    ss >> file_and_line;
    throw thrust::system_error(code, thrust::cuda_category(), file_and_line);
  }
}

This will incorporate the filename, line number, and an English language description of the cudaError_t into the thrown exception's .what() member:

#include <iostream>

int main()
{
  try
  {
    // do something crazy
    throw_on_cuda_error(cudaSetDevice(-1), __FILE__, __LINE__);
  }
  catch(thrust::system_error &e)
  {
    std::cerr << "CUDA error after cudaSetDevice: " << e.what() << std::endl;

    // oops, recover
    cudaSetDevice(0);
  }

  return 0;
}

The output:

$ nvcc exception.cu -run
CUDA error after cudaSetDevice: exception.cu(23): invalid device ordinal

A client of some_function can distinguish CUDA errors from other kinds of errors if desired:

try
{
  // call some_function which may throw something
  some_function();
}
catch(thrust::system_error &e)
{
  std::cerr << "CUDA error during some_function: " << e.what() << std::endl;
}
catch(std::bad_alloc &e)
{
  std::cerr << "Bad memory allocation during some_function: " << e.what() << std::endl;
}
catch(std::runtime_error &e)
{
  std::cerr << "Runtime error during some_function: " << e.what() << std::endl;
}
catch(...)
{
  std::cerr << "Some other kind of error during some_function" << std::endl;

  // no idea what to do, so just rethrow the exception
  throw;
}

Because thrust::system_error is a std::runtime_error, we can alternatively handle it in the same manner of a broad class of errors if we don't require the precision of the previous example:

try
{
  // call some_function which may throw something
  some_function();
}
catch(std::runtime_error &e)
{
  std::cerr << "Runtime error during some_function: " << e.what() << std::endl;
}

How do you update a DateTime field in T-SQL?

If you aren't interested in specifying a time, you can also use the format 'DD/MM/YYYY', however I would stick to a Conversion method, and its relevant ISO format, as you really should avoid using default values.

Here's an example:

SET startDate = CONVERT(datetime,'2015-03-11T23:59:59.000',126) WHERE custID = 'F24'

Google Maps API warning: NoApiKeys

Creating and using the key is the way to go. The usage is free until your application reaches 25.000 calls per day on 90 consecutive days.

BTW.: In the google Developer documentation it says you shall add the api key as option {key:yourKey} when calling the API to create new instances. This however doesn't shush the console warning. You have to add the key as a parameter when including the api.

<script src="https://maps.googleapis.com/maps/api/js?key=yourKEYhere"></script>

Get the key here: GoogleApiKey Generation site

Search for highest key/index in an array

You can get the maximum key this way:

<?php
$arr = array("a"=>"test", "b"=>"ztest");
$max = max(array_keys($arr));
?>

Convert time.Time to string

You can use the Time.String() method to convert a time.Time to a string. This uses the format string "2006-01-02 15:04:05.999999999 -0700 MST".

If you need other custom format, you can use Time.Format(). For example to get the timestamp in the format of yyyy-MM-dd HH:mm:ss use the format string "2006-01-02 15:04:05".

Example:

t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))

Output (try it on the Go Playground):

2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00

Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.

Also note that using Time.Format(), as the layout string you always have to pass the same time –called the reference time– formatted in a way you want the result to be formatted. This is documented at Time.Format():

Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.

PHP code to remove everything but numbers

This is for future developers, you can also try this. Simple too

echo preg_replace('/\D/', '', '604-619-5135');

How do I find out my root MySQL password?

For RHEL-mysql 5.5:

/etc/init.d/mysql stop

/etc/init.d/mysql start --skip-grant-tables

 mysql> UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
 mysql> FLUSH PRIVILEGES;
 mysql> exit;

mysql -uroot -pnewpwd

mysql>  

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

PUT

$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

POST

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

GET See @Dan H answer

DELETE

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

How to form a correct MySQL connection string?

try creating connection string this way:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";

using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{    //watch out for this SQL injection vulnerability below
     cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
                                    OSGconv.deciLat, OSGconv.deciLon);
     conn.Open();
     cmd.ExecuteNonQuery();
}

python convert list to dictionary

I'd go for recursions:

l = ['a', 'b', 'c', 'd', 'e', ' ']
d = dict([(k, v) for k,v in zip (l[::2], l[1::2])])

How to bind a List<string> to a DataGridView control?

you can also use linq and anonymous types to achieve the same result with much less code as described here.

UPDATE: blog is down, here's the content:

(..) The values shown in the table represent the length of strings instead of string values (!) It may seem strange, but that’s how binding mechanism works by default – given an object it will try to bind to the first property of that object (the first property it can find). When passed an instance the String class the property it binds to is String.Length since there’s no other property that would provide the actual string itself.

That means that to get our binding right we need a wrapper object that will expose the actual value of a string as a property:

public class StringWrapper
    {
     string stringValue;
     public string StringValue { get { return stringValue; } set { stringValue = value; } }

     public StringWrapper(string s)
     {
     StringValue = s;
     }
  }   

   List<StringWrapper> testData = new List<StringWrapper>();

   // add data to the list / convert list of strings to list of string wrappers

  Table1.SetDataBinding(testdata);

While this solution works as expected it requires quite a few lines of code (mostly to convert list of strings to the list of string wrappers).

We can improve this solution by using LINQ and anonymous types- we’ll use LINQ query to create a new list of string wrappers (string wrapper will be an anonymous type in our case).

 var values = from data in testData select new { Value = data };

 Table1.SetDataBinding(values.ToList());

The last change we’re going to make is to move the LINQ code to an extension method:

public static class StringExtensions
  {
     public static IEnumerable CreateStringWrapperForBinding(this IEnumerable<string> strings)
     {
     var values = from data in strings
     select new { Value = data };

     return values.ToList();
     }

This way we can reuse the code by calling single method on any collection of strings:

Table1.SetDataBinding(testData.CreateStringWrapperForBinding());

Repeat a task with a time delay?

In my case, I had to execute a process if one of these conditions were true: if a previous process was completed or if 5 seconds had already passed. So, I did the following and worked pretty well:

private Runnable mStatusChecker;
private Handler mHandler;

class {
method() {
  mStatusChecker = new Runnable() {
            int times = 0;
            @Override
            public void run() {
                if (times < 5) {
                    if (process1.isRead()) {
                        executeProcess2();
                    } else {
                        times++;
                        mHandler.postDelayed(mStatusChecker, 1000);
                    }
                } else {
                    executeProcess2();
                }
            }
        };

        mHandler = new Handler();
        startRepeatingTask();
}

    void startRepeatingTask() {
       mStatusChecker.run();
    }

    void stopRepeatingTask() {
        mHandler.removeCallbacks(mStatusChecker);
    }


}

If process1 is read, it executes process2. If not, it increments the variable times, and make the Handler be executed after one second. It maintains a loop until process1 is read or times is 5. When times is 5, it means that 5 seconds passed and in each second, the if clause of process1.isRead() is executed.

Resizing UITableView to fit content

My Swift 5 implementation is to set the hight constraint of the tableView to the size of its content (contentSize.height). This method assumes you are using auto layout. This code should be placed inside the cellForRowAt tableView method.

tableView.heightAnchor.constraint(equalToConstant: tableView.contentSize.height).isActive = true

Set disable attribute based on a condition for Html.TextBoxFor

Yet another solution would be to create a Dictionary<string, object> before calling TextBoxFor and pass that dictionary. In the dictionary, add "disabled" key only if the textbox is to be diabled. Not the neatest solution but simple and straightforward.

HTTP POST Returns Error: 417 "Expectation Failed."

System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting this static property to false:

System.Net.ServicePointManager.Expect100Continue = false;

Some servers choke on that header and send back the 417 error you're seeing.

Give that a shot.

How do I hide the PHP explode delimiter from submitted form results?

You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.

$fh = fopen("employees.txt", "r"); if ($fh) {     while (($line = fgets($fh)) !== false) {         $line = trim($line);         echo "<option value='".$line."'>".$line."</option>";     } } else {     // error opening the file, do something } 

Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?

And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.

FirebaseInstanceIdService is deprecated

Use FirebaseMessaging instead

 FirebaseMessaging.getInstance().getToken()
    .addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull Task<String> task) {
          if (!task.isSuccessful()) {
            Log.w(TAG, "Fetching FCM registration token failed", task.getException());
            return;
          }

          // Get new FCM registration token
          String token = task.getResult();

          // Log and toast
          String msg = getString(R.string.msg_token_fmt, token);
          Log.d(TAG, msg);
          Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

Calculating a directory's size using Python?

Here is a one liner that does it recursively (recursive option available as of Python 3.5):

import os
import glob
print(sum(os.path.getsize(f) for f in glob.glob('**', recursive=True) if os.path.isfile(f))/(1024*1024))

Gradle DSL method not found: 'runProguard'

runProguard has been renamed to minifyEnabled in version 0.14.0 (2014/10/31) or more in Gradle.

To fix this, you need to change runProguard to minifyEnabled in the build.gradle file of your project.

enter image description here

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Example without getters or valueOf:

_x000D_
_x000D_
a = [1,2,3];_x000D_
a.join = a.shift;_x000D_
console.log(a == 1 && a == 2 && a == 3);
_x000D_
_x000D_
_x000D_

This works because == invokes toString which calls .join for Arrays.

Another solution, using Symbol.toPrimitive which is an ES6 equivalent of toString/valueOf:

_x000D_
_x000D_
let i = 0;_x000D_
let a = { [Symbol.toPrimitive]: () => ++i };_x000D_
_x000D_
console.log(a == 1 && a == 2 && a == 3);
_x000D_
_x000D_
_x000D_

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException in simple words is -> you have 10 students in your class (int array size 10) and you want to view the value of the 11th student (a student who does not exist)

if you make this int i[3] then i takes values i[0] i[1] i[2]

for your problem try this code structure

double[] array = new double[50];

    for (int i = 0; i < 24; i++) {

    }

    for (int j = 25; j < 50; j++) {

    }

How to make ng-repeat filter out duplicate results

I had an array of strings, not objects and i used this approach:

ng-repeat="name in names | unique"

with this filter:

angular.module('app').filter('unique', unique);
function unique(){
return function(arry){
        Array.prototype.getUnique = function(){
        var u = {}, a = [];
        for(var i = 0, l = this.length; i < l; ++i){
           if(u.hasOwnProperty(this[i])) {
              continue;
           }
           a.push(this[i]);
           u[this[i]] = 1;
        }
        return a;
    };
    if(arry === undefined || arry.length === 0){
          return '';
    }
    else {
         return arry.getUnique(); 
    }

  };
}

Cannot implicitly convert type from Task<>

Depending on what you're trying to do, you can either block with GetIdList().Result ( generally a bad idea, but it's hard to tell the context) or use a test framework that supports async test methods and have the test method do var results = await GetIdList();

VirtualBox error "Failed to open a session for the virtual machine"

Killing VM process dint work in my case.

Right click on the VM and click on "Discard Saved State".

 Right click on the VM and click on "Discard Saved State".

This worked for me.

Getting a "This application is modifying the autolayout engine from a background thread" error?

Here check out this line from the logs

$S12AppName18ViewControllerC11Func()ySS_S2StF + 4420

you can check that which function calling from the either background thread or where you are calling api method you need to call your function from the main thread like this.

DispatchQueue.main.async { func()}

func() is that function you want to call in the result of api call success or else.

Logs Here

This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.
 Stack:(
    0   Foundation                          0x00000001c570ce50 <redacted> + 96
    1   Foundation                          0x00000001c5501868 <redacted> + 32
    2   Foundation                          0x00000001c5544370 <redacted> + 540
    3   Foundation                          0x00000001c5543840 <redacted> + 396
    4   Foundation                          0x00000001c554358c <redacted> + 272
    5   Foundation                          0x00000001c5542e10 <redacted> + 264
    6   UIKitCore                           0x00000001f20d62e4 <redacted> + 488
    7   UIKitCore                           0x00000001f20d67b0 <redacted> + 36
    8   UIKitCore                           0x00000001f20d6eb0 <redacted> + 84
    9   Foundation                          0x00000001c571d124 <redacted> + 76
    10  Foundation                          0x00000001c54ff30c <redacted> + 108
    11  Foundation                          0x00000001c54fe304 <redacted> + 328
    12  UIKitCore                           0x00000001f151dc0c <redacted> + 156
    13  UIKitCore                           0x00000001f151e0c0 <redacted> + 152
    14  UIKitCore                           0x00000001f1514834 <redacted> + 868
    15  UIKitCore                           0x00000001f1518760 <redacted> + 104
    16  UIKitCore                           0x00000001f1543370 <redacted> + 1772
    17  UIKitCore                           0x00000001f1546598 <redacted> + 120
    18  UIKitCore                           0x00000001f14fc850 <redacted> + 1452
    19  UIKitCore                           0x00000001f168f318 <redacted> + 196
    20  UIKitCore                           0x00000001f168d330 <redacted> + 144
    21  AppName                        0x0000000100b8ed00 $S12AppName18ViewControllerC11Func()ySS_S2StF + 4420
    22  AppName                        0x0000000100b8d9f4 $S12CcfU0_y10Foundation4DataVSg_So13NSURLResponseCSgs5Error_pSgtcfU_ + 2384
    23  App NAme                        0x0000000100a98f3c $S10Foundation4DataVSgSo13NSURLResponseCSgs5Error_pSgIegggg_So6NSDataCSgAGSo7NSErrorCSgIeyByyy_TR + 316
    24  CFNetwork                           0x00000001c513aa00 <redacted> + 32
    25  CFNetwork                           0x00000001c514f1a0 <redacted> + 176
    26  Foundation                          0x00000001c55ed8bc <redacted> + 16
    27  Foundation                          0x00000001c54f5ab8 <redacted> + 72
    28  Foundation                          0x00000001c54f4f8c <redacted> + 740
    29  Foundation                          0x00000001c55ef790 <redacted> + 272
    30  libdispatch.dylib                   0x000000010286f824 _dispatch_call_block_and_release + 24
    31  libdispatch.dylib                   0x0000000102870dc8 _dispatch_client_callout + 16
    32  libdispatch.dylib                   0x00000001028741c4 _dispatch_continuation_pop + 528
    33  libdispatch.dylib                   0x0000000102873604 _dispatch_async_redirect_invoke + 632
    34  libdispatch.dylib                   0x00000001028821dc _dispatch_root_queue_drain + 376
    35  libdispatch.dylib                   0x0000000102882bc8 _dispatch_worker_thread2 + 156
    36  libsystem_pthread.dylib             0x00000001c477917c _pthread_wqthread + 472
    37  libsystem_pthread.dylib             0x00000001c477bcec start_wqthread + 4
)

how to configure apache server to talk to HTTPS backend server?

In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service to https://my-service helped.

Show hide div using codebehind

RegisteredClientScriptBlock adds the script at the top of the page on the post-back with no assurance about the order, meaning that either the call is being injected after the function declaration (your js file with the function is inlined after your call) or when the script tries to execute the div is probably not there yet 'cause the page is still rendering. A good idea is probably to simulate the two scenarios I described above on firebug and see if you get similar errors.

My guess is this would work if you append the script at the bottom of the page with RegisterStartupScript - worth a shot at least.

Anyway, as an alternative solution if you add the runat="server" attribute to the div you will be able to access it by its id in the codebehind (without reverting to js - how cool that might be), and make it disappear like this:

data.visible = false

How to read a text-file resource into Java unit test?

First make sure that abc.xml is being copied to your output directory. Then you should use getResourceAsStream():

InputStream inputStream = 
    Thread.currentThread().getContextClassLoader().getResourceAsStream("test/resources/abc.xml");

Once you have the InputStream, you just need to convert it into a string. This resource spells it out: http://www.kodejava.org/examples/266.html. However, I'll excerpt the relevent code:

public String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {        
        return "";
    }
}

dplyr mutate with conditional values

Try this:

myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))

giving:

  V1 V2 V3 V4 V5
1  1  2  3  5  1
2  2  4  4  1  2
3  1  4  1  1  0
4  4  5  1  3  0
5  5  5  5  4  0

or this:

myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))

giving:

  V1 V2 V3 V4 V5
1  1  2  3  5  1
2  2  4  4  1  2
3  1  4  1  1  0
4  4  5  1  3  0
5  5  5  5  4  0

Note

Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.

Above used this input:

myfile <- 
structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L, 
5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))

Update 1 Since originally posted dplyr has changed %.% to %>% so have modified answer accordingly.

Update 2 dplyr now has case_when which provides another solution:

myfile %>% 
       mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1, 
                             V2 == 4 & V3 != 1 ~ 2,
                             TRUE ~ 0))

Maven Error: Could not find or load main class

Unless you need the 'maven-assembly-plugin' for reasons other than setting the mainClass, you could use the 'maven-jar-plugin' plugin.

     <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <index>true</index>
                    <manifest>
                        <mainClass>your.package.yourprogram.YourMainClass</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
     </plugins>

You can see the plugin in practise in the ATLauncher.

The 'mainClass' element should be set to the class that you have the entry point to your program in eg:

package your.package.yourprogram;

public class YourMainClass {

    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Where to put default parameter value in C++?

Although this is an "old" thread, I still would like to add the following to it:

I've experienced the next case:

  • In the header file of a class, I had
int SetI2cSlaveAddress( UCHAR addr, bool force );
  • In the source file of that class, I had
int CI2cHal::SetI2cSlaveAddress( UCHAR addr, bool force = false )
{
   ...
}

As one can see, I had put the default value of the parameter "force" in the class source file, not in the class header file.

Then I used that function in a derived class as follows (derived class inherited the base class in a public way):

SetI2cSlaveAddress( addr );

assuming it would take the "force" parameter as "false" 'for granted'.

However, the compiler (put in c++11 mode) complained and gave me the following compiler error:

/home/.../mystuff/domoproject/lib/i2cdevs/max6956io.cpp: In member function 'void CMax6956Io::Init(unsigned char, unsigned char, unsigned int)':
/home/.../mystuff/domoproject/lib/i2cdevs/max6956io.cpp:26:30: error: no matching function for call to 'CMax6956Io::SetI2cSlaveAddress(unsigned char&)'
/home/.../mystuff/domoproject/lib/i2cdevs/max6956io.cpp:26:30: note: candidate is:
In file included from /home/geertvc/mystuff/domoproject/lib/i2cdevs/../../include/i2cdevs/max6956io.h:35:0,
                 from /home/geertvc/mystuff/domoproject/lib/i2cdevs/max6956io.cpp:1:
/home/.../mystuff/domoproject/lib/i2cdevs/../../include/i2chal/i2chal.h:65:9: note: int CI2cHal::SetI2cSlaveAddress(unsigned char, bool)
/home/.../mystuff/domoproject/lib/i2cdevs/../../include/i2chal/i2chal.h:65:9: note:   candidate expects 2 arguments, 1 provided
make[2]: *** [lib/i2cdevs/CMakeFiles/i2cdevs.dir/max6956io.cpp.o] Error 1
make[1]: *** [lib/i2cdevs/CMakeFiles/i2cdevs.dir/all] Error 2
make: *** [all] Error 2

But when I added the default parameter in the header file of the base class:

int SetI2cSlaveAddress( UCHAR addr, bool force = false );

and removed it from the source file of the base class:

int CI2cHal::SetI2cSlaveAddress( UCHAR addr, bool force )

then the compiler was happy and all code worked as expected (I could give one or two parameters to the function SetI2cSlaveAddress())!

So, not only for the user of a class it's important to put the default value of a parameter in the header file, also compiling and functional wise it apparently seems to be a must!

Properties private set;

Depending on the scope of my application, I like to put the object hydration mechanisms in the object itself. I'll wrap the data reader with a custom object and pass it a delegate that gets executed once the query returns. The delegate gets passed the DataReader. Then, since I'm in my smart business object, I can hydrate away with my private setters.

Edit for Pseudo-Code

The "DataAccessWrapper" wraps all of the connection and object lifecycle management for me. So, when I call "ExecuteDataReader," it creates the connection, with the passed proc (there's an overload for params,) executes it, executes the delegate and then cleans up after itself.

public class User
{
    public static List<User> GetAllUsers()
    {
        DataAccessWrapper daw = new DataAccessWrapper();
        return (List<User>)(daw.ExecuteDataReader("MyProc", new ReaderDelegate(ReadList)));
    }

    protected static object ReadList(SQLDataReader dr)
    {
        List<User> retVal = new List<User>();
        while(dr.Read())
        {
            User temp = new User();
            temp.Prop1 = dr.GetString("Prop1");
            temp.Prop2 = dr.GetInt("Prop2");
            retVal.Add(temp);
        }
        return retVal;
    }
}

How to open a second activity on click of button in android app

add below code to activity_main.xml file:

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="buttonClick"
        android:text="@string/button" />

and just add the below method to the MainActivity.java file:

public void buttonClick(View view){
  Intent i = new Intent(getApplicationContext()SendPhotos.class);
  startActivity(i);
}

How would I get everything before a : in a string Python

partition() may be better then split() for this purpose as it has the better predicable results for situations you have no delimiter or more delimiters.