Programs & Examples On #Getmessage

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

MultipartException: Current request is not a multipart request

Check the file which you have selected in the request.

For me i was getting the error because the file was not present in the system, as i have imported the request from some other machine.

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

These steps worked for me on several Systems using Ubuntu 16.04, Apache 2.4, MariaDB, PDO

  1. log into MYSQL as root

    mysql -u root
    
  2. Grant privileges. To a new user execute:

    CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
    GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost';
    FLUSH PRIVILEGES;
    

    UPDATE for Google Cloud Instances

    MySQL on Google Cloud seem to require an alternate command (mind the backticks).

    GRANT ALL PRIVILEGES ON `%`.* TO 'newuser'@'localhost';
    
  3. bind to all addresses:

    The easiest way is to comment out the line in your /etc/mysql/mariadb.conf.d/50-server.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf file, depending on what system you are running:

    #bind-address = 127.0.0.1 
    
  4. exit mysql and restart mysql

    exit
    service mysql restart
    

By default it binds only to localhost, but if you comment the line it binds to all interfaces it finds. Commenting out the line is equivalent to bind-address=*.

To check the binding of mysql service execute as root:

netstat -tupan | grep mysql

The request was rejected because no multipart boundary was found in springboot

I was having the same problem while making a POST request from Postman and later I could solve the problem by setting a custom Content-Type with a boundary value set along with it like this.

I thought people can run into similar problem and hence, I'm sharing my solution.

postman

Add my custom http header to Spring RestTemplate request / extend RestTemplate

Here's a method I wrote to check if an URL exists or not. I had a requirement to add a request header. It's Groovy but should be fairly simple to adapt to Java. Essentially I'm using the org.springframework.web.client.RestTemplate#execute(java.lang.String, org.springframework.http.HttpMethod, org.springframework.web.client.RequestCallback, org.springframework.web.client.ResponseExtractor<T>, java.lang.Object...) API method. I guess the solution you arrive at depends at least in part on the HTTP method you want to execute. The key take away from example below is that I'm passing a Groovy closure (The third parameter to method restTemplate.execute(), which is more or less, loosely speaking a Lambda in Java world) that is executed by the Spring API as a callback to be able to manipulate the request object before Spring executes the command,

boolean isUrlExists(String url) {
    try {
      return (restTemplate.execute(url, HttpMethod.HEAD,
              { ClientHttpRequest request -> request.headers.add('header-name', 'header-value') },
              { ClientHttpResponse response -> response.headers }) as HttpHeaders)?.get('some-response-header-name')?.contains('some-response-header-value')
    } catch (Exception e) {
      log.warn("Problem checking if $url exists", e)
    }
    false
  }

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

You just rebuilt your project

compile fileTree(dir: 'libs', include: ['*.jar'])

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

I had the same issue, the problem I had was I imported the wrong environment variable, which means that my secret key for AWS was wrong. Based on reading all the answers, I would verify that all your access ID and secret key is right and there are no additional characters or anything.

How to disable spring security for particular url

This may be not the full answer to your question, however if you are looking for way to disable csrf protection you can do:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/web/admin/**").hasAnyRole(ADMIN.toString(), GUEST.toString())
                .anyRequest().permitAll()
                .and()
                .formLogin().loginPage("/web/login").permitAll()
                .and()
                .csrf().ignoringAntMatchers("/contact-email")
                .and()
                .logout().logoutUrl("/web/logout").logoutSuccessUrl("/web/").permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("admin").roles(ADMIN.toString())
                .and()
                .withUser("guest").password("guest").roles(GUEST.toString());
    }

}

I have included full configuration but the key line is:

.csrf().ignoringAntMatchers("/contact-email")

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

Using MAMP I changed the host=localhost to host=127.0.0.1. But a new issue came "connection refused"

Solved this by putting 'port' => '8889', in 'Datasources' => [

java.lang.NoClassDefFoundError: org/json/JSONObject

Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20080701</version>
</dependency>

No content to map due to end-of-input jackson parser

In my case the problem was caused by my passing a null InputStream to the ObjectMapper.readValue call:

ObjectMapper objectMapper = ...
InputStream is = null; // The code here was returning null.
Foo foo = objectMapper.readValue(is, Foo.class)

I am guessing that this is the most common reason for this exception.

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

I am sure what Artem Bilan has explained here might be one of the reasons for this error:

Caused by: com.rabbitmq.client.AuthenticationFailureException: 
ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. 
For details see the

but the solution for me was that I logged in to rabbitMQ admin page (http://localhost:15672/#/users) with the default user name and password which is guest/guest then added a new user and for that new user I enabled the permission to access it from virtual host and then used the new user name and password instead of default guest and that cleared the error.

enter image description here

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

change

public static final String URL = "http://api-Location";

to

public static final String URL = "https://api-Location"

it's happen because i'm using 000webhostapp app

Multipart File upload Spring Boot

@RequestBody MultipartFile[] submissions

should be

@RequestParam("file") MultipartFile[] submissions

The files are not the request body, they are part of it and there is no built-in HttpMessageConverter that can convert the request to an array of MultiPartFile.

You can also replace HttpServletRequest with MultipartHttpServletRequest, which gives you access to the headers of the individual parts.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.

The JSON snippet you have posted is malformed.

You have posted:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe"[{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }]

while the correct JSON would be:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe" : [{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }
        ]
    }
]

Automatically scroll down chat div

if you just scrollheight it will make a problem when user will want to see his previous message. so you need to make something that when new message come only then the code. use jquery latest version. 1.here I checked the height before message loaded. 2. again check the new height. 3. if the height is different only that time it will scroll otherwise it will not scroll. 4. not in the if condition you can put any ringtone or any other feature that you need. that will play when new message will come. thanks

var oldscrollHeight = $("#messages").prop("scrollHeight");
$.get('msg_show.php', function(data) {
    div.html(data);
    var newscrollHeight = $("#messages").prop("scrollHeight"); //Scroll height after the request
    if (newscrollHeight > oldscrollHeight) {
        $("#messages").animate({
            scrollTop: newscrollHeight
        }, 'normal'); //Autoscroll to bottom of div
    }

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

Use EntityScanner if you can bear external dependency.It will inject your all entity classes seamlessly even from multiple packages. Just add following line after configuration setup.

Configuration configuration = new Configuration().configure();    
EntityScanner.scanPackages("com.fz.epms.db.model.entity").addTo(configuration);
// And following depencency if you are using Maven
<dependency>
        <groupId>com.github.v-ladynev</groupId>
        <artifactId>fluent-hibernate-core</artifactId>
        <version>0.3.1</version>
</dependency>

This way you don't need to declare all entities in hibernate mapping file.

Exception is never thrown in body of corresponding try statement

A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}-block can throw (or a super class of that).

try {
    //do something that throws ExceptionA, e.g.
    throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
    //do something to handle the exception, e.g.
    System.out.println("Message: " + e.getMessage());
}

What you are trying to do is this:

try {
    throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
    System.out.println("Message: " + e.getMessage());
}

This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement.

How do I debug jquery AJAX calls?

2020 answer with Chrome dev tools

To debug any XHR request:

  1. Open Chrome DEV tools (F12)
  2. Right-click your Ajax url in the console

Chrome console Ajax request

for a GET request:

  • click Open in new tab

for a POST request:

  1. click Reveal in Network panel

  2. In the Network panel:

    1. click on your request

    2. click on the response tab to see the details Chrome Network panel's response tab

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

Try enabling openssl extension in your php.ini if it is disabled. This way I could access the web service without need of any extra arguments, i.e.,

$client = new SoapClient(url);

no suitable HttpMessageConverter found for response type

This is not answering the problem but if anyone comes to this question when they stumble upon this exception of no suitable message converter found, here is my problem and solution.

In Spring 4.0.9, we were able to send this

    JSONObject jsonCredential = new JSONObject();
    jsonCredential.put(APPLICATION_CREDENTIALS, data);

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

ResponseEntity<String> res = restTemplate.exchange(myRestUrl), HttpMethod.POST,request, String.class);

In Spring 4.3.5 release, we starting seeing errors with the message that converter was not found.

The way Convertors work is that if you have it in your classpath, they get registered.

Jackson-asl was still in classpath but was not being recognized by spring. We replaced Jackson-asl with faster-xml jackson core.

Once we added I could see the converter being registered.

enter image description here

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

This means you are using JPA or hibernate in your code and performing modifying operation on DB without making the business logic transaction. So simple solution for this is mark your piece of code @Transactional

Why is my method undefined for the type object?

The line

Object EchoServer0;

says that you are allocating an Object named EchoServer0. This has nothing to do with the class EchoServer0. Furthermore, the object is not initialized, so EchoServer0 is null. Classes and identifiers have separate namespaces. This will actually compile:

String String = "abc";  // My use of String String was deliberate.

Please keep to the Java naming standards: classes begin with a capital letter, identifiers begin with a small letter, constants and enums are all-capitals.

public final String ME = "Eric Jablow";
public final double GAMMA = 0.5772;
public enum Color { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET}
public COLOR background = Color.RED;

"PKIX path building failed" and "unable to find valid certification path to requested target"

goals:

  1. use https connections
  2. verify SSL chains
  3. do not deal with cacerts
  4. add certificate in runtime
  5. do not lose certificates from cacerts

How to do it:

  1. define own keystore
  2. put certificate into keystore
  3. redefine SSL default context with our custom class
  4. ???
  5. profit

My Keystore wrapper file:

public class CertificateManager {

    private final static Logger logger = Logger.getLogger(CertificateManager.class);

    private String keyStoreLocation;
    private String keyStorePassword;
    private X509TrustManager myTrustManager;
    private static KeyStore myTrustStore;

    public CertificateManager(String keyStoreLocation, String keyStorePassword) throws Exception {
        this.keyStoreLocation = keyStoreLocation;
        this.keyStorePassword = keyStorePassword;
        myTrustStore = createKeyStore(keyStoreLocation, keyStorePassword);
    }

    public void addCustomCertificate(String certFileName, String certificateAlias)
            throws Exception {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);
        Certificate certificate = myTrustStore.getCertificate(certificateAlias);
        if (certificate == null) {
            logger.info("Certificate not exists");
            addCertificate(certFileName, certificateAlias);
        } else {
            logger.info("Certificate exists");
        }
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(myTrustStore);
        for (TrustManager tm : tmf.getTrustManagers()) {
            if (tm instanceof X509TrustManager) {
                setMytrustManager((X509TrustManager) tm);
                logger.info("Trust manager found");
                break;
            }
        }
    }

    private InputStream fullStream(String fname) throws IOException {
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream resource = classLoader.getResourceAsStream(fname);
        try {
            if (resource != null) {
                DataInputStream dis = new DataInputStream(resource);
                byte[] bytes = new byte[dis.available()];
                dis.readFully(bytes);
                return new ByteArrayInputStream(bytes);
            } else {
                logger.info("resource not found");
            }
        } catch (Exception e) {
            logger.error("exception in certificate fetching as resource", e);
        }
        return null;
    }

    public static KeyStore createKeyStore(String keystore, String pass) throws Exception {
        try {
            InputStream in = CertificateManager.class.getClass().getResourceAsStream(keystore);
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(in, pass.toCharArray());
            logger.info("Keystore was created from resource file");
            return keyStore;
        } catch (Exception e) {
            logger.info("Fail to create keystore from resource file");
        }

        File file = new File(keystore);
        KeyStore keyStore = KeyStore.getInstance("JKS");
        if (file.exists()) {
            keyStore.load(new FileInputStream(file), pass.toCharArray());
            logger.info("Default keystore loaded");
        } else {
            keyStore.load(null, null);
            keyStore.store(new FileOutputStream(file), pass.toCharArray());
            logger.info("New keystore created");
        }
        return keyStore;
    }

    private void addCertificate(String certFileName, String certificateAlias) throws CertificateException,
            IOException, KeyStoreException, NoSuchAlgorithmException {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream certStream = fullStream(certFileName);
        Certificate certs = cf.generateCertificate(certStream);
        myTrustStore.setCertificateEntry(certificateAlias, certs);
        FileOutputStream out = new FileOutputStream(getKeyStoreLocation());
        myTrustStore.store(out, getKeyStorePassword().toCharArray());
        out.close();
        logger.info("Certificate pushed");
    }

    public String getKeyStoreLocation() {
        return keyStoreLocation;
    }

    public String getKeyStorePassword() {
        return keyStorePassword;
    }
    public X509TrustManager getMytrustManager() {
        return myTrustManager;
    }
    public void setMytrustManager(X509TrustManager myTrustManager) {
        this.myTrustManager = myTrustManager;
    }
}

This class will create keystore if necessary, and will be able to manage certificates inside of it. Now class for SSL context:

public class CustomTrustManager implements X509TrustManager {

    private final static Logger logger = Logger.getLogger(CertificateManager.class);

    private static SSLSocketFactory socketFactory;
    private static CustomTrustManager instance = new CustomTrustManager();
    private static List<CertificateManager> register = new ArrayList<>();

    public static CustomTrustManager getInstance() {
        return instance;
    }

    private X509TrustManager defaultTm;

    public void register(CertificateManager certificateManager) {
        for(CertificateManager manager : register) {
            if(manager == certificateManager) {
                logger.info("Certificate manager already registered");
                return;
            }
        }
        register.add(certificateManager);
        logger.info("New Certificate manager registered");
    }

    private CustomTrustManager() {
        try {
            String algorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);

            tmf.init((KeyStore) null);
            boolean found = false;
            for (TrustManager tm : tmf.getTrustManagers()) {
                if (tm instanceof X509TrustManager) {
                    defaultTm = (X509TrustManager) tm;
                    found = true;
                    break;
                }
            }
            if(found) {
                logger.info("Default trust manager found");
            } else {
                logger.warn("Default trust manager was not found");
            }

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{this}, null);
            SSLContext.setDefault(sslContext);
            socketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);


            logger.info("Custom trust manager was set");
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            logger.warn("Custom trust manager can't be set");
            e.printStackTrace();
        }
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        List<X509Certificate> out = new ArrayList<>();
        if (defaultTm != null) {
            out.addAll(Arrays.asList(defaultTm.getAcceptedIssuers()));
        }
        int defaultCount = out.size();
        logger.info("Default trust manager contain " + defaultCount + " certficates");
        for(CertificateManager manager : register) {
            X509TrustManager customTrustManager = manager.getMytrustManager();
            X509Certificate[] issuers = customTrustManager.getAcceptedIssuers();
            out.addAll(Arrays.asList(issuers));
        }
        logger.info("Custom trust managers contain " + (out.size() - defaultCount) + " certficates");
        X509Certificate[] arrayOut = new X509Certificate[out.size()];
        return out.toArray(arrayOut);
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain,
                                   String authType) throws CertificateException {
        for(CertificateManager certificateManager : register) {
            X509TrustManager customTrustManager = certificateManager.getMytrustManager();
            try {
                customTrustManager.checkServerTrusted(chain, authType);
                logger.info("Certificate chain (server) was aproved by custom trust manager");
                return;
            } catch (Exception e) {
            }
        }
        if (defaultTm != null) {
            defaultTm.checkServerTrusted(chain, authType);
            logger.info("Certificate chain (server) was aproved by default trust manager");
        } else {
            logger.info("Certificate chain (server) was rejected");
            throw new CertificateException("Can't check server trusted certificate.");
        }
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain,
                                   String authType) throws CertificateException {
        try {
            if (defaultTm != null) {
                defaultTm.checkClientTrusted(chain, authType);
                logger.info("Certificate chain (client) was aproved by default trust manager");
            } else {
                throw new NullPointerException();
            }
        } catch (Exception e) {
            for(CertificateManager certificateManager : register) {
                X509TrustManager customTrustManager = certificateManager.getMytrustManager();
                try {
                    customTrustManager.checkClientTrusted(chain, authType);
                    logger.info("Certificate chain (client) was aproved by custom trust manager");
                    return;
                } catch (Exception e1) {
                }
            }
            logger.info("Certificate chain (client) was rejected");
            throw new CertificateException("Can't check client trusted certificate.");
        }
    }

    public SSLSocketFactory getSocketFactory() {
        return socketFactory;
    }
}

This class made as singleton, because only one defaultSSL context allowed. So, now usage:

            CertificateManager certificateManager = new CertificateManager("C:\\myapplication\\mykeystore.jks", "changeit");
            String certificatePath = "C:\\myapplication\\public_key_for_your_ssl_service.crt";
            try {
                certificateManager.addCustomCertificate(certificatePath, "alias_for_public_key_for_your_ssl_service");
            } catch (Exception e) {
                log.error("Can't add custom certificate");
                e.printStackTrace();
            }
            CustomTrustManager.getInstance().register(certificateManager);

Possibly, it will not work with this settings, because I keep certificate file inside of resource folder, so my path is not absolute. But generally, it work perfectly.

Date in to UTC format Java

What Time Zones?

No where in your question do you mention time zone. What time zone is implied that input string? What time zone do you want for your output? And, UTC is a time zone (or lack thereof depending on your mindset) not a string format.

ISO 8601

Your input string is in ISO 8601 format, except that it lacks an offset from UTC.

Joda-Time

Here is some example code in Joda-Time 2.3 to show you how to handle time zones. Joda-Time has built-in default formatters for parsing and generating String representations of date-time values.

String input = "2013-10-22T01:37:56";
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
DateTime dateTimeMontréal = dateTimeUtc.withZone( DateTimeZone.forID( "America/Montreal" );
String output = dateTimeMontréal.toString();

As for generating string representations in other formats, search StackOverflow for "Joda format".

Spring MVC Missing URI template variable

This error may happen when mapping variables you defined in REST definition do not match with @PathVariable names.

Example: Suppose you defined in the REST definition

@GetMapping(value = "/{appId}", produces = "application/json", consumes = "application/json")

Then during the definition of the function, it should be

public ResponseEntity<List> getData(@PathVariable String appId)

This error may occur when you use any other variable other than defined in the REST controller definition with @PathVariable. Like, the below code will raise the error as ID is different than appId variable name:

public ResponseEntity<List> getData(@PathVariable String ID)

Handle spring security authentication exceptions with @ExceptionHandler

This is a very interesting problem that Spring Security and Spring Web framework is not quite consistent in the way they handle the response. I believe it has to natively support error message handling with MessageConverter in a handy way.

I tried to find an elegant way to inject MessageConverter into Spring Security so that they could catch the exception and return them in a right format according to content negotiation. Still, my solution below is not elegant but at least make use of Spring code.

I assume you know how to include Jackson and JAXB library, otherwise there is no point to proceed. There are 3 Steps in total.

Step 1 - Create a standalone class, storing MessageConverters

This class plays no magic. It simply stores the message converters and a processor RequestResponseBodyMethodProcessor. The magic is inside that processor which will do all the job including content negotiation and converting the response body accordingly.

public class MessageProcessor { // Any name you like
    // List of HttpMessageConverter
    private List<HttpMessageConverter<?>> messageConverters;
    // under org.springframework.web.servlet.mvc.method.annotation
    private RequestResponseBodyMethodProcessor processor;

    /**
     * Below class name are copied from the framework.
     * (And yes, they are hard-coded, too)
     */
    private static final boolean jaxb2Present =
        ClassUtils.isPresent("javax.xml.bind.Binder", MessageProcessor.class.getClassLoader());

    private static final boolean jackson2Present =
        ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", MessageProcessor.class.getClassLoader()) &&
        ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", MessageProcessor.class.getClassLoader());

    private static final boolean gsonPresent =
        ClassUtils.isPresent("com.google.gson.Gson", MessageProcessor.class.getClassLoader());

    public MessageProcessor() {
        this.messageConverters = new ArrayList<HttpMessageConverter<?>>();

        this.messageConverters.add(new ByteArrayHttpMessageConverter());
        this.messageConverters.add(new StringHttpMessageConverter());
        this.messageConverters.add(new ResourceHttpMessageConverter());
        this.messageConverters.add(new SourceHttpMessageConverter<Source>());
        this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());

        if (jaxb2Present) {
            this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
        }
        if (jackson2Present) {
            this.messageConverters.add(new MappingJackson2HttpMessageConverter());
        }
        else if (gsonPresent) {
            this.messageConverters.add(new GsonHttpMessageConverter());
        }

        processor = new RequestResponseBodyMethodProcessor(this.messageConverters);
    }

    /**
     * This method will convert the response body to the desire format.
     */
    public void handle(Object returnValue, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        ServletWebRequest nativeRequest = new ServletWebRequest(request, response);
        processor.handleReturnValue(returnValue, null, new ModelAndViewContainer(), nativeRequest);
    }

    /**
     * @return list of message converters
     */
    public List<HttpMessageConverter<?>> getMessageConverters() {
        return messageConverters;
    }
}

Step 2 - Create AuthenticationEntryPoint

As in many tutorials, this class is essential to implement custom error handling.

public class CustomEntryPoint implements AuthenticationEntryPoint {
    // The class from Step 1
    private MessageProcessor processor;

    public CustomEntryPoint() {
        // It is up to you to decide when to instantiate
        processor = new MessageProcessor();
    }

    @Override
    public void commence(HttpServletRequest request,
        HttpServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {

        // This object is just like the model class, 
        // the processor will convert it to appropriate format in response body
        CustomExceptionObject returnValue = new CustomExceptionObject();
        try {
            processor.handle(returnValue, request, response);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}

Step 3 - Register the entry point

As mentioned, I do it with Java Config. I just show the relevant configuration here, there should be other configuration such as session stateless, etc.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().authenticationEntryPoint(new CustomEntryPoint());
    }
}

Try with some authentication fail cases, remember the request header should include Accept : XXX and you should get the exception in JSON, XML or some other formats.

Handle Guzzle exception and get HTTP body

Guzzle 6.x

Per the docs, the exception types you may need to catch are:

  • GuzzleHttp\Exception\ClientException for 400-level errors
  • GuzzleHttp\Exception\ServerException for 500-level errors
  • GuzzleHttp\Exception\BadResponseException for both (it's their superclass)

Code to handle such errors thus now looks something like this:

$client = new GuzzleHttp\Client;
try {
    $client->get('http://google.com/nosuchpage');    
}
catch (GuzzleHttp\Exception\ClientException $e) {
    $response = $e->getResponse();
    $responseBodyAsString = $response->getBody()->getContents();
}

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

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

NullPointerException with JSP can also happen if:

A getter returns a non-public inner class.

This code will fail if you remove Getters's access modifier or make it private or protected.

JAVA:

package com.myPackage;
public class MyClass{ 
    //: Must be public or you will get:
    //: org.apache.jasper.JasperException: 
    //: java.lang.NullPointerException
    public class Getters{
        public String 
        myProperty(){ return(my_property); }
    };;

    //: JSP EL can only access functions:
    private Getters _get;
    public  Getters  get(){ return _get; }

    private String 
    my_property;

    public MyClass(String my_property){
        super();
        this.my_property    = my_property;
        _get = new Getters();
    };;
};;

JSP

<%@ taglib uri   ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
    MyClass inst = new MyClass("[PROP_VALUE]");
    pageContext.setAttribute("my_inst", inst ); 
%><html lang="en"><body>
    ${ my_inst.get().myProperty() }
</body></html>

The APR based Apache Tomcat Native library was not found on the java.library.path

Regarding the original question asked in the title ...

  • sudo apt-get install libtcnative-1

  • or if you are on RHEL Linux yum install tomcat-native

The documentation states you need http://tomcat.apache.org/native-doc/

  • sudo apt-get install libapr1.0-dev libssl-dev
  • or RHEL yum install apr-devel openssl-devel

IOException: read failed, socket might closed - Bluetooth on Android 4.3

i also faced with this problem,you could solve it in 2 ways , as mentioned earlier use reflection to create the socket Second one is, client is looking for a server with given UUID and if your server isn't running parallel to client then this happens. Create a server with given client UUID and then listen and accept the client from server side.It will work.

How to add Headers on RESTful call using Jersey Client API

Here is an example how I do it.

import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import java.util.Map;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>() {
}.getType();
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("key1", "value1");
formData.add("key1", "value2");
WebTarget webTarget = ClientBuilder.newClient().target("https://some.server.url/");
String response = webTarget.path("subpath/subpath2").request().post(Entity.form(formData), String.class);
Map<String, String> gsonResponse = gson.fromJson(response, type);

Update query with PDO and MySQL

  1. Your UPDATE syntax is wrong
  2. You probably meant to update a row not all of them so you have to use WHERE clause to target your specific row

Change

UPDATE `access_users`   
      (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
      VALUES (:firstname, :surname, :telephone, :email)

to

UPDATE `access_users`   
   SET `contact_first_name` = :firstname,
       `contact_surname` = :surname,
       `contact_email` = :email,
       `telephone` = :telephone 
 WHERE `user_id` = :user_id -- you probably have some sort of id 

Get Selected Item Using Checkbox in Listview

Full reference present at : listview with checkbox android studio Pass selected items to next activity

Main source code is as below.

Create a model class first

public class Model {

    private boolean isSelected;
    private String animal;

    public String getAnimal() {
        return animal;
    }

    public void setAnimal(String animal) {
        this.animal = animal;
    }

    public boolean getSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}

Then in adapter class, setTags to checkbox. Use those tags in onclicklistener of checkbox.

public class CustomAdapter  extends BaseAdapter {

    private Context context;
    public static ArrayList<Model> modelArrayList;


    public CustomAdapter(Context context, ArrayList<Model> modelArrayList) {

        this.context = context;
        this.modelArrayList = modelArrayList;

    }

    @Override
    public int getViewTypeCount() {
        return getCount();
    }
    @Override
    public int getItemViewType(int position) {

        return position;
    }

    @Override
    public int getCount() {
        return modelArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return modelArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.lv_item, null, true);

            holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
            holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);

            convertView.setTag(holder);
        }else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)convertView.getTag();
        }


        holder.checkBox.setText("Checkbox "+position);
        holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());

        holder.checkBox.setChecked(modelArrayList.get(position).getSelected());

        holder.checkBox.setTag(R.integer.btnplusview, convertView);
        holder.checkBox.setTag( position);
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                TextView tv = (TextView) tempview.findViewById(R.id.animal); 
                Integer pos = (Integer)  holder.checkBox.getTag();
                Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();

                if(modelArrayList.get(pos).getSelected()){
                    modelArrayList.get(pos).setSelected(false);
                }else {
                    modelArrayList.get(pos).setSelected(true);
                }

            }
        });

        return convertView;
    }

    private class ViewHolder {

        protected CheckBox checkBox;
        private TextView tvAnimal;

    }

}

Scale Image to fill ImageView width and keep aspect ratio

Without using any custom classes or libraries:

<ImageView
    android:id="@id/img"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="fitCenter" />

scaleType="fitCenter" (default when omitted)

  • will make it as wide as the parent allows and up/down-scale as needed keeping aspect ratio.

scaleType="centerInside"

  • if the intrinsic width of src is smaller than parent width
    will center the image horizontally
  • if the intrinsic width of src is larger than parent width
    will make it as wide as the parent allows and down-scale keeping aspect ratio.

It doesn't matter if you use android:src or ImageView.setImage* methods and the key is probably the adjustViewBounds.

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

It worked for me after adding the following dependency in pom,

<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-validator</artifactId>
 <version>4.3.0.Final</version>
</dependency>

android.os.NetworkOnMainThreadException with android 4.2

Please make sure that you don't do any network access on UI Thread, instead do it in Async Task

The reason why your application crashes on Android versions 3.0 and above, but works fine on Android 2.x is because since HoneyComb are much stricter about abuse against the UI Thread. For example, when an Android device running HoneyComb or above detects a network access on the UI thread, a NetworkOnMainThreadException will be thrown.

See this

How to read file from res/raw by name

You can read files in raw/res using getResources().openRawResource(R.raw.myfilename).

BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt or my_data.bin will not be listed in R.

Android - How to download a file from a webserver

Mr.Iam4fun your code answer here..You will use thread...

   findViewById(R.id.download).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            new Thread(new Runnable() {
                public void run() {
                    DownloadFiles();
                }
            }).start();

And,then..

 public void DownloadFiles(){

        try {
            URL u = new URL("http://www.qwikisoft.com/demo/ashade/20001.kml");
            InputStream is = u.openStream();

            DataInputStream dis = new DataInputStream(is);

            byte[] buffer = new byte[1024];
            int length;

            FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/" + "data/test.kml"));
            while ((length = dis.read(buffer))>0) {
              fos.write(buffer, 0, length);
            }

          } catch (MalformedURLException mue) {
            Log.e("SYNC getUpdate", "malformed url error", mue);
          } catch (IOException ioe) {
            Log.e("SYNC getUpdate", "io error", ioe);
          } catch (SecurityException se) {
            Log.e("SYNC getUpdate", "security error", se);
          }
}
}

Sure, it will be working..

Printing Exception Message in java

try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}

How to save a bitmap on internal storage

private static void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().getAbsolutePath();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();

    String fname = "Image-"+ o +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete ();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

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

How to check if a folder exists

From SonarLint, if you already have the path, use path.toFile().exists() instead of Files.exists for better performance.

The Files.exists method has noticeably poor performance in JDK 8, and can slow an application significantly when used to check files that don't actually exist.

The same goes for Files.notExists, Files.isDirectory and Files.isRegularFile.

Noncompliant Code Example:

Path myPath;
if(java.nio.Files.exists(myPath)) {  // Noncompliant
    // do something
}

Compliant Solution:

Path myPath;
if(myPath.toFile().exists())) {
    // do something
}

How to log as much information as possible for a Java Exception?

The java.util.logging package is standard in Java SE. Its Logger includes an overloaded log method that accepts Throwable objects. It will log stacktraces of exceptions and their cause for you.

For example:

import java.util.logging.Level;
import java.util.logging.Logger;

[...]

Logger logger = Logger.getAnonymousLogger();
Exception e1 = new Exception();
Exception e2 = new Exception(e1);
logger.log(Level.SEVERE, "an exception was thrown", e2);

Will log:

SEVERE: an exception was thrown
java.lang.Exception: java.lang.Exception
    at LogStacktrace.main(LogStacktrace.java:21)
Caused by: java.lang.Exception
    at LogStacktrace.main(LogStacktrace.java:20)

Internally, this does exactly what @philipp-wendler suggests, by the way. See the source code for SimpleFormatter.java. This is just a higher level interface.

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

SmsListenerClass

public class SmsListener extends BroadcastReceiver {

static final String ACTION =
        "android.provider.Telephony.SMS_RECEIVED";

@Override
public void onReceive(Context context, Intent intent) {

    Log.e("RECEIVED", ":-:-" + "SMS_ARRIVED");

    // TODO Auto-generated method stub
    if (intent.getAction().equals(ACTION)) {

        Log.e("RECEIVED", ":-" + "SMS_ARRIVED");

        StringBuilder buf = new StringBuilder();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {

            Object[] pdus = (Object[]) bundle.get("pdus");

            SmsMessage[] messages = new SmsMessage[pdus.length];
            SmsMessage message = null;

            for (int i = 0; i < messages.length; i++) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    String format = bundle.getString("format");
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
                } else {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                }

                message = messages[i];
                buf.append("Received SMS from  ");
                buf.append(message.getDisplayOriginatingAddress());
                buf.append(" - ");
                buf.append(message.getDisplayMessageBody());
            }

            MainActivity inst = MainActivity.instance();
            inst.updateList(message.getDisplayOriginatingAddress(),message.getDisplayMessageBody());

        }

        Log.e("RECEIVED:", ":" + buf.toString());

        Toast.makeText(context, "RECEIVED SMS FROM :" + buf.toString(), Toast.LENGTH_LONG).show();

    }
}

Activity

@Override
public void onStart() {
    super.onStart();
    inst = this;
}

public static MainActivity instance() {
    return inst;
}

public void updateList(final String msg_from, String msg_body) {

    tvMessage.setText(msg_from + " :- " + msg_body);

    sendSMSMessage(msg_from, msg_body);

}

protected void sendSMSMessage(String phoneNo, String message) {

    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, message, null, null);
        Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}

Manifest

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>

<receiver android:name=".SmsListener">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

for wamp server use 10.0.2.2 for local host e.g. 10.0.2.2/phpMyAdmin

and for tomcat use 10.0.2.2:8080/server

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

I had faced the similar error when supporting one application. It was about the generated classes for a SOAP Webservice.

The issue was caused due to the missing classes. When javax.xml.bind.Marshaller was trying to marshal the jaxb object it was not finding all dependent classes which were generated by using wsdl and xsd. after adding the jar with all the classes at the class path the issue was resolved.

PHP MySQL Google Chart JSON - Complete Example

Some might encounter this error either locally or on the server:

syntax error var data = new google.visualization.DataTable(<?=$jsonTable?>);

This means that their environment does not support short tags the solution is to use this instead:

<?php echo $jsonTable; ?>

And everything should work fine!

How can I iterate JSONObject to get individual items

How about this?

JSONObject jsonObject = new JSONObject           (YOUR_JSON_STRING);
JSONObject ipinfo     = jsonObject.getJSONObject ("ipinfo");
String     ip_address = ipinfo.getString         ("ip_address");
JSONObject location   = ipinfo.getJSONObject     ("Location");
String     latitude   = location.getString       ("latitude");
System.out.println (latitude);

This sample code using "org.json.JSONObject"

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

You can write your own listener. It's same as HelmiB's answer but looks more natural:

Create listener interface:

public interface myAsyncTaskCompletedListener {
    void onMyAsynTaskCompleted(int responseCode, String result);
}

Then write your asynchronous task:

public class myAsyncTask extends AsyncTask<String, Void, String> {

    private myAsyncTaskCompletedListener listener;
    private int responseCode = 0;

    public myAsyncTask() {
    }

    public myAsyncTask(myAsyncTaskCompletedListener listener, int responseCode) {
        this.listener = listener;
        this.responseCode = responseCode;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }


    @Override
    protected String doInBackground(String... params) {
        String result;
        String param = (params.length == 0) ? null : params[0];
        if (param != null) {
            // Do some background jobs, like httprequest...
            return result;
        }
        return null;
    }

    @Override
    protected void onPostExecute(String finalResult) {
        super.onPostExecute(finalResult);
        if (!isCancelled()) {
            if (listener != null) {
                listener.onMyAsynTaskCompleted(responseCode, finalResult);
            }
        }
    }
}

Finally implement listener in activity:

public class MainActivity extends AppCompatActivity implements myAsyncTaskCompletedListener {

    @Override
    public void onMyAsynTaskCompleted(int responseCode, String result) {

        switch (responseCode) {
            case TASK_CODE_ONE: 
                // Do something for CODE_ONE
                break;
            case TASK_CODE_TWO:
                // Do something for CODE_TWO
                break;
            default: 
                // Show some error code
        }        
    }

And this is how you can call asyncTask:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Some other codes...
        new myAsyncTask(this,TASK_CODE_ONE).execute("Data for background job");
        // And some another codes...
}

how to show progress bar(circle) in an activity having a listview before loading the listview with data

I suggest you when working with listview or recyclerview to use SwipeRefreshLayout. Like this

    <android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swiperefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/card_recycler_view"
            android:scrollbars="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

</android.support.v4.widget.SwipeRefreshLayout>

Only wrap your view and this will create an animation of refresh when loading data or by swipping down the screen as we can do in many apps.
Here's the documentation of how to use it:
https://developer.android.com/training/swipe/add-swipe-interface.html https://developer.android.com/training/swipe/respond-refresh-request.html

Happy coding !

How can I read a text file in Android?

If you want to read file from sd card. Then following code might be helpful for you.

 StringBuilder text = new StringBuilder();
    try {
    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard,"testFile.txt");

        BufferedReader br = new BufferedReader(new FileReader(file));  
        String line;   
        while ((line = br.readLine()) != null) {
                    text.append(line);
                    Log.i("Test", "text : "+text+" : end");
                    text.append('\n');
                    } }
    catch (IOException e) {
        e.printStackTrace();                    

    }
    finally{
            br.close();
    }       
    TextView tv = (TextView)findViewById(R.id.amount);  

    tv.setText(text.toString()); ////Set the text to text view.
  }

    }

If you wan to read file from asset folder then

AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

Or If you wan to read this file from res/raw foldery, where the file will be indexed and is accessible by an id in the R file:

InputStream is = getResources().openRawResource(R.raw.test);     

Good example of reading text file from res/raw folder

How to convert TimeStamp to Date in Java?

Assuming you have a pre-existing java.util.Date date:

Timestamp timestamp = new Timestamp(long);
date.setTime( l_timestamp.getTime() );

Sending files using POST with HttpURLConnection

The solution of Jaydipsinh Zala didn't work for me, I don't know why but it seems to be close to the solution.

So merging this one with the great solution and explanation of Mihai Todor, the result is this class that currently works for me. If it helps someone:

MultipartUtility2V.java

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;

public class MultipartUtilityV2 {
    private HttpURLConnection httpConn;
    private DataOutputStream request;
    private final String boundary =  "*****";
    private final String crlf = "\r\n";
    private final String twoHyphens = "--";

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     *
     * @param requestURL
     * @throws IOException
     */
    public MultipartUtilityV2(String requestURL)
            throws IOException {

        // creates a unique boundary based on time stamp
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);

        httpConn.setRequestMethod("POST");
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        httpConn.setRequestProperty("Cache-Control", "no-cache");
        httpConn.setRequestProperty(
                "Content-Type", "multipart/form-data;boundary=" + this.boundary);

        request =  new DataOutputStream(httpConn.getOutputStream());
    }

    /**
     * Adds a form field to the request
     *
     * @param name  field name
     * @param value field value
     */
    public void addFormField(String name, String value)throws IOException  {
        request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
        request.writeBytes("Content-Disposition: form-data; name=\"" + name + "\""+ this.crlf);
        request.writeBytes("Content-Type: text/plain; charset=UTF-8" + this.crlf);
        request.writeBytes(this.crlf);
        request.writeBytes(value+ this.crlf);
        request.flush();
    }

    /**
     * Adds a upload file section to the request
     *
     * @param fieldName  name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
        request.writeBytes("Content-Disposition: form-data; name=\"" +
                fieldName + "\";filename=\"" +
                fileName + "\"" + this.crlf);
        request.writeBytes(this.crlf);

        byte[] bytes = Files.readAllBytes(uploadFile.toPath());
        request.write(bytes);
    }

    /**
     * Completes the request and receives response from the server.
     *
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public String finish() throws IOException {
        String response ="";

        request.writeBytes(this.crlf);
        request.writeBytes(this.twoHyphens + this.boundary +
                this.twoHyphens + this.crlf);

        request.flush();
        request.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            InputStream responseStream = new
                    BufferedInputStream(httpConn.getInputStream());

            BufferedReader responseStreamReader =
                    new BufferedReader(new InputStreamReader(responseStream));

            String line = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = responseStreamReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            responseStreamReader.close();

            response = stringBuilder.toString();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response;
    }
}

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

Use component scanning as given below, if com.project.action.PasswordHintAction is annotated with stereotype annotations

<context:component-scan base-package="com.project.action"/>

EDIT

I see your problem, in PasswordHintActionTest you are autowiring PasswordHintAction. But you did not create bean configuration for PasswordHintAction to autowire. Add one of stereotype annotation(@Component, @Service, @Controller) to PasswordHintAction like

@Component
public class PasswordHintAction extends BaseAction {
    private static final long serialVersionUID = -4037514607101222025L;
    private String username;

or create xml configuration in applicationcontext.xml like

<bean id="passwordHintAction" class="com.project.action.PasswordHintAction" />

The system cannot find the file specified in java

First Create folder same as path which you Specified. after then create File

File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");

if(!file.exists())
{
    dir.mkdir();
    file.createNewFile();
    System.out.println("File,Folder Created.);
}

Convert object to JSON string in C#

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

public class ReturnData 
{
    public int totalCount { get; set; }
    public List<ExceptionReport> reports { get; set; }  
}

public class ExceptionReport
{
    public int reportId { get; set; }
    public string message { get; set; }  
}


string json = JsonConvert.SerializeObject(myReturnData);

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

Try adding this piece of code. It worked for me.

_x000D_
_x000D_
$opts = array(_x000D_
    'ssl' => array('ciphers'=>'RC4-SHA', 'verify_peer'=>false, 'verify_peer_name'=>false)_x000D_
);_x000D_
// SOAP 1.2 client_x000D_
$params = array ('encoding' => 'UTF-8', 'verifypeer' => false, 'verifyhost' => false, 'soap_version' => SOAP_1_2, 'trace' => 1, 'exceptions' => 1, "connection_timeout" => 180, 'stream_context' => stream_context_create($opts) );_x000D_
$url = "http://www.webservicex.net/globalweather.asmx?WSDL";_x000D_
_x000D_
try{_x000D_
 $client = new SoapClient($url,$params );_x000D_
}_x000D_
catch(SoapFault $fault) {_x000D_
 echo '<br>'.$fault;_x000D_
}
_x000D_
_x000D_
_x000D_

Check if null Boolean is true results in exception

If you don't like extra null checks:

if (Boolean.TRUE.equals(value)) {...}

Driver executable must be set by the webdriver.ie.driver system property

  1. You will need InternetExplorer driver executable on your system. So download it from the hinted source (http://www.seleniumhq.org/download/) unpack it and place somewhere you can find it. In my example, I will assume you will place it to C:\Selenium\iexploredriver.exe

  2. Then you have to set it up in the system. Here is the Java code pasted from my Selenium project:

    File file = new File("C:/Selenium/iexploredriver.exe");
    System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
    WebDriver driver = new InternetExplorerDriver();
    

Basically, you have to set this property before you initialize driver

How do I enable php to work with postgresql?

I have to add in httpd.conf this line (Windows):

LoadFile "C:/Program Files (x86)/PostgreSQL/8.3/bin/libpq.dll"

Java image resize, maintain aspect ratio

All other answers show how to calculate the new image height in function of the new image width or vice-versa and how to resize the image using Java Image API. For those people who are looking for a straightforward solution I recommend any java image processing framework that can do this in a single line.

The exemple below uses Marvin Framework:

// 300 is the new width. The height is calculated to maintain aspect.
scale(image.clone(), image, 300);

Necessary import:

import static marvin.MarvinPluginCollection.*

read file from assets

cityfile.txt

   public void getCityStateFromLocal() {
        AssetManager am = getAssets();
        InputStream inputStream = null;
        try {
            inputStream = am.open("city_state.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        ObjectMapper mapper = new ObjectMapper();
        Map<String, String[]> map = new HashMap<String, String[]>();
        try {
            map = mapper.readValue(getStringFromInputStream(inputStream), new TypeReference<Map<String, String[]>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        ConstantValues.arrayListStateName.clear();
        ConstantValues.arrayListCityByState.clear();
        if (map.size() > 0)
        {
            for (Map.Entry<String, String[]> e : map.entrySet()) {
                CityByState cityByState = new CityByState();
                String key = e.getKey();
                String[] value = e.getValue();
                ArrayList<String> s = new ArrayList<String>(Arrays.asList(value));
                ConstantValues.arrayListStateName.add(key);
                s.add(0,"Select City");
                cityByState.addValue(s);
                ConstantValues.arrayListCityByState.add(cityByState);
            }
        }
        ConstantValues.arrayListStateName.add(0,"Select States");
    }
 // Convert InputStream to String
    public String getStringFromInputStream(InputStream is) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb + "";

    }

Eclipse error: "Editor does not contain a main type"

Did you import the packages for the file reading stuff.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

also here

cfiltering(numberOfUsers, numberOfMovies);

Are you trying to create an object or calling a method?

also another thing:

user_movie_matrix[userNo][movieNo]=rating;

you are assigning a value to a member of an instance as if it was a static variable also remove the Th in

private int user_movie_matrix[][];Th

Hope this helps.

Throwing exceptions in a PHP Try Catch block

throw $e->getMessage();

You try to throw a string

As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data

exception.getMessage() output with class name

I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:

public static void main(String[] args) {
    try {
        throw new RuntimeException("Cannot move file");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
    }
}

...you will see a popup that says exactly what you want.


However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:

public static void main(String[] args) {
    try {
        throw new Exception(new RuntimeException("Cannot move file"));
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                                      "Error: " + getRootCause(ex).getMessage());
    }
}

public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() != null)
        return getRootCause(throwable.getCause());

    return throwable;
}

Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.

Mocking Logger and LoggerFactory with PowerMock and Mockito

EDIT 2020-09-21: Since 3.4.0, Mockito supports mocking static methods, API is still incubating and is likely to change, in particular around stubbing and verification. It requires the mockito-inline artifact. And you don't need to prepare the test or use any specific runner. All you need to do is :

@Test
public void name() {
    try (MockedStatic<LoggerFactory> integerMock = mockStatic(LoggerFactory.class)) {
        final Logger logger = mock(Logger.class);
        integerMock.when(() -> LoggerFactory.getLogger(any(Class.class))).thenReturn(logger);
        new Controller().log();
        verify(logger).warn(any());
    }
}

The two inportant aspect in this code, is that you need to scope when the static mock applies, i.e. within this try block. And you need to call the stubbing and verification api from the MockedStatic object.


@Mick, try to prepare the owner of the static field too, eg :

@PrepareForTest({GoodbyeController.class, LoggerFactory.class})

EDIT1 : I just crafted a small example. First the controller :

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Controller {
    Logger logger = LoggerFactory.getLogger(Controller.class);

    public void log() { logger.warn("yup"); }
}

Then the test :

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Controller.class, LoggerFactory.class})
public class ControllerTest {

    @Test
    public void name() throws Exception {
        mockStatic(LoggerFactory.class);
        Logger logger = mock(Logger.class);
        when(LoggerFactory.getLogger(any(Class.class))).thenReturn(logger);
        
        new Controller().log();
        
        verify(logger).warn(anyString());
    }
}

Note the imports ! Noteworthy libs in the classpath : Mockito, PowerMock, JUnit, logback-core, logback-clasic, slf4j


EDIT2 : As it seems to be a popular question, I'd like to point out that if these log messages are that important and require to be tested, i.e. they are feature / business part of the system then introducing a real dependency that make clear theses logs are features would be a so much better in the whole system design, instead of relying on static code of a standard and technical classes of a logger.

For this matter I would recommend to craft something like= a Reporter class with methods such as reportIncorrectUseOfYAndZForActionX or reportProgressStartedForActionX. This would have the benefit of making the feature visible for anyone reading the code. But it will also help to achieve tests, change the implementations details of this particular feature.

Hence you wouldn't need static mocking tools like PowerMock. In my opinion static code can be fine, but as soon as the test demands to verify or to mock static behavior it is necessary to refactor and introduce clear dependencies.

How to view query error in PDO PHP

I'm using this without any additional settings:

if (!$st->execute()) {
    print_r($st->errorInfo());
}

Call to undefined method mysqli_stmt::get_result

Please read the user notes for this method:

http://php.net/manual/en/mysqli-stmt.get-result.php

It requires the mysqlnd driver... if it isn't installed on your webspace you will have to work with BIND_RESULT & FETCH!

https://secure.php.net/manual/en/mysqli-stmt.bind-result.php

https://secure.php.net/manual/en/mysqli-stmt.fetch.php

java calling a method from another class

You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.

So, instead of simply calling addWord("someWord"), you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();), and then call the method using that (i.e. list.addWord("someWord");.

However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord() static, or change the methods in the Words class so that they're not static.

My bad with the above paragraph - however you might want to reconsider ProcessInput() being a static method - does it really need to be?

Java - Reading XML file

One of the possible implementations:

File file = new File("userdata.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
        .newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();

when used with the XML content:

<credentials>
    <user>testusr</user>
    <password>testpwd</password>
</credentials>

results in "testusr" and "testpwd" getting assigned to the usr and pwd references above.

Total Number of Row Resultset getRow Method

I have solved that problem. The only I do is:

private int num_rows;

And then in your method using the resultset put this code

while (this.rs.next())
{

    this.num_rows++;
}

That's all

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

first Download the ssl certificate then you can go to your java bin path execute the below command in the console.

C:\java\JDK1.8.0_66-X64\bin>keytool -printcert -file C:\Users\lova\openapi.cer -keystore openapistore

Solving a "communications link failure" with JDBC and MySQL

In my case it was an idle timeout, that caused the connection to be dropped on the server. The connection was kept open, but not used for a long period of time. Then a client restart works, while I believe a reconnect will work as well.

A not bad solution is to have a daemon/service to ping the connection from time to time.

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

You might also see this error if you attempt to parse the same file twice from the same source.

I was parsing the file once to validate and again (from the same InputStream) to process - this produced the above error.

To get round this I parsed the source file into 2 different InputStreams, one to validate and one to process.

Fragment Inside Fragment

That may help those who works on Kotlin you can use extension function so create a kotlin file let's say "util.kt" and add this piece of code

fun Fragment.addChildFragment(fragment: Fragment, frameId: Int) {

    val transaction = childFragmentManager.beginTransaction()
    transaction.replace(frameId, fragment).commit()
}

Let's say this is the class of the child

class InputFieldPresentation: Fragment()
{
    var views: View? = null
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        views = inflater!!.inflate(R.layout.input_field_frag, container, false)
        return views
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ...
    }
    ...
}

Now you can add the children to the father fragment like this

 FatherPresentation:Fragment()
{
  ...

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val fieldFragment= InputFieldPresentation()
        addChildFragment(fieldFragment,R.id.fragmet_field)
    }
...
}

where R.id.fragmet_field is the id of the layout which will contain the fragment.This lyout is inside the father fragment of course. Here is an example

father_fragment.xml:

<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >

    ...

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:id="@+id/fragmet_field"
            android:orientation="vertical"
            >
        </LinearLayout>
    ...

    </LinearLayout>

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

The error seems to be thrown when you try and load they keystore from "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12" here:

ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() ); 

Have you tried replaceing "/" with "\\" in your file path? If that doesn't help it probably has to do with Java's Unlimited Strength Jurisdiction Policy Files. You could check this by writing a little program that does AES encryption. Try encrypting with a 128 bit key, then if that works, try with a 256 bit key and see if it fails.

Code that does AES encyrption:

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Test 
{
    final String ALGORITHM = "AES";                       //symmetric algorithm for data encryption
    final String PADDING_MODE = "/CBC/PKCS5Padding";      //Padding for symmetric algorithm
    final String CHAR_ENCODING = "UTF-8";                 //character encoding
    //final String CRYPTO_PROVIDER = "SunMSCAPI";             //provider for the crypto

    int AES_KEY_SIZE = 256;  //symmetric key size (128, 192, 256) if using 256 you must have the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files  installed

    private String doCrypto(String plainText) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException
    {
        byte[] dataToEncrypt = plainText.getBytes(CHAR_ENCODING);

        //get the symmetric key generator
        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
        keyGen.init(AES_KEY_SIZE); //set the key size

        //generate the key
        SecretKey skey = keyGen.generateKey();

        //convert to binary
        byte[] rawAesKey = skey.getEncoded();

        //initialize the secret key with the appropriate algorithm
        SecretKeySpec skeySpec = new SecretKeySpec(rawAesKey, ALGORITHM);

        //get an instance of the symmetric cipher
        Cipher aesCipher = Cipher.getInstance(ALGORITHM + PADDING_MODE);

        //set it to encrypt mode, with the generated key
        aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        //get the initialization vector being used (to be returned)
        byte[] aesIV = aesCipher.getIV();

        //encrypt the data
        byte[] encryptedData = aesCipher.doFinal(dataToEncrypt);    

        //initialize the secret key with the appropriate algorithm
        SecretKeySpec skeySpecDec = new SecretKeySpec(rawAesKey, ALGORITHM);

        //get an instance of the symmetric cipher
        Cipher aesCipherDec = Cipher.getInstance(ALGORITHM +PADDING_MODE);

        //set it to decrypt mode with the AES key, and IV
        aesCipherDec.init(Cipher.DECRYPT_MODE, skeySpecDec, new IvParameterSpec(aesIV));

        //decrypt and return the data
        byte[] decryptedData = aesCipherDec.doFinal(encryptedData);

        return new String(decryptedData, CHAR_ENCODING);
    }

    public static void main(String[] args)
    {
        String text = "Lets encrypt me";

        Test test = new Test();

        try {
            System.out.println(test.doCrypto(text));
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Does this code work for you?

You might also want to try specifying your bouncy castle provider in this line:

Cipher.getInstance(ALGORITHM +PADDING_MODE, "YOUR PROVIDER");

And see if it could be an error associated with bouncy castle.

Received fatal alert: handshake_failure through SSLHandshakeException

To troubleshoot from developer (item 1) and system admin (item 2 and 3) perspective:

  1. Enable SSL handshake debug at Java via -Djavax.net.debug=ssl:handshake:verbose.
  2. Install ssldump at server via sudo apt install ssldump or compile from source by following this link if you observe Unknown value in cipher when you run below step.
  3. At server, sudo ssldump -k <your-private-key> -i <your-network-interface>
  4. Check the log about real reason of the failure.

Example of not working handshake of ssldump log:

New TCP connection #1: 10.1.68.86(45308) <-> 10.1.68.83(5671)
1 1  0.0111 (0.0111)  C>S  Handshake
      ClientHello
        Version 3.3
        cipher suites
        TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
        TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
        TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
        TLS_RSA_WITH_AES_256_GCM_SHA384
        TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
        TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
        TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
        TLS_DHE_DSS_WITH_AES_256_GCM_SHA384
        TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
        TLS_RSA_WITH_AES_128_GCM_SHA256
        TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
        TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
        TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
        TLS_DHE_DSS_WITH_AES_128_GCM_SHA256
        TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
        TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
        TLS_RSA_WITH_AES_256_CBC_SHA256
        TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
        TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
        TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
        TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
        TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
        TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
        TLS_RSA_WITH_AES_256_CBC_SHA
        TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
        TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
        TLS_DHE_RSA_WITH_AES_256_CBC_SHA
        TLS_DHE_DSS_WITH_AES_256_CBC_SHA
        TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
        TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
        TLS_RSA_WITH_AES_128_CBC_SHA256
        TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
        TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
        TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
        TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
        TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
        TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
        TLS_RSA_WITH_AES_128_CBC_SHA
        TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
        TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
        TLS_DHE_RSA_WITH_AES_128_CBC_SHA
        TLS_DHE_DSS_WITH_AES_128_CBC_SHA
        TLS_EMPTY_RENEGOTIATION_INFO_SCSV
        compression methods
                  NULL
1 2  0.0122 (0.0011)  S>C  Alert
    level           fatal
    value           insufficient_security
1    0.0126 (0.0004)  S>C  TCP RST

Example of successful handshake of ssldump log

New TCP connection #1: 10.1.68.86(56558) <-> 10.1.68.83(8443)
1 1  0.0009 (0.0009)  C>S  Handshake
      ClientHello
        Version 3.3
        cipher suites
        TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
        TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
        TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
        Unknown value 0xcca9
        Unknown value 0xcca8
        Unknown value 0xccaa
        TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
        TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
        TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
        TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
        TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
        TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
        TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
        TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
        TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
        TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
        TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
        TLS_DHE_RSA_WITH_AES_256_CBC_SHA
        TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
        TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
        TLS_DHE_RSA_WITH_AES_128_CBC_SHA
        TLS_RSA_WITH_AES_256_GCM_SHA384
        TLS_RSA_WITH_AES_128_GCM_SHA256
        TLS_RSA_WITH_AES_256_CBC_SHA256
        TLS_RSA_WITH_AES_128_CBC_SHA256
        TLS_RSA_WITH_AES_256_CBC_SHA
        TLS_RSA_WITH_AES_128_CBC_SHA
        TLS_EMPTY_RENEGOTIATION_INFO_SCSV
        compression methods
                  NULL
1 2  0.0115 (0.0106)  S>C  Handshake
      ServerHello
        Version 3.3
        session_id[0]=

        cipherSuite         TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
        compressionMethod                   NULL
1 3  0.0115 (0.0000)  S>C  Handshake
      Certificate
1 4  0.0115 (0.0000)  S>C  Handshake
      ServerKeyExchange
Not enough data. Found 294 bytes (expecting 32767)
1 5    0.0115   (0.0000)    S>C    Handshake
        ServerHelloDone
1 6    0.0141   (0.0025)    C>S    Handshake
        ClientKeyExchange
Not enough data. Found 31 bytes (expecting 16384)
1 7    0.0141   (0.0000)    C>S    ChangeCipherSpec
1 8    0.0141   (0.0000)    C>S      Handshake
1 9    0.0149   (0.0008)    S>C    Handshake
1 10   0.0149   (0.0000)    S>C    ChangeCipherSpec
1 11   0.0149   (0.0000)    S>C      Handshake

Example of not working Java log

javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.778 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.779 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.779 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.780 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_RSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.780 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.780 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.781 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.781 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.781 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.782 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_RSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.782 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.782 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.782 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.783 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.783 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.783 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.783 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.783 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: T LS_DHE_RSA_WITH_AES_256_CBC_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 for TLS11
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.784 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_RSA_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_RSA_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.785 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 for TLS10 javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.786 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 for TLS10
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.787 MYT|HandshakeContext.java:294|Ignore unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 for TLS10
javax.net.ssl|WARNING|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.818 MYT|SignatureScheme.java:282|Signature algorithm, ed25519, is not supported by the underlying providers
javax.net.ssl|WARNING|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.818 MYT|SignatureScheme.java:282|Signature algorithm, ed448, is not supported by the underlying providers
javax.net.ssl|ALL|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.822 MYT|SignatureScheme.java:358|Ignore disabled signature sheme: rsa_md5
javax.net.ssl|INFO|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.822 MYT|AlpnExtension.java:161|No available application protocols
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.823 MYT|SSLExtensions.java:256|Ignore, context unavailable extension: application_layer_protocol_negotiation
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.823 MYT|SSLExtensions.java:256|Ignore, context unavailable extension: renegotiation_info
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.825 MYT|ClientHello.java:651|Produced ClientHello handshake message (
"ClientHello": {
  "client version"      : "TLSv1.2",
  "random"              : "FB BC CD 7C 17 65 86 49 3E 1C 15 37 24 94 7D E7 60 44 1B B8 F4 18 21 D0 E1 B1 31 0D E1 80 D6 A7",
  "session id"          : "",
  "cipher suites"       : "[TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384(0xC02C), TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256(0xC02B), TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384(0xC030), TLS_RSA_WITH_AES_256_GCM_SHA384(0x009D), TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384(0xC02E), TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384(0xC032), TLS_DHE_RSA_WITH_AES_256_GCM_SHA384(0x009F), TLS_DHE_DSS_WITH_AES_256_GCM_SHA384(0x00A3), TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256(0xC02F), TLS_RSA_WITH_AES_128_GCM_SHA256(0x009C), TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256(0xC02D), TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256(0xC031), TLS_DHE_RSA_WITH_AES_128_GCM_SHA256(0x009E), TLS_DHE_DSS_WITH_AES_128_GCM_SHA256(0x00A2), TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384(0xC024), TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384(0xC028), TLS_RSA_WITH_AES_256_CBC_SHA256(0x003D), TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384(0xC026), TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384(0xC02A), TLS_DHE_RSA_WITH_AES_256_CBC_SHA256(0x006B), TLS_DHE_DSS_WITH_AES_256_CBC_SHA256(0x006A), TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA(0xC00A), TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA(0xC014), TLS_RSA_WITH_AES_256_CBC_SHA(0x0035), TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA(0xC005), TLS_ECDH_RSA_WITH_AES_256_CBC_SHA(0xC00F), TLS_DHE_RSA_WITH_AES_256_CBC_SHA(0x0039), TLS_DHE_DSS_WITH_AES_256_CBC_SHA(0x0038), TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256(0xC023), TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256(0xC027), TLS_RSA_WITH_AES_128_CBC_SHA256(0x003C), TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256(0xC025), TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256(0xC029), TLS_DHE_RSA_WITH_AES_128_CBC_SHA256(0x0067), TLS_DHE_DSS_WITH_AES_128_CBC_SHA256(0x0040), TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA(0xC009), TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA(0xC013), TLS_RSA_WITH_AES_128_CBC_SHA(0x002F), TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA(0xC004), TLS_ECDH_RSA_WITH_AES_128_CBC_SHA(0xC00E), TLS_DHE_RSA_WITH_AES_128_CBC_SHA(0x0033), TLS_DHE_DSS_WITH_AES_128_CBC_SHA(0x0032), TLS_EMPTY_RENEGOTIATION_INFO_SCSV(0x00FF)]",
  "compression methods" : "00",  "extensions"          : [
    "server_name (0)": {
      type=host_name (0), value=mq.tpc-ohcis.moh.gov.my
    },
    "status_request (5)": {
      "certificate status type": ocsp
      "OCSP status request": {
        "responder_id": <empty>
        "request extensions": {
          <empty>
        }
      }
    },
    "supported_groups (10)": {
      "versions": [secp256r1, secp384r1, secp521r1, sect283k1, sect283r1, sect409k1, sect409r1, sect571k1, sect571r1, secp256k1, ffdhe2048, ffdhe3072, ffdhe4096, ffdhe6144, ffdhe8192]
    },
    "ec_point_formats (11)": {
      "formats": [uncompressed]
    },
    "signature_algorithms (13)": {
      "signature schemes": [ecdsa_secp256r1_sha256, ecdsa_secp384r1_sha384, ecdsa_secp512r1_sha512, rsa_pss_rsae_sha256, rsa_pss_rsae_sha384, rsa_pss_rsae_sha512, rsa_pss_pss_sha256, rsa_pss_pss_sha384, rsa_pss_pss_sha512, rsa_pkcs1_sha256, rsa_pkcs1_sha384, rsa_pkcs1_sha512, dsa_sha256, ecdsa_sha224, rsa_sha224, dsa_sha224, ecdsa_sha1, rsa_pkcs1_sha1, dsa_sha1]
    },
    "signature_algorithms_cert (50)": {
      "signature schemes": [ecdsa_secp256r1_sha256, ecdsa_secp384r1_sha384, ecdsa_secp512r1_sha512, rsa_pss_rsae_sha256, rsa_pss_rsae_sha384, rsa_pss_rsae_sha512, rsa_pss_pss_sha256, rsa_pss_pss_sha384, rsa_pss_pss_sha512, rsa_pkcs1_sha256, rsa_pkcs1_sha384, rsa_pkcs1_sha512, dsa_sha256, ecdsa_sha224, rsa_sha224, dsa_sha224, ecdsa_sha1, rsa_pkcs1_sha1, dsa_sha1]
    },
    "status_request_v2 (17)": {
      "cert status request": {
        "certificate status type": ocsp_multi
        "OCSP status request": {
          "responder_id": <empty>
          "request extensions": {
            <empty>
          }
        }      }
    },
    "extended_master_secret (23)": {
      <empty>
    },
    "supported_versions (43)": {
      "versions": [TLSv1.2, TLSv1.1, TLSv1]
    }
  ]
}
)
javax.net.ssl|DEBUG|43|SimpleAsyncTaskExecutor-1|2019-07-03 17:35:01.829 MYT|Alert.java:238|Received alert message (
"Alert": {
  "level"      : "fatal",
  "description": "insufficient_security"
}
)

Unable to resolve host "<insert URL here>" No address associated with hostname

This error because of you host cann't be translate to IP addresses via DNS.

Solve of this problem :

1- Make sure you connect to the internet (check quality of network).

2- Make sure you take proper permission to access network

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

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

For someone looking to solve same by using maven. Add below dependency in POM:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>7.0.0.jre8</version>
</dependency>

And use below code for connection:

String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";

try {
    System.out.print("Connecting to SQL Server ... ");
    try (Connection connection = DriverManager.getConnection(connectionUrl))        {
        System.out.println("Done.");
    }
} catch (Exception e) {
    System.out.println();
    e.printStackTrace();
}

Look for this link for other CRUD type of queries.

Showing all errors and warnings

I was able to get all errors via the below code:

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

Redirecting a request using servlets and the "setHeader" method not working

As you can see, the response is still HTTP/1.1 200 OK. To indicate a redirect, you need to send back a 302 status code:

response.setStatus(HttpServletResponse.SC_FOUND); // SC_FOUND = 302

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

First you have to ensure that there is a SMTP server listening on port 25.

To look whether you have the service, you can try using TELNET client, such as:

C:\> telnet localhost 25

(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.

$ telnet localhost 25

If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.

If you don't have the service, you can use these:

  • A mock SMTP server that will mimic the behavior of actual SMTP server, as you are using Java, it is natural to suggest Dumbster fake SMTP server. This even can be made to work within JUnit tests (with setup/tear down/validation), or independently run as separate process for integration test.
  • If your host is Windows, you can try installing Mercury email server (also comes with WAMPP package from Apache Friends) on your local before running above code.
  • If your host is Linux or UNIX, try to enable the mail service such as Postfix,
  • Another full blown SMTP server in Java, such as Apache James mail server.

If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.

How do I send an HTML email?

You can use setText(java.lang.String text, boolean html) from MimeMessageHelper:

MimeMessage mimeMsg = javaMailSender.createMimeMessage();
MimeMessageHelper msgHelper = new MimeMessageHelper(mimeMsg, false, "utf-8");
boolean isHTML = true;
msgHelper.setText("<h1>some html</h1>", isHTML);

But you need to:

mimeMsg.saveChanges();

Before:

javaMailSender.send(mimeMsg);

convert ArrayList<MyCustomClass> to JSONArray

As somebody figures out that the OP wants to convert custom List to org.json.JSONArray not the com.google.gson.JsonArray,the CORRECT answer should be like this:

Gson gson = new Gson();

String listString = gson.toJson(
                    targetList,
           new TypeToken<ArrayList<targetListItem>>() {}.getType());

 JSONArray jsonArray =  new JSONArray(listString);

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

I've got this exact error, but in my case I was binding values for the LIMIT clause without specifying the type. I'm just dropping this here in case somebody gets this error for the same reason. Without specifying the type LIMIT :limit OFFSET :offset; resulted in LIMIT '10' OFFSET '1'; instead of LIMIT 10 OFFSET 1;. What helps to correct that is the following:

$stmt->bindParam(':limit', intval($limit, 10), \PDO::PARAM_INT);
$stmt->bindParam(':offset', intval($offset, 10), \PDO::PARAM_INT);

ProgressDialog in AsyncTask

A couple of days ago I found a very nice solution of this problem. Read about it here. In two words Mike created a AsyncTaskManager that mediates ProgressDialog and AsyncTask. It's very easy to use this solution. You just need to include in your project several interfaces and several classes and in your activity write some simple code and nest your new AsyncTask from BaseTask. I also advice you to read comments because there are some useful tips.

When to use throws in a Java method declaration?

This is not an answer, but a comment, but I could not write a comment with a formatted code, so here is the comment.

Lets say there is

public static void main(String[] args) {
  try {
    // do nothing or throw a RuntimeException
    throw new RuntimeException("test");
  } catch (Exception e) {
    System.out.println(e.getMessage());
    throw e;
  }
}

The output is

test
Exception in thread "main" java.lang.RuntimeException: test
    at MyClass.main(MyClass.java:10)

That method does not declare any "throws" Exceptions, but throws them! The trick is that the thrown exceptions are RuntimeExceptions (unchecked) that are not needed to be declared on the method. It is a bit misleading for the reader of the method, since all she sees is a "throw e;" statement but no declaration of the throws exception

Now, if we have

public static void main(String[] args) throws Exception {
  try {
    throw new Exception("test");
  } catch (Exception e) {
    System.out.println(e.getMessage());
    throw e;
  }
}

We MUST declare the "throws" exceptions in the method otherwise we get a compiler error.

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

If you're still facing the issue even after replacing doGet() with doPost() and changing the form method="post". Try clearing the cache of the browser or hit the URL in another browser or incognito/private mode. It may works!

For best practices, please follow this link. https://www.oracle.com/technetwork/articles/javase/servlets-jsp-140445.html

MySQL & Java - Get id of the last inserted value (JDBC)

Alternatively you can do:

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getString(1);
}

But use Sean Bright's answer instead for your scenario.

JAX-WS client : what's the correct path to access the local WSDL?

The best option is to use jax-ws-catalog.xml

When you compile the local WSDL file , override the WSDL location and set it to something like

http://localhost/wsdl/SOAService.wsdl

Don't worry this is only a URI and not a URL , meaning you don't have to have the WSDL available at that address.
You can do this by passing the wsdllocation option to the wsdl to java compiler.

Doing so will change your proxy code from

static {
    URL url = null;
    try {
        URL baseUrl;
        baseUrl = com.ibm.eci.soaservice.SOAService.class.getResource(".");
        url = new URL(baseUrl, "file:/C:/local/path/to/wsdl/SOAService.wsdl");
    } catch (MalformedURLException e) {
        logger.warning("Failed to create URL for the wsdl Location: 'file:/C:/local/path/to/wsdl/SOAService.wsdl', retrying as a local file");
        logger.warning(e.getMessage());
    }
    SOASERVICE_WSDL_LOCATION = url;
}

to

static {
    URL url = null;
    try {
        URL baseUrl;
        baseUrl = com.ibm.eci.soaservice.SOAService.class.getResource(".");
        url = new URL(baseUrl, "http://localhost/wsdl/SOAService.wsdl");
    } catch (MalformedURLException e) {
        logger.warning("Failed to create URL for the wsdl Location: 'http://localhost/wsdl/SOAService.wsdl', retrying as a local file");
        logger.warning(e.getMessage());
    }
    SOASERVICE_WSDL_LOCATION = url;
}

Notice file:// changed to http:// in the URL constructor.

Now comes in jax-ws-catalog.xml. Without jax-ws-catalog.xml jax-ws will indeed try to load the WSDL from the location

http://localhost/wsdl/SOAService.wsdl
and fail, as no such WSDL will be available.

But with jax-ws-catalog.xml you can redirect jax-ws to a locally packaged WSDL whenever it tries to access the WSDL @

http://localhost/wsdl/SOAService.wsdl
.

Here's jax-ws-catalog.xml

<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="system">
        <system systemId="http://localhost/wsdl/SOAService.wsdl"
                uri="wsdl/SOAService.wsdl"/>
    </catalog>

What you are doing is telling jax-ws that when ever it needs to load WSDL from

http://localhost/wsdl/SOAService.wsdl
, it should load it from local path wsdl/SOAService.wsdl.

Now where should you put wsdl/SOAService.wsdl and jax-ws-catalog.xml ? That's the million dollar question isn't it ?
It should be in the META-INF directory of your application jar.

so something like this

ABCD.jar  
|__ META-INF    
    |__ jax-ws-catalog.xml  
    |__ wsdl  
        |__ SOAService.wsdl  

This way you don't even have to override the URL in your client that access the proxy. The WSDL is picked up from within your JAR, and you avoid having to have hard-coded filesystem paths in your code.

More info on jax-ws-catalog.xml http://jax-ws.java.net/nonav/2.1.2m1/docs/catalog-support.html

Hope that helps

Android - SMS Broadcast receiver

I tried your code and found it wasn't working.

I had to change

if (intent.getAction() == SMS_RECEIVED) {

to

if (intent.getAction().equals(SMS_RECEIVED)) {

Now it's working. It's just an issue with java checking equality.

PKIX path building failed: unable to find valid certification path to requested target

I had hit this when I was trying to initiate a SOAP request from Java code. What worked for me was:

  1. Get the Server certificate by hitting the URL in browser: http://docs.bvstools.com/home/ssl-documentation/exporting-certificate-authorities-cas-from-a-website This link has all the steps to get the server certificate

  2. Once you have the server certificate with you follow http://java.globinch.com/enterprise-java/security/pkix-path-building-failed-validation-sun-security-validatorexception/#Valid-Certification-Path-to-Requested-Target .

Copying the text from the link, in case this link dies:

All you need to do to fix this error is to add the server certificate to your trusted Java key store. First You need to download the document from the server.

Once you have the certificate in your hard drive you can import it to the Java trust store. To import the certificate to the trusted Java key store, you can use the java ‘keytool‘ tool. On command prompt navigate to JRE bin folder, in my case the path is : C:\Program Files\Java\jdk1.7.0_75\jre\bin . Then use keytool command as follows to import the certificate to JRE.

keytool -import -alias _alias_name_ -keystore ..\lib\security\cacerts -file _path_to_cer_file

It will ask for a password. By default the password is “changeit”. If the password is different you may not be able to import the certificate.

org.hibernate.MappingException: Unknown entity

you should add all the entity files in the .addAnnotatedClass(Class) method, if the class needs to be auto discovered.

use this link, it might help..

http://docs.jboss.org/hibernate/stable/core/api/org/hibernate/cfg/AnnotationConfiguration.html

Sending emails through SMTP with PHPMailer

Try to send an e-mail through that SMTP server manually/from an interactive mailer (e.g. Mozilla Thunderbird). From the errors, it seems the server won't accept your credentials. Is that SMTP running on the port, or is it SSL+SMTP? You don't seem to be using secure connection in the code you've posted, and I'm not sure if PHPMailer actually supports SSL+SMTP.

(First result of googling your SMTP server's hostname: http://podpora.ebola.cz/idx.php/0/006/article/Strucny-technicky-popis-nastaveni-sluzeb.html seems to say "SMTPs mail sending: secure SSL connection,port: 465" . )

It looks like PHPMailer does support SSL; at least from this. So, you'll need to change this:

define('SMTP_SERVER', 'smtp.ebola.cz');

into this:

define('SMTP_SERVER', 'ssl://smtp.ebola.cz');

Who sets response content-type in Spring MVC (@ResponseBody)

Thanks digz6666, your solution works for me with a slight changes because I'm using json:

responseHeaders.add("Content-Type", "application/json; charset=utf-8");

The answer given by axtavt (whch you've recommended) wont work for me. Even if I've added the correct media type:

if (conv instanceof StringHttpMessageConverter) {                   
                    ((StringHttpMessageConverter) conv).setSupportedMediaTypes(
                        Arrays.asList(
                                new MediaType("text", "html", Charset.forName("UTF-8")),
                                new MediaType("application", "json", Charset.forName("UTF-8")) ));
                }

How do you write to a folder on an SD card in Android?

Add Permission to Android Manifest

Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your.company.package"
    android:versionCode="1"
    android:versionName="0.1">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <!-- ... -->
    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest> 

Check availability of external storage

You should always check for availability first. A snippet from the official android documentation on external storage.

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {
    // We can read and write the media
    mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    // We can only read the media
    mExternalStorageAvailable = true;
    mExternalStorageWriteable = false;
} else {
    // Something else is wrong. It may be one of many other states, but all we need
    //  to know is we can neither read nor write
    mExternalStorageAvailable = mExternalStorageWriteable = false;
}

Use a Filewriter

At last but not least forget about the FileOutputStream and use a FileWriter instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.

// get external storage file reference
FileWriter writer = new FileWriter(getExternalStorageDirectory()); 
// Writes the content to the file
writer.write("This\n is\n an\n example\n"); 
writer.flush();
writer.close();

java.io.StreamCorruptedException: invalid stream header: 7371007E

This exception may also occur if you are using Sockets on one side and SSLSockets on the other. Consistency is important.

How can I disable the default console handler, while using the java logging API?

You must instruct your logger not to send its messages on up to its parent logger:

...
import java.util.logging.*;
...
Logger logger = Logger.getLogger(this.getClass().getName());
logger.setUseParentHandlers(false);
...

However, this should be done before adding any more handlers to logger.

java: How can I do dynamic casting of a variable from one type to another?

So, this is an old post, however I think I can contribute something to it.

You can always do something like this:

package com.dyna.test;  

import java.io.File;  
import java.lang.reflect.Constructor;  

public class DynamicClass{  

  @SuppressWarnings("unchecked")  
  public Object castDynamicClass(String className, String value){  
    Class<?> dynamicClass;  

    try  
    {  
      //We get the actual .class object associated with the specified name  
      dynamicClass = Class.forName(className);  



    /* We get the constructor that received only 
     a String as a parameter, since the value to be used is a String, but we could
easily change this to be "dynamic" as well, getting the Constructor signature from
the same datasource we get the values from */ 


      Constructor<?> cons =  
        (Constructor<?>) dynamicClass.getConstructor(new Class<?>[]{String.class});  

      /*We generate our object, without knowing until runtime 
 what type it will be, and we place it in an Object as 
 any Java object extends the Object class) */  
      Object object = (Object) cons.newInstance(new Object[]{value});  

      return object;  
    }  
    catch (Exception e)  
    {  
      e.printStackTrace();  
    }  
    return null;  
  }  

  public static void main(String[] args)  
  {   
    DynamicClass dynaClass = new DynamicClass();  

    /* 
 We specify the type of class that should be used to represent 
 the value "3.0", in this case a Double. Both these parameters 
 you can get from a file, or a network stream for example. */  
    System.out.println(dynaClass.castDynamicClass("java.lang.Double", "3.0"));  

    /* 
We specify a different value and type, and it will work as 
 expected, printing 3.0 in the above case and the test path in the one below, as the Double.toString() and 
 File.toString() would do. */  
    System.out.println(dynaClass.castDynamicClass("java.io.File", "C:\\testpath"));  
  }  

Of course, this is not really dynamic casting, as in other languages (Python for example), because java is a statically typed lang. However, this can solve some fringe cases where you actually need to load some data in different ways, depending on some identifier. Also, the part where you get a constructor with a String parameter could be probably made more flexible, by having that parameter passed from the same data source. I.e. from a file, you get the constructor signature you want to use, and the list of values to be used, that way you pair up, say, the first parameter is a String, with the first object, casting it as a String, next object is an Integer, etc, but somehwere along the execution of your program, you get now a File object first, then a Double, etc.

In this way, you can account for those cases, and make a somewhat "dynamic" casting on-the-fly.

Hope this helps anyone as this keeps turning up in Google searches.

Java: how to use UrlConnection to post request with authorization?

HTTP authorization does not differ between GET and POST requests, so I would first assume that something else is wrong. Instead of setting the Authorization header directly, I would suggest using the java.net.Authorization class, but I am not sure if it solves your problem. Perhaps your server is somehow configured to require a different authorization scheme than "basic" for post requests?

JUnit test for System.out.println()

for out

@Test
void it_prints_out() {

    PrintStream save_out=System.out;final ByteArrayOutputStream out = new ByteArrayOutputStream();System.setOut(new PrintStream(out));

    System.out.println("Hello World!");
    assertEquals("Hello World!\r\n", out.toString());

    System.setOut(save_out);
}

for err

@Test
void it_prints_err() {

    PrintStream save_err=System.err;final ByteArrayOutputStream err= new ByteArrayOutputStream();System.setErr(new PrintStream(err));

    System.err.println("Hello World!");
    assertEquals("Hello World!\r\n", err.toString());

    System.setErr(save_err);
}

How to call a .NET Webservice from Android using KSOAP2?

I think you can't call

 androidHttpTransport.call(SOAP_ACTION, envelope);

on main Thread.

Network operations should be done on different Thread.

Create another Thread or AsyncTask to call the method.

Get login username in java

inspired by @newacct's answer, a code that can be compiled in any platform:

String osName = System.getProperty( "os.name" ).toLowerCase();
String className = null;
String methodName = "getUsername";

if( osName.contains( "windows" ) ){
    className = "com.sun.security.auth.module.NTSystem";
    methodName = "getName";
}
else if( osName.contains( "linux" ) ){
    className = "com.sun.security.auth.module.UnixSystem";
}
else if( osName.contains( "solaris" ) || osName.contains( "sunos" ) ){
    className = "com.sun.security.auth.module.SolarisSystem";
}

if( className != null ){
    Class<?> c = Class.forName( className );
    Method method = c.getDeclaredMethod( methodName );
    Object o = c.newInstance();
    System.out.println( method.invoke( o ) );
}

Send email using the GMail SMTP server from a PHP page

I had this problem also. I set the correct settings and have enabled less secure apps but it still did not work. Finally, I enabled this https://accounts.google.com/UnlockCaptcha, and it worked for me. I hope this helps someone.

How to Consume WCF Service with Android

If I were doing this I would probably use WCF REST on the server and a REST library on the Java/Android client.

How to use sed to replace only the first occurrence in a file?

A possible solution:

    /#include/!{p;d;}
    i\
    #include "newfile.h"
    :a
    n
    ba

Explanation:

  • read lines until we find the #include, print these lines then start new cycle
  • insert the new include line
  • enter a loop that just reads lines (by default sed will also print these lines), we won't get back to the first part of the script from here

PHP PDO with foreach and fetch

This is because you are reading a cursor, not an array. This means that you are reading sequentially through the results and when you get to the end you would need to reset the cursor to the beginning of the results to read them again.

If you did want to read over the results multiple times, you could use fetchAll to read the results into a true array and then it would work as you are expecting.

subquery in codeigniter active record

I think this code will work. I dont know if this is acceptable query style in CI but it works perfectly in my previous problem. :)

$subquery = 'SELECT id_cer FROM revokace';

$this->db->select('*');
$this->db->where_not_in(id, $subquery);
$this->db->from('certs');
$query = $this->db->get();

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

Go to root folder

Right Click, click on Properties

Choose Tab Security

Click on Edit

Click on Add

Type 'EveryOne'

Click OK

Check Out Full Control

Click OK

How can I reconcile detached HEAD with master/origin?

If you want to push your current detached HEAD (check git log before), try:

git push origin HEAD:master

to send your detached HEAD into master branch at origin. If your push gets rejected, try git pull origin master first to get the changes from origin. If you don't care about the changes from origin and it's rejected, because you did some intentional rebase and you want to replace origin/master with your currently detached branch - then you may force it (-f). In case you lost some access to previous commits, you can always run git reflog to see the history from all branches.


To get back on a master branch, while keeping the changes, try the following commands:

git rebase HEAD master
git checkout master

See: Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

How to set image button backgroundimage for different state?

Hi try the following code it will be useful to you,

((ImageView)findViewById(R.id.ImageViewButton)).setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN)
            ((ImageView) v.findViewById(R.id.ImageViewButton)).setImageResource(R.drawable.image_over);

        if(event.getAction() == MotionEvent.ACTION_UP)
            ((ImageView) v.findViewById(R.id.ImageViewButton)).setImageResource(R.drawable.image_normal);

        return false;
    }
});

To delay JavaScript function call using jQuery

Since you declare sample inside the anonymous function you pass to ready, it is scoped to that function.

You then pass a string to setTimeout which is evaled after 2 seconds. This takes place outside the current scope, so it can't find the function.

Only pass functions to setTimeout, using eval is inefficient and hard to debug.

setTimeout(sample,2000)

Checking network connection

Best way to do this is to make it check against an IP address that python always gives if it can't find the website. In this case this is my code:

import socket

print("website connection checker")
while True:
    website = input("please input website: ")
    print("")
    print(socket.gethostbyname(website))
    if socket.gethostbyname(website) == "92.242.140.2":
        print("Website could be experiencing an issue/Doesn't exist")
    else:
        socket.gethostbyname(website)
        print("Website is operational!")
        print("")

Select all where [first letter starts with B]

You can use:

WHERE LEFT (name_field, 1) = 'B';

Add a column with a default value to an existing table in SQL Server

This has a lot of answers, but I feel the need to add this extended method. This seems a lot longer, but it is extremely useful if you're adding a NOT NULL field to a table with millions of rows in an active database.

ALTER TABLE {schemaName}.{tableName}
    ADD {columnName} {datatype} NULL
    CONSTRAINT {constraintName} DEFAULT {DefaultValue}

UPDATE {schemaName}.{tableName}
    SET {columnName} = {DefaultValue}
    WHERE {columName} IS NULL

ALTER TABLE {schemaName}.{tableName}
    ALTER COLUMN {columnName} {datatype} NOT NULL

What this will do is add the column as a nullable field and with the default value, update all fields to the default value (or you can assign more meaningful values), and finally it will change the column to be NOT NULL.

The reason for this is if you update a large scale table and add a new not null field it has to write to every single row and hereby will lock out the entire table as it adds the column and then writes all the values.

This method will add the nullable column which operates a lot faster by itself, then fills the data before setting the not null status.

I've found that doing the entire thing in one statement will lock out one of our more active tables for 4-8 minutes and quite often I have killed the process. This method each part usually takes only a few seconds and causes minimal locking.

Additionally, if you have a table in the area of billions of rows it may be worth batching the update like so:

WHILE 1=1
BEGIN
    UPDATE TOP (1000000) {schemaName}.{tableName}
        SET {columnName} = {DefaultValue}
        WHERE {columName} IS NULL

    IF @@ROWCOUNT < 1000000
        BREAK;
END

PLS-00201 - identifier must be declared

When creating the TABLE under B2BOWNER, be sure to prefix the PL/SQL function with the Schema name; i.e. B2BOWNER.F_SSC_Page_Map_Insert.

I did not realize this until the DBAs pointed it out. I could have created the table under my root USER/SCHEMA and the PL/SQL function would have worked fine.

How to write a unit test for a Spring Boot Controller endpoint

Spring MVC offers a standaloneSetup that supports testing relatively simple controllers, without the need of context.

Build a MockMvc by registering one or more @Controller's instances and configuring Spring MVC infrastructure programmatically. This allows full control over the instantiation and initialization of controllers, and their dependencies, similar to plain unit tests while also making it possible to test one controller at a time.

An example test for your controller can be something as simple as

public class DemoApplicationTests {

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = standaloneSetup(new HelloWorld()).build();
    }

    @Test
    public void testSayHelloWorld() throws Exception {
        this.mockMvc.perform(get("/")
           .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
           .andExpect(status().isOk())
           .andExpect(content().contentType("application/json"));

    }
}

Import PEM into Java Key Store

If you only want to import a certificate in PEM format into a keystore, keytool will do the job:

keytool -import -alias *alias* -keystore cacerts -file *cert.pem*

Excel SUMIF between dates

One more solution when you want to use data from any sell ( in the key C3)

=SUMIF(Sheet6!M:M;CONCATENATE("<";TEXT(C3;"dd.mm.yyyy"));Sheet6!L:L)

How to add a "open git-bash here..." context menu to the windows explorer?

Here are the Registry exports (*.reg files) for Git GUI and Git Bash directly from the Windows installer —Git GUI:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\background\shell\git_gui]
@="Git &GUI Here"
"Icon"="C:\\Program Files\\Git\\cmd\\git-gui.exe"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\background\shell\git_gui\command]
@="\"C:\\Program Files\\Git\\cmd\\git-gui.exe\" \"--working-dir\" \"%v.\""

Git bash:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\background\shell\git_shell]
@="Git Ba&sh Here"
"Icon"="C:\\Program Files\\Git\\git-bash.exe"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\background\shell\git_shell\command]
@="\"C:\\Program Files\\Git\\git-bash.exe\" \"--cd=%v.\""

For detail about *.reg files, see “How to add, modify, or delete registry subkeys and values by using a .reg file” from Microsoft.

Java random number with given length

Would that work for you?

public class Main {

public static void main(String[] args) {
    Random r = new Random(System.currentTimeMillis());
    System.out.println(r.nextInt(100000) * 0.000001);
}

}

result e.g. 0.019007

PHP function ssh2_connect is not working

You need to install ssh2 lib

sudo apt-get install libssh2-php && sudo /etc/init.d/apache2 restart

that should be enough to get you on the road

Compiling C++ on remote Linux machine - "clock skew detected" warning

According to user m9dhatter on LinuxQuestions.org:

"make" uses the time stamp of the file to determine if the file it is trying to compile is old or new. if your clock is bonked, it may have problems compiling.

if you try to modify files at another machine with a clock time ahead by a few minutes and transfer them to your machine and then try to compile it may cough up a warning that says the file was modified from the future. clock may be skewed or something to that effect ( cant really remember ). you could just ls to the offending file and do this:

#touch <filename of offending file>

How to edit data in result grid in SQL Server Management Studio

Right click on any table in your dB of interest or any database in the server using master if there are joins or using multiple dBs. Select "edit top 200 rows". Select the "SQL" button in the task bar. Copy and paste your code over the existing code and run again. Now you can edit your query's result set. Sherry ;-)

How can I disable a specific LI element inside a UL?

Using CSS3: http://www.w3schools.com/cssref/sel_nth-child.asp

If that's not an option for any reason, you could try giving the list items classes:

<ul>
<li class="one"></li>
<li class="two"></li>
<li class="three"></li>
...
</ul>

Then in your css:

li.one{display:none}/*hide first li*/
li.three{display:none}/*hide third li*/

How can I redirect a php page to another php page?

<?php
   header("Location: your url");
   exit;
?>

In Oracle, is it possible to INSERT or UPDATE a record through a view?

YES, you can Update and Insert into view and that edit will be reflected on the original table....
BUT
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...

Changing file extension in Python

Starting from Python 3.4 there's pathlib built-in library. So the code could be something like:

from pathlib import Path

filename = "mysequence.fasta"
new_filename = Path(filename).stem + ".aln"

https://docs.python.org/3.4/library/pathlib.html#pathlib.PurePath.stem

I love pathlib :)

Sql select rows containing part of string

you can use CHARINDEX in t-sql.

select * from table where CHARINDEX(url, 'http://url.com/url?url...') > 0

Styling Form with Label above Inputs

I'd make both the input and label elements display: block , and then split the name label & input, and the email label & input into div's and float them next to each other.

_x000D_
_x000D_
input, label {_x000D_
    display:block;_x000D_
}
_x000D_
<form name="message" method="post">_x000D_
    <section>_x000D_
_x000D_
  <div style="float:left;margin-right:20px;">_x000D_
    <label for="name">Name</label>_x000D_
    <input id="name" type="text" value="" name="name">_x000D_
  </div>_x000D_
_x000D_
  <div style="float:left;">_x000D_
    <label for="email">Email</label>_x000D_
    <input id="email" type="text" value="" name="email">_x000D_
  </div>_x000D_
_x000D_
  <br style="clear:both;" />_x000D_
_x000D_
    </section>_x000D_
_x000D_
    <section>_x000D_
_x000D_
    <label for="subject">Subject</label>_x000D_
    <input id="subject" type="text" value="" name="subject">_x000D_
    <label for="message">Message</label>_x000D_
    <input id="message" type="text" value="" name="message">_x000D_
_x000D_
    </section>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Java method to swap primitives

I think this is the closest you can get to a simple swap, but it does not have a straightforward usage pattern:

int swap(int a, int b) {  // usage: y = swap(x, x=y);
   return a;
}

y = swap(x, x=y);

It relies on the fact that x will pass into swap before y is assigned to x, then x is returned and assigned to y.

You can make it generic and swap any number of objects of the same type:

<T> T swap(T... args) {   // usage: z = swap(a, a=b, b=c, ... y=z);
    return args[0];
}

c = swap(a, a=b, b=c)

Java - How to create a custom dialog box?

Try this simple class for customizing a dialog to your liking:

import java.util.ArrayList;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;

public class CustomDialog
{
    private List<JComponent> components;

    private String title;
    private int messageType;
    private JRootPane rootPane;
    private String[] options;
    private int optionIndex;

    public CustomDialog()
    {
        components = new ArrayList<>();

        setTitle("Custom dialog");
        setMessageType(JOptionPane.PLAIN_MESSAGE);
        setRootPane(null);
        setOptions(new String[] { "OK", "Cancel" });
        setOptionSelection(0);
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public void setMessageType(int messageType)
    {
        this.messageType = messageType;
    }

    public void addComponent(JComponent component)
    {
        components.add(component);
    }

    public void addMessageText(String messageText)
    {
        JLabel label = new JLabel("<html>" + messageText + "</html>");

        components.add(label);
    }

    public void setRootPane(JRootPane rootPane)
    {
        this.rootPane = rootPane;
    }

    public void setOptions(String[] options)
    {
        this.options = options;
    }

    public void setOptionSelection(int optionIndex)
    {
        this.optionIndex = optionIndex;
    }

    public int show()
    {
        int optionType = JOptionPane.OK_CANCEL_OPTION;
        Object optionSelection = null;

        if(options.length != 0)
        {
            optionSelection = options[optionIndex];
        }

        int selection = JOptionPane.showOptionDialog(rootPane,
                components.toArray(), title, optionType, messageType, null,
                options, optionSelection);

        return selection;
    }

    public static String getLineBreak()
    {
        return "<br>";
    }
}

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Swipe ListView item From right to left show delete button

I have gone through tons of third party libraries to try to achieve this. But none of them exhibits smoothness and usability experience which i wanted. Then i decided to write it myself. And the result was , well, i loved it. I will share the code here. Maybe i will write it as a library which can be embedded in any recycler view in future. But for now here is the code.

Note: i have uses recycler view and ViewHolder. Some values are hardcoded so change them according to your requirement.

  • row_layout.xml

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:orientation="horizontal">
        <Button
            android:id="@+id/slide_button_2"
            android:text="Button2"
            android:layout_width="80dp"
            android:layout_height="80dp" />
        <Button
            android:id="@+id/slide_button_1"
            android:text="Button1"
            android:layout_width="80dp"
            android:layout_height="80dp" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/chat_row_cell"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:orientation="horizontal"
        android:background="@color/white">
        <ImageView
            android:id="@+id/chat_image"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:layout_marginRight="10dp"
            android:layout_gravity="center"/>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
                <TextView
                    android:id="@+id/chat_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="@color/md_grey_800"
                    android:textSize="18sp"/>
                <TextView
                    android:id="@+id/chat_subtitle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textColor="@color/md_grey_600"/>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
    

  • ChatAdaptor.java

    public class ChatAdaptor extends RecyclerView.Adapter {

    List<MXGroupChatSession> sessions;
    Context context;
    ChatAdaptorInterface listener;
    
    public interface ChatAdaptorInterface{
        void cellClicked(MXGroupChatSession session);
        void utilityButton1Clicked(MXGroupChatSession session);
        void utilityButton2Clicked(MXGroupChatSession session);
    }
    
    public ChatAdaptor(List<MXGroupChatSession> sessions, ChatAdaptorInterface listener, Context context){
        this.sessions=sessions;
        this.context=context;
        this.listener=listener;
    }
    
    @Override
    public ChatViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=(View)LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_row,null);
        ChatViewHolder chatViewHolder=new ChatViewHolder(view);
        return chatViewHolder;
    }
    
    @Override
    public void onBindViewHolder(ChatViewHolder holder, final int position) {
        MXGroupChatSession session=this.sessions.get(position);
        holder.selectedSession=session;
        holder.titleView.setText(session.getTopic());
        holder.subtitleView.setText(session.getLastFeedContent());
        Picasso.with(context).load(new File(session.getCoverImagePath())).transform(new CircleTransformPicasso()).into(holder.imageView);
    }
    
    @Override
    public int getItemCount() {
        return sessions.size();
    }
    
    public class ChatViewHolder extends RecyclerView.ViewHolder{
        ImageView imageView;
        TextView titleView;
        TextView subtitleView;
        ViewGroup cell;
        ViewGroup cellContainer;
        Button button1;
        Button button2;
    
        MXGroupChatSession selectedSession;
        private GestureDetectorCompat gestureDetector;
    
        float totalx;
        float buttonTotalWidth;
    
        Boolean open=false;
        Boolean isScrolling=false;
    
    
        public ChatViewHolder(View itemView) {
            super(itemView);
            cell=(ViewGroup) itemView.findViewById(R.id.chat_row_cell);
            cellContainer=(ViewGroup) itemView.findViewById(R.id.chat_row_container);
            button1=(Button) itemView.findViewById(R.id.slide_button_1);
            button2=(Button) itemView.findViewById(R.id.slide_button_2);
    
            button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.utilityButton1Clicked(selectedSession);
                }
            });
    
            button2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.utilityButton2Clicked(selectedSession);
                }
            });
    
            ViewTreeObserver vto = cellContainer.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    buttonTotalWidth = button1.getWidth()+button2.getWidth();
                }
            });
    
            this.titleView=(TextView)itemView.findViewById(R.id.chat_title);
            subtitleView=(TextView)itemView.findViewById(R.id.chat_subtitle);
            imageView=(ImageView)itemView.findViewById(R.id.chat_image);
            gestureDetector=new GestureDetectorCompat(context,new ChatRowGesture());
    
            cell.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if(gestureDetector.onTouchEvent(event)){
                        return true;
                    }
    
                    if(event.getAction() == MotionEvent.ACTION_UP) {
                        if(isScrolling ) {
                            isScrolling  = false;
                            handleScrollFinished();
                        };
                    }
                    else if(event.getAction() == MotionEvent.ACTION_CANCEL){
                        if(isScrolling ) {
                            isScrolling  = false;
                            handleScrollFinished();
                        };
                    }
                    return false;
                }
            });
        }
    
    
        public class ChatRowGesture extends GestureDetector.SimpleOnGestureListener {
    
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (!open){
                    listener.cellClicked(selectedSession);
                }
                return true;
            }
    
            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }
    
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                    isScrolling=true;
                    totalx=totalx+distanceX;
                    freescroll(totalx);
    
                return true;
            }
        }
    
        void handleScrollFinished(){
            if (open){
                if (totalx>2*buttonTotalWidth/3){
                    slideLeft();
                    totalx=buttonTotalWidth;
                }else{
                    slideRight();
                    totalx=0;
                }
            }else{
                if (totalx>buttonTotalWidth/3){
                    slideLeft();
                    totalx=buttonTotalWidth;
                }else{
                    slideRight();
                    totalx=0;
                }
            }
    
        }
    
        void slideRight(){
            TransitionManager.beginDelayedTransition(cellContainer);
            ViewGroup.MarginLayoutParams params;
            params=(ViewGroup.MarginLayoutParams) cell.getLayoutParams();
            params.setMargins(0,0,0,0);
            cell.setLayoutParams(params);
            open=false;
        }
    
        void slideLeft(){
            TransitionManager.beginDelayedTransition(cellContainer);
            ViewGroup.MarginLayoutParams params;
            params=(ViewGroup.MarginLayoutParams) cell.getLayoutParams();
            params.setMargins(((int)buttonTotalWidth*-1),0,(int)buttonTotalWidth,0);
            cell.setLayoutParams(params);
            open=true;
        }
        void freescroll(float x){
            if (x<buttonTotalWidth && x>0){
                int xint=(int)x;
                ViewGroup.MarginLayoutParams params;
                params=(ViewGroup.MarginLayoutParams) cell.getLayoutParams();
                params.setMargins(params.leftMargin,0,xint,0);
                cell.setLayoutParams(params);
            }
        }
    }
    

Hope this helps someone!!

Presenting a UIAlertController properly on an iPad using iOS 8

2018 Update

I just had an app rejected for this reason and a very quick resolution was simply to change from using an action sheet to an alert.

Worked a charm and passed the App Store testers just fine.

May not be a suitable answer for everyone but I hope this helps some of you out of a pickle quickly.

Android - default value in editText

 public class Main extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText et = (EditText) findViewById(R.id.et);
        EditText et_city = (EditText) findViewById(R.id.et_city);
        // Set the default text of second EditText widget
        et_city.setText("USA");
 }
}

MongoDB relationships: embed or reference?

If I want to edit a specified comment, how do I get its content and its question?

If you had kept track of the number of comments and the index of the comment you wanted to alter, you could use the dot operator (SO example).

You could do f.ex.

db.questions.update(
    {
        "title": "aaa"       
    }, 
    { 
        "comments.0.contents": "new text"
    }
)

(as another way to edit the comments inside the question)

Multi column forms with fieldsets

I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.

<div class="form-group">
    <div class="col-sm-12">
        <label for="user_login">Username</label>
        <input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />
    </div>
</div>

Check out this demo.

Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.

<form action="#" method="post" class="form-horizontal">

Check out this demo.

When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.

Creating a list of objects in Python

To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.

instancelist = [ MyClass() for i in range(29)]

and then access the instances through the index of the list.

instancelist[5].attr1 = 'whamma'

Skipping Iterations in Python

for i in iterator:
    try:
        # Do something.
        pass
    except:
        # Continue to next iteration.
        continue

Remove accents/diacritics in a string in JavaScript

Assuming you know what you're doing, I suspect IE6 is not interpreting the file's encoding correctly, and hence not recognising the non-ASCII characters in the file:

  • Make sure the file is saved as UTF-8 (say)
  • Use Fiddler or some other tool to check that the web server is sending the correct Content-Encoding HTTP header.

(It "smells" wrong though, I'd look into doing the sorting, say on the server using something that's locale-aware... but anyway...)

Run all SQL files in a directory

What I know you can use the osql or sqlcmd commands to execute multiple sql files. The drawback is that you will have to create a script for both the commands.

Using SQLCMD to Execute Multiple SQL Server Scripts

OSQL (This is for sql server 2000)

http://msdn.microsoft.com/en-us/library/aa213087(v=SQL.80).aspx

Angular + Material - How to refresh a data source (mat-table)

import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

export class LanguageComponent implemnts OnInit {
  displayedColumns = ['name', 'native', 'code', 'leavel'];
  user: any;
  private update = new Subject<void>();
  update$ = this.update.asObservable();

  constructor(private authService: AuthService, private dialog: MatDialog) {}

   ngOnInit() {
     this.update$.subscribe(() => { this.refresh()});
   }

   setUpdate() {
     this.update.next();
   }

   add() {
     this.dialog.open(LanguageAddComponent, {
     data: { user: this.user },
   }).afterClosed().subscribe(result => {
     this.setUpdate();
   });
 }

 refresh() {
   this.authService.getAuthenticatedUser().subscribe((res) => {
     this.user = res;
     this.teachDS = new LanguageDataSource(this.user.profile.languages.teach);   
    });
  }
}

How To Get The Current Year Using Vba

Try =Year(Now()) and format the cell as General.

Better way to check if a Path is a File or a Directory?

Just adding a fringe case - "Folder Selection." in path

In my app I get recently opened paths passed to me, some of which have "Folder Selection." at the end.

Some FileOpenDialogs and WinMerge add "Folder Selection." to paths (it's true).

Dialog showing "Folder Selection." getting added to path

But under Windows OS "Folder Selection." is not an advised file or folder name (as in don't do it, ever - shakes fist). As said here: http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx

Do not end a file or directory name with a space or a period. Although the underlying file system may support such names, the Windows shell and user interface does not. However, it is acceptable to specify a period as the first character of a name. For example, ".temp".

So whilst "Folder Selection." shouldn't be used, it can be. (awesome).

Enough explanation - my code (I like enums a lot):

public static class Utility
{
    public enum ePathType
    {
        ePathType_Unknown = 0,
        ePathType_ExistingFile = 1,
        ePathType_ExistingFolder = 2,
        ePathType_ExistingFolder_FolderSelectionAdded = 3,
    }

    public static ePathType GetPathType(string path)
    {
        if (File.Exists(path) == true) { return ePathType.ePathType_ExistingFile; }
        if (Directory.Exists(path) == true) { return ePathType.ePathType_ExistingFolder; }

        if (path.EndsWith("Folder Selection.") == true)
        {
            // Test the path again without "Folder Selection."
            path = path.Replace("\\Folder Selection.", "");
            if (Directory.Exists(path) == true)
            {
                // Could return ePathType_ExistingFolder, but prefer to let the caller known their path has text to remove...
                return ePathType.ePathType_ExistingFolder_FolderSelectionAdded;
            }
        }

        return ePathType.ePathType_Unknown;
    }
}

I'm getting Key error in python

This means your array is missing the key you're looking for. I handle this with a function which either returns the value if it exists or it returns a default value instead.

def keyCheck(key, arr, default):
    if key in arr.keys():
        return arr[key]
    else:
        return default


myarray = {'key1':1, 'key2':2}

print keyCheck('key1', myarray, '#default')
print keyCheck('key2', myarray, '#default')
print keyCheck('key3', myarray, '#default')

Output:

1
2
#default

Creating a chart in Excel that ignores #N/A or blank cells

I was having the same issue by using an IF statement to return an unwanted value to "", and the chart would do as you described.

However, when I used #N/A instead of "" (important, note that it's without the quotation marks as in #N/A and not "#N/A"), the chart ignored the invalid data. I even tried putting in an invalid FALSE statement and it worked the same, the only difference was #NAME? returned as the error in the cell instead of #N/A. I will use a made up IF statement to show you what I mean:

=IF(A1>A2,A3,"")  
---> Returned "" into cell when statement is FALSE and plotted on chart 
     (this is unwanted as you described)

=IF(A1>A2,A3,"#N/A")  
---> Returned #N/A as text when statement is FALSE and plotted on chart 
     (this is also unwanted as you described)

=IF(A1>A2,A3,#N/A)  
---> Returned #N/A as Error when statement is FALSE and does not plot on chart (Ideal)

=IF(A1>A2,A3,a)  
---> Returned #NAME? as Error when statement is FALSE and does not plot on chart 
    (Ideal, and this is because any letter without quotations is not a valid statement)

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

The main difference is that if you use a synchronized block you may lock on an object other than this which allows to be much more flexible.

Assume you have a message queue and multiple message producers and consumers. We don't want producers to interfere with each other, but the consumers should be able to retrieve messages without having to wait for the producers. So we just create an object

Object writeLock = new Object();

And from now on every time a producers wants to add a new message we just lock on that:

synchronized(writeLock){
  // do something
}

So consumers may still read, and producers will be locked.

how to zip a folder itself using java

Here's a pretty terse Java 7+ solution which relies purely on vanilla JDK classes, no third party libraries required:

public static void pack(final Path folder, final Path zipFilePath) throws IOException {
    try (
            FileOutputStream fos = new FileOutputStream(zipFilePath.toFile());
            ZipOutputStream zos = new ZipOutputStream(fos)
    ) {
        Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                zos.putNextEntry(new ZipEntry(folder.relativize(file).toString()));
                Files.copy(file, zos);
                zos.closeEntry();
                return FileVisitResult.CONTINUE;
            }

            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                zos.putNextEntry(new ZipEntry(folder.relativize(dir).toString() + "/"));
                zos.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

It copies all files in folder, including empty directories, and creates a zip archive at zipFilePath.

Submit HTML form on self page

You can do it using the same page on the action attribute: action='<yourpage>'

Preprocessing in scikit learn - single sample - Depreciation warning

Just listen to what the warning is telling you:

Reshape your data either X.reshape(-1, 1) if your data has a single feature/column and X.reshape(1, -1) if it contains a single sample.

For your example type(if you have more than one feature/column):

temp = temp.reshape(1,-1) 

For one feature/column:

temp = temp.reshape(-1,1)

Android intent for playing video?

From now onwards after API 24, Uri.parse(filePath) won't work. You need to use this

final File videoFile = new File("path to your video file");
Uri fileUri = FileProvider.getUriForFile(mContext, "{yourpackagename}.fileprovider", videoFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(fileUri, "video/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//DO NOT FORGET THIS EVER
startActivity(intent);

But before using this you need to understand how file provider works. Go to official document link to understand file provider better.

Flutter: Run method on Widget build complete

In flutter version 1.14.6, Dart version 28.

Below is what worked for me, You simply just need to bundle everything you want to happen after the build method into a separate method or function.

@override
void initState() {
super.initState();
print('hello girl');

WidgetsBinding.instance
    .addPostFrameCallback((_) => afterLayoutWidgetBuild());

}

Multiple maven repositories in one gradle file

In short you have to do like this

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "https://maven.fabric.io/public" }
}

Detail:

You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:

apply plugin: 'java'

sourceCompatibility = 1.7
version = '1.0'

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

dependencies {
  compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
  compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
  compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
  compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
  compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
  testCompile group:'junit', name:'junit', version:'4.11'
}

Blog

Filling a List with all enum values in Java

try

enum E {
    E1, E2, E3
}

public static void main(String[] args) throws Exception {
    List<E> list = Arrays.asList(E.values());
    System.out.println(list);
}

C#: Printing all properties of an object

This is exactly what reflection is for. I don't think there's a simpler solution, but reflection isn't that code intensive anyway.

pandas resample documentation

There's more to it than this, but you're probably looking for this list:

B   business day frequency
C   custom business day frequency (experimental)
D   calendar day frequency
W   weekly frequency
M   month end frequency
BM  business month end frequency
MS  month start frequency
BMS business month start frequency
Q   quarter end frequency
BQ  business quarter endfrequency
QS  quarter start frequency
BQS business quarter start frequency
A   year end frequency
BA  business year end frequency
AS  year start frequency
BAS business year start frequency
H   hourly frequency
T   minutely frequency
S   secondly frequency
L   milliseconds
U   microseconds

Source: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases

What is the difference between CSS and SCSS?

Variable definitions right:

$      => SCSS, SASS
--     => CSS
@      => LESS

All answers is good but question a little different than answers

"about Sass. How is SCSS different from CSS" : scss is well formed CSS3 syntax. uses sass preprocessor to create that.

and if I use SCSS instead of CSS will it work the same? yes. if your ide supports sass preprocessor. than it will work same.

Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension .scss.

The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Files in the indented syntax use the extension .sass.


  • Furher Information About:

What Is A CSS Preprocessor?

CSS in itself is devoid of complex logic and functionality which is required to write reusable and organized code. As a result, a developer is bound by limitations and would face extreme difficulty in code maintenance and scalability, especially when working on large projects involving extensive code and multiple CSS stylesheets. This is where CSS Preprocessors come to the rescue.

A CSS Preprocessor is a tool used to extend the basic functionality of default vanilla CSS through its own scripting language. It helps us to use complex logical syntax like – variables, functions, mixins, code nesting, and inheritance to name a few, supercharging your vanilla CSS. By using CSS Preprocessors, you can seamlessly automate menial tasks, build reusable code snippets, avoid code repetition and bloating and write nested code blocks that are well organized and easy to read. However, browsers can only understand native vanilla CSS code and will be unable to interpret the CSS Preprocessor syntax. Therefore, the complex and advanced Preprocessor syntax needs to be first compiled into native CSS syntax which can then be interpreted by the browsers to avoid cross browser compatibility issues. While different Preprocessors have their own unique syntaxes, eventually all of them are compiled to the same native CSS code.

Moving forward in the article, we will take a look at the 3 most popular CSS Preprocessors currently being used by developers around the world i.e Sass, LESS, and Stylus. Before you decide the winner between Sass vs LESS vs Stylus, let us get to know them in detail first.

Sass – Syntactically Awesome Style Sheets

Sass is the acronym for “Syntactically Awesome Style Sheets”. Sass is not only the most popular CSS Preprocessor in the world but also one of the oldest, launched in 2006 by Hampton Catlin and later developed by Natalie Weizenbaum. Although Sass is written in Ruby language, a Precompiler LibSass allows Sass to be parsed in other languages and decouple it from Ruby. Sass has a massive active community and extensive learning resources available on the net for beginners. Thanks to its maturity, stability and powerful logical prowess, Sass has established itself to the forefront of CSS Preprocessor ahead of its rival peers.

Sass can be written in 2 syntaxes either using Sass or SCSS. What is the difference between the two? Let’s find out.

Syntax Declaration: Sass vs SCSS

  • SCSS stands for Sassy CSS. Unlike Sass, SCSS is not based on indentation.
  • .sass extension is used as original syntax for Sass, while SCSS offers a newer syntax with .scss extension.
  • Unlike Sass, SCSS has curly braces and semicolons, just like CSS.
  • Contrary to SCSS, Sass is difficult to read as it is quite deviant from CSS. Which is why SCSS it the more recommended Sass syntax as it is easier to read and closely resembles Native CSS while at the same time enjoying with power of Sass.

Consider the example below with Sass vs SCSS syntax along with Compiled CSS code.

Sass SYNTAX
    $font-color: #fff
    $bg-color: #00f

    #box
      color: $font-color
      background: $bg-color

SCSS SYNTAX
    $font-color: #fff;
    $bg-color: #00f;

    #box{
      color: $font-color;
      background: $bg-color;
    }

In both cases, be it Sass or SCSS, the compiled CSS code will be the same –

#box {
      color: #fff;
      background: #00f;

Usage of Sass

Arguably the most Popular front end framework Bootstrap is written in Sass. Up until version 3, Bootstrap was written in LESS but bootstrap 4 adopted Sass and boosted its popularity. A few of the big companies using Sass are – Zapier, Uber, Airbnb and Kickstarter.

LESS – Leaner Style Sheets

LESS is an acronym for “Leaner Stylesheets”. It was released in 2009 by Alexis Sellier, 3 years after the initial launch of Sass in 2006. While Sass is written in Ruby, LESS is written JavaScript. In fact, LESS is a JavaScript library that extends the functionality of native vanilla CSS with mixins, variables, nesting and rule set loop. Sass vs LESS has been a heated debate. It is no surprise that LESS is the strongest competitor to Sass and has the second-largest user base. However, When bootstrap dumped LESS in favor of Sass with the launch of Bootstrap 4, LESS has waned in popularity. One of the few disadvantages of LESS over Sass is that it does not support functions. Unlike Sass, LESS uses @ to declare variables which might cause confusion with @media and @keyframes. However, One key advantage of LESS over Sass and Stylus or any other preprocessors, is the ease of adding it in your project. You can do that either by using NPM or by incorporating Less.js file. Syntax Declaration: LESS Uses .less extension. Syntax of LESS is quite similar to SCSS with the exception that for declaring variables, instead of $ sign, LESS uses @.

@font-color: #fff;
    @bg-color: #00f

    #box{
      color: @font-color;
      background: @bg-color;
    }

COMPILED CSS
    #box {
        color: #fff;
        background: #00f;
      }

Usage Of LESS The popular Bootstrap framework until the launch of version 4 was written in LESS. However, another popular framework called SEMANTIC UI is still written in LESS. Among the big companies using Sass are – Indiegogo, Patreon, and WeChat

Stylus

The stylus was launched in 2010 by former Node JS developer TJ Holowaychuk, nearly 4 years after the release of Sass and 1 year after the release of LESS. The stylus is written Node JS and fits perfectly with JS stack. The stylus was heavily influenced by the logical prowess of the Sass and simplicity of LESS. Even though Stylus is still popular with Node JS developers, it hasn’t managed to carve out a sizeable share for itself. One advantage of Stylus over Sass or LESS, is that it is armed with extremely powerful built-in functions and is capable of handling heavy computing.

Syntax Declaration: Stylus Uses .styl extension. Stylus offers a great deal of flexibility in writing syntax, supports native CSS as well as allows omission of brackets colons and semicolons. Also, note that Stylus does not use @ or $ symbols for defining variables. Instead, Stylus uses the assignment operators to indicate a variable declaration.

STYLUS SYNTAX WRITTEN LIKE NATIVE CSS

font-color = #fff;
bg-color = #00f;

#box {
    color: font-color;
    background: bg-color;
}

OR

STYLUS SYNTAX WITHOUT CURLY BRACES

font-color = #fff;
bg-color = #00f;

#box 
    color: font-color;
    background: bg-color;

OR

STYLUS SYNTAX WITHOUT COLONS AND SEMICOLONS

font-color = #fff
bg-color = #00f

#box 
    color font-color
    background bg-color

Find an object in SQL Server (cross-database)

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


/**********************************************************************
Naziv procedure     : sp_rfv_FIND
Ime i prezime autora: Srdjan Nadrljanski
Datum kreiranja     : 13.06.2013. 
Namena              : Traži sql objekat na celom serveru
Tabele              : 
Ulazni parametri    : 
Izlazni parametri   : 
Datum zadnje izmene :  
Opis izmene         : 
exec sp_rfv_FIND 'TUN',''
**********************************************************************/
CREATE PROCEDURE [dbo].[sp_rfv_FIND] (  @SEARCHSTRING VARCHAR(255),
                                        @notcontain Varchar(255)
                                        )
AS


declare @text varchar(1500),@textinit varchar (1500)
set @textinit=
'USE @sifra

insert into ##temp2
select ''@sifra''as dbName,a.[Object Name],a.[Object Type]
from(
 SELECT DISTINCT sysobjects.name AS [Object Name]   ,
case
when sysobjects.xtype = ''C'' then ''CHECK constraint''
when sysobjects.xtype = ''D'' then ''Default or DEFAULT constraint''
when sysobjects.xtype = ''F'' then ''Foreign Key''
when sysobjects.xtype = ''FN'' then ''Scalar function''
when sysobjects.xtype = ''P'' then ''Stored Procedure''
when sysobjects.xtype = ''PK'' then ''PRIMARY KEY constraint''
when sysobjects.xtype = ''S'' then ''System table''
when sysobjects.xtype = ''TF'' then ''Function''
when sysobjects.xtype = ''TR'' then ''Trigger''
when sysobjects.xtype = ''U'' then ''User table''
when sysobjects.xtype = ''UQ'' then ''UNIQUE constraint''
when sysobjects.xtype = ''V'' then ''View''
when sysobjects.xtype = ''X'' then ''Extended stored procedure''
end as [Object Type]
FROM sysobjects
WHERE
sysobjects.type in (''C'',''D'',''F'',''FN'',''P'',''K'',''S'',''TF'',''TR'',''U'',''V'',''X'')
AND sysobjects.category = 0
AND CHARINDEX(''@SEARCHSTRING'',sysobjects.name)>0
AND ((CHARINDEX(''@notcontain'',sysobjects.name)=0 or 
CHARINDEX(''@notcontain'',sysobjects.name)<>0)) 
)a'

    set @textinit=replace(@textinit,'@SEARCHSTRING',@SEARCHSTRING)
    set @textinit=replace(@textinit,'@notcontain',@notcontain)


SELECT name AS dbName,cast(null as varchar(255)) as ObjectName,cast(null as varchar(255)) as ObjectType  
into ##temp1 
from master.dbo.sysdatabases order by name

SELECT * INTO ##temp2 FROM ##temp1 WHERE 1 = 0


declare @sifra VARCHAR(255),@suma int,@brojac int

set @suma=(select count(dbName) from ##temp1) 

DECLARE c_k CURSOR LOCAL FAST_FORWARD FOR
SELECT dbName FROM ##temp1 ORDER BY dbName DESC

OPEN c_k
FETCH NEXT FROM c_K INTO @sifra
SET @brojac = 1
WHILE (@@fetch_status = 0 ) AND (@brojac <= @suma)
BEGIN

    set @text=replace(@textinit,'@sifra',@sifra)

    exec (@text)

    SET @brojac = @brojac +1

    DELETE FROM ##temp1 WHERE dbName = @sifra

       FETCH NEXT FROM c_k INTO @sifra 
END
close c_k
DEALLOCATE c_k

select * from ##temp2
order by dbName,ObjectType
drop table ##temp2
drop table ##temp1

How to pass values arguments to modal.show() function in Bootstrap

I want to share how I did this. I spent the last few days rattling my head with how to pass a couple of parameters to the bootstrap modal dialog. After much head bashing, I came up with a rather simple way of doing this.

Here is my modal code:

<div class="modal fade" id="editGroupNameModal" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div id="editGroupName" class="modal-header">Enter new name for group </div>
        <div class="modal-body">
          <%= form_tag( { action: 'update_group', port: portnum } ) do %>
          <%= text_field_tag( :gid, "", { type: "hidden" })  %>
          <div class="input-group input-group-md">
          <span class="input-group-addon" style="font-size: 16px; padding: 3;" >Name</span>
          <%= text_field_tag( :gname, "", { placeholder: "New name goes here", class: "form-control", aria: {describedby: "basic-addon1"}})  %>
        </div>
        <div class="modal-footer">
          <%= submit_tag("Submit") %>
        </div>
        <% end %>
      </div>
    </div>
  </div>
</div>

And here is the simple javascript to change the gid, and gname input values:

function editGroupName(id, name) {
    $('input#gid').val(id);
    $('input#gname.form-control').val(name);
  }

I just used the onclick event in a link:

//                                                                              &#39; is single quote
//                                                                                   ('1', 'admin')
<a data-toggle="modal" data-target="#editGroupNameModal" onclick="editGroupName(&#39;1&#39;, &#39;admin&#39;); return false;" href="#">edit</a>

The onclick fires first, changing the value property of the input boxes, so when the dialog pops up, values are in place for the form to submit.

I hope this helps someone someday. Cheers.

Regex for checking if a string is strictly alphanumeric

try this [0-9a-zA-Z]+ for only alpha and num with one char at-least..

may need modification so test on it

http://www.regexplanet.com/advanced/java/index.html

Pattern pattern = Pattern.compile("^[0-9a-zA-Z]+$");
Matcher matcher = pattern.matcher(phoneNumber);
if (matcher.matches()) {

}

Check if character is number?

Simple function

function isCharNumber(c) {
  return c >= '0' && c <= '9';
}

Set default value of an integer column SQLite

Use the SQLite keyword default

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" 
    + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + KEY_NAME + " TEXT NOT NULL, "
    + KEY_WORKED + " INTEGER, "
    + KEY_NOTE + " INTEGER DEFAULT 0);");

This link is useful: http://www.sqlite.org/lang_createtable.html

How to create a directory using Ansible

You can directly run the command and create directly using ansible

ansible -v targethostname -m shell -a "mkdir /srv/www" -u targetuser

OR

ansible -v targethostname -m file -a "path=/srv/www state=directory" -u targetuser

Set variable in jinja

Just Set it up like this

{% set active_link = recordtype -%}

How to access a value defined in the application.properties file in Spring Boot

you can use @ConfigurationProperties it's simple and easy to access a value defined in application.properties

#datasource
app.datasource.first.jdbc-url=jdbc:mysql://x.x.x.x:3306/ovtools?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
app.datasource.first.username=
app.datasource.first.password=
app.datasource.first.driver-class-name=com.mysql.cj.jdbc.Driver
server.port=8686
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.database=mysql

@Slf4j
@Configuration
public class DataSourceConfig {
    @Bean(name = "tracenvDb")
    @Primary
    @ConfigurationProperties(prefix = "app.datasource.first")
    public DataSource mysqlDataSourceanomalie() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "JdbcTemplateenv")
    public JdbcTemplate jdbcTemplateanomalie(@Qualifier("tracenvDb") DataSource datasourcetracenv) {
        return new JdbcTemplate(datasourcetracenv);
    }

How do you know a variable type in java?

I learned from the Search Engine(My English is very bad , So code...) How to get variable's type? Up's :

String str = "test";
String type = str.getClass().getName();
value: type = java.lang.String

this method :

str.getClass().getSimpleName();
value:String

now example:

Object o = 1;
o.getClass().getSimpleName();
value:Integer

How to clear the Entry widget after a button is pressed in Tkinter?

if none of the above is working you can use this->

idAssignedToEntryWidget.delete(first = 0, last = UpperLimitAssignedToEntryWidget)

for e.g. ->

id assigned is = en then

en.delete(first =0, last =100)

Copy file(s) from one project to another using post build event...VS2010

I use it like this.

xcopy "$(TargetDir)$(TargetName).dll" "$(SolutionDir)Lib\TIRM\x86\" /F /Y 
xcopy "$(TargetDir)$(TargetName).lib" "$(SolutionDir)Lib\TIRM\x86\" /F /Y 


/F : Copy source is File   
/Y : Overwrite and don't ask me

Note the use of this. $(TargetDir) has already '\' "D:\MyProject\bin\" = $(TargetDir)

You can find macro in Command editor

enter image description here

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

You can also use the toBase64Image() method setting animation: false

var options = {
    bezierCurve : false,
    animation: false
};

Updated Fiddle

Fatal error: Call to a member function prepare() on null

@delato468 comment must be listed as a solution as it worked for me.

In addition to defining the parameter, the user must pass it too at the time of calling the function

fetch_data(PDO $pdo, $cat_id)

What is the worst real-world macros/pre-processor abuse you've ever come across?

In one year of the International Obfuscated C Coding Contest, there was an entry where the entire program was:

P

With the proviso that you could define P in the makefile to be whatever program you wanted.

As I recall, it won in one of the categories, and the next year a rule had popped up disallowing that style of entry.

(Edit: six months later or something... I'm sure the "No IOCCC" thing wasn't in the main question when I wrote this...)

Get element inside element by class and ID - JavaScript

If this needs to work in IE 7 or lower you need to remember that getElementsByClassName does not exist in all browsers. Because of this you can create your own getElementsByClassName or you can try this.

var fooDiv = document.getElementById("foo");

for (var i = 0, childNode; i <= fooDiv.childNodes.length; i ++) {
    childNode = fooDiv.childNodes[i];
    if (/bar/.test(childNode.className)) {
        childNode.innerHTML = "Goodbye world!";
    }
}

Proper way of checking if row exists in table in PL/SQL block

IMO code with a stand-alone SELECT used to check to see if a row exists in a table is not taking proper advantage of the database. In your example you've got a hard-coded ID value but that's not how apps work in "the real world" (at least not in my world - yours may be different :-). In a typical app you're going to use a cursor to find data - so let's say you've got an app that's looking at invoice data, and needs to know if the customer exists. The main body of the app might be something like

FOR aRow IN (SELECT * FROM INVOICES WHERE DUE_DATE < TRUNC(SYSDATE)-60)
LOOP
  -- do something here
END LOOP;

and in the -- do something here you want to find if the customer exists, and if not print an error message.

One way to do this would be to put in some kind of singleton SELECT, as in

-- Check to see if the customer exists in PERSON

BEGIN
  SELECT 'TRUE'
    INTO strCustomer_exists
    FROM PERSON
    WHERE PERSON_ID = aRow.CUSTOMER_ID;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    strCustomer_exists := 'FALSE';
END;

IF strCustomer_exists = 'FALSE' THEN
  DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
END IF;

but IMO this is relatively slow and error-prone. IMO a Better Way (tm) to do this is to incorporate it in the main cursor:

FOR aRow IN (SELECT i.*, p.ID AS PERSON_ID
               FROM INVOICES i
               LEFT OUTER JOIN PERSON p
                 ON (p.ID = i.CUSTOMER_PERSON_ID)
               WHERE DUE_DATA < TRUNC(SYSDATE)-60)
LOOP
  -- Check to see if the customer exists in PERSON

  IF aRow.PERSON_ID IS NULL THEN
    DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
  END IF;
END LOOP;

This code counts on PERSON.ID being declared as the PRIMARY KEY on PERSON (or at least as being NOT NULL); the logic is that if the PERSON table is outer-joined to the query, and the PERSON_ID comes up as NULL, it means no row was found in PERSON for the given CUSTOMER_ID because PERSON.ID must have a value (i.e. is at least NOT NULL).

Share and enjoy.

Removing packages installed with go get

#!/bin/bash

goclean() {
 local pkg=$1; shift || return 1
 local ost
 local cnt
 local scr

 # Clean removes object files from package source directories (ignore error)
 go clean -i $pkg &>/dev/null

 # Set local variables
 [[ "$(uname -m)" == "x86_64" ]] \
 && ost="$(uname)";ost="${ost,,}_amd64" \
 && cnt="${pkg//[^\/]}"

 # Delete the source directory and compiled package directory(ies)
 if (("${#cnt}" == "2")); then
  rm -rf "${GOPATH%%:*}/src/${pkg%/*}"
  rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*}"
 elif (("${#cnt}" > "2")); then
  rm -rf "${GOPATH%%:*}/src/${pkg%/*/*}"
  rm -rf "${GOPATH%%:*}/pkg/${ost}/${pkg%/*/*}"
 fi

 # Reload the current shell
 source ~/.bashrc
}

Usage:

# Either launch a new terminal and copy `goclean` into the current shell process, 
# or create a shell script and add it to the PATH to enable command invocation with bash.

goclean github.com/your-username/your-repository

How to combine two or more querysets in a Django view?

This recursive function concatenates array of querysets into one queryset.

def merge_query(ar):
    if len(ar) ==0:
        return [ar]
    while len(ar)>1:
        tmp=ar[0] | ar[1]
        ar[0]=tmp
        ar.pop(1)
        return ar

Difference between timestamps with/without time zone in PostgreSQL

Timestamptz vs Timestamp

The timestamptz field in Postgres is basically just the timestamp field where Postgres actually just stores the “normalised” UTC time, even if the timestamp given in the input string has a timezone.

If your input string is: 2018-08-28T12:30:00+05:30 , when this timestamp is stored in the database, it will be stored as 2018-08-28T07:00:00.

The advantage of this over the simple timestamp field is that your input to the database will be timezone independent, and will not be inaccurate when apps from different timezones insert timestamps, or when you move your database server location to a different timezone.

To quote from the docs:

For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system’s TimeZone parameter, and is converted to UTC using the offset for the timezone zone. To give a simple analogy, a timestamptz value represents an instant in time, the same instant for anyone viewing it. But a timestamp value just represents a particular orientation of a clock, which will represent different instances of time based on your timezone.

For pretty much any use case, timestamptz is almost always a better choice. This choice is made easier with the fact that both timestamptz and timestamp take up the same 8 bytes of data.

source: https://hasura.io/blog/postgres-date-time-data-types-on-graphql-fd926e86ee87/

What is the use of ByteBuffer in Java?

The ByteBuffer class is important because it forms a basis for the use of channels in Java. ByteBuffer class defines six categories of operations upon byte buffers, as stated in the Java 7 documentation:

  • Absolute and relative get and put methods that read and write single bytes;

  • Relative bulk get methods that transfer contiguous sequences of bytes from this buffer into an array;

  • Relative bulk put methods that transfer contiguous sequences of bytes from a byte array or some other byte buffer into this buffer;

  • Absolute and relative get and put methods that read and write values of other primitive types, translating them to and from sequences of bytes in a particular byte order;

  • Methods for creating view buffers, which allow a byte buffer to be viewed as a buffer containing values of some other primitive type; and

  • Methods for compacting, duplicating, and slicing a byte buffer.

Example code : Putting Bytes into a buffer.

    // Create an empty ByteBuffer with a 10 byte capacity
    ByteBuffer bbuf = ByteBuffer.allocate(10);

    // Get the buffer's capacity
    int capacity = bbuf.capacity(); // 10

    // Use the absolute put(int, byte).
    // This method does not affect the position.
    bbuf.put(0, (byte)0xFF); // position=0

    // Set the position
    bbuf.position(5);

    // Use the relative put(byte)
    bbuf.put((byte)0xFF);

    // Get the new position
    int pos = bbuf.position(); // 6

    // Get remaining byte count
    int rem = bbuf.remaining(); // 4

    // Set the limit
    bbuf.limit(7); // remaining=1

    // This convenience method sets the position to 0
    bbuf.rewind(); // remaining=7

React: trigger onChange if input value is changing by state?

I think you should change that like so:

<input value={this.state.value} onChange={(e) => {this.handleChange(e)}}/>

That is in principle the same as onClick={this.handleClick.bind(this)} as you did on the button.

So if you want to call handleChange() when the button is clicked, than:

<button onClick={this.handleChange.bind(this)}>Change Input</button>

or

handleClick () {
  this.setState({value: 'another random text'});
  this.handleChange();
}

Shall we always use [unowned self] inside closure in Swift

According to Apple-doc

  • Weak references are always of an optional type, and automatically become nil when the instance they reference is deallocated.

  • If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference

Example -

    // if my response can nil use  [weak self]
      resource.request().onComplete { [weak self] response in
      guard let strongSelf = self else {
        return
      }
      let model = strongSelf.updateModel(response)
      strongSelf.updateUI(model)
     }

    // Only use [unowned self] unowned if guarantees that response never nil  
      resource.request().onComplete { [unowned self] response in
      let model = self.updateModel(response)
      self.updateUI(model)
     }

How to get primary key column in Oracle?

Save the following script as something like findPK.sql.

set verify off
accept TABLE_NAME char prompt 'Table name>'

SELECT cols.column_name
FROM all_constraints cons NATURAL JOIN all_cons_columns cols
WHERE cons.constraint_type = 'P' AND table_name = UPPER('&TABLE_NAME');

It can then be called using

@findPK

Remove git mapping in Visual Studio 2015

The above answer did not work for me. The registry entries would just be automatically re-added when I opened the solution in Visual Studio. I found the resolution in one of the links in Matthews answer though so credit still goes to him for the correct answer.

Remove Git binding from Visual Studio 2013 solution?

Remove the hidden .git folder in your solutionfolder.

I also removed the .gitattributes and .gitignore files just to keep my folder clean.

How to install libusb in Ubuntu

Here is what worked for me.

Install the userspace USB programming library development files

sudo apt-get install libusb-1.0-0-dev
sudo updatedb && locate libusb.h

The path should appear as (or similar)

/usr/include/libusb-1.0/libusb.h

Include the header to your C code

#include <libusb-1.0/libusb.h>

Compile your C file

gcc -o example example.c -lusb-1.0

What is the correct way to free memory in C#

The garbage collector will come around and clean up anything that no longer has references to it. Unless you have unmanaged resources inside Foo, calling Dispose or using a using statement on it won't really help you much.

I'm fairly sure this applies, since it was still in C#. But, I took a game design course using XNA and we spent some time talking about the garbage collector for C#. Garbage collecting is expensive, since you have to check if you have any references to the object you want to collect. So, the GC tries to put this off as long as possible. So, as long as you weren't running out of physical memory when your program went to 700MB, it might just be the GC being lazy and not worrying about it yet.

But, if you just use Foo o outside the loop and create a o = new Foo() each time around, it should all work out fine.

Decorators with parameters?

Writing a decorator that works with and without parameter is a challenge because Python expects completely different behavior in these two cases! Many answers have tried to work around this and below is an improvement of answer by @norok2. Specifically, this variation eliminates the use of locals().

Following the same example as given by @norok2:

import functools

def multiplying(f_py=None, factor=1):
    assert callable(f_py) or f_py is None
    def _decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return factor * func(*args, **kwargs)
        return wrapper
    return _decorator(f_py) if callable(f_py) else _decorator


@multiplying
def summing(x): return sum(x)

print(summing(range(10)))
# 45


@multiplying()
def summing(x): return sum(x)

print(summing(range(10)))
# 45


@multiplying(factor=10)
def summing(x): return sum(x)

print(summing(range(10)))
# 450

Play with this code.

The catch is that the user must supply key,value pairs of parameters instead of positional parameters and the first parameter is reserved.

Imply bit with constant 1 or 0 in SQL Server

If you want the column is BIT and NOT NULL, you should put ISNULL before the CAST.

ISNULL(
   CAST (
      CASE
         WHEN FC.CourseId IS NOT NULL THEN 1 ELSE 0
      END
    AS BIT)
,0) AS IsCoursedBased

How to place Text and an Image next to each other in HTML?

You want to use css float for this, you can put it directly in your code.

<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>

But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).

HTML:

<body>
  <img src="website_art.png" class="myImage"/>
  <h3 class="heading">The Art of Gaming</h3>
</body>

CSS:

.myImage {
  float: left;
  height: 75px;
  width: 235px;
  font-family: Veranda;
}
.heading {
  float:right;
}

How to open the default webbrowser using java

Hope you don't mind but I cobbled together all the helpful stuff, from above, and came up with a complete class ready for testing...

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class MultiBrowPop {

    public static void main(String[] args) {
        OUT("\nWelcome to Multi Brow Pop.\nThis aims to popup a browsers in multiple operating systems.\nGood luck!\n");

        String url = "http://www.birdfolk.co.uk/cricmob";
        OUT("We're going to this page: "+ url);

        String myOS = System.getProperty("os.name").toLowerCase();
        OUT("(Your operating system is: "+ myOS +")\n");

        try {
            if(Desktop.isDesktopSupported()) { // Probably Windows
                OUT(" -- Going with Desktop.browse ...");
                Desktop desktop = Desktop.getDesktop();
                desktop.browse(new URI(url));
            } else { // Definitely Non-windows
                Runtime runtime = Runtime.getRuntime();
                if(myOS.contains("mac")) { // Apples
                    OUT(" -- Going on Apple with 'open'...");
                    runtime.exec("open " + url);
                } 
                else if(myOS.contains("nix") || myOS.contains("nux")) { // Linux flavours 
                    OUT(" -- Going on Linux with 'xdg-open'...");
                    runtime.exec("xdg-open " + url);
                }
                else 
                    OUT("I was unable/unwilling to launch a browser in your OS :( #SadFace");
            }
            OUT("\nThings have finished.\nI hope you're OK.");
        }
        catch(IOException | URISyntaxException eek) {
            OUT("**Stuff wrongly: "+ eek.getMessage());
        }
    }

    private static void OUT(String str) {
        System.out.println(str);
    }
}

How to run a cron job inside a docker container?

So, my problem was the same. The fix was to change the command section in the docker-compose.yml.

From

command: crontab /etc/crontab && tail -f /etc/crontab

To

command: crontab /etc/crontab

command: tail -f /etc/crontab

The problem was the '&&' between the commands. After deleting this, it was all fine.

(How) can I count the items in an enum?

There's not really a good way to do this, usually you see an extra item in the enum, i.e.

enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};

So then you can do:

int fuz[FOOBAR_NR_ITEMS];

Still not very nice though.

But of course you do realize that just the number of items in an enum is not safe, given e.g.

enum foobar {foo, bar = 5, baz, quz = 20};

the number of items would be 4, but the integer values of the enum values would be way out of the array index range. Using enum values for array indexing is not safe, you should consider other options.

edit: as requested, made the special entry stick out more.

Rails 3 execute custom sql query without a model

You could also use find_by_sql

# A simple SQL query spanning multiple tables
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]

Copy text from nano editor to shell

First method

This method seems to work when the content doesn't include ?.

Install xsel or similar and assign a global shortcut key for this command in your WM or DE:

xsel -o | sed -r 's/^ ?[[:digit:]]+($| +)//g' | perl -pe 's/\n/?/g' | sed -r 's/??/\n\n/g; s/ ?? {1,}/ /g; s/?/\n/g' | xsel -b

Put this in your ~/.Xresources:

*selectToClipboard: false

Issue this in your xterm once to activate the above option:

xrdb -load ~/.Xresources

Now select the line(s) including the line numbers by pressing Shift while dragging the mouse. After the selection click your key combo; the line(s) are coppied and ready to be pasted anywhere you like.

Second method

Doesn't have the shortcoming of the first method.

Install xdotool and xsel or similar.

Put these two lines

Ctrl <Btn3Down>: select-start(PRIMARY, CLIPBOARD)
Ctrl <Btn3Up>: select-end(CLIPBOARD, PRIMARY)

in your ~/.Xresources like so:

*VT100*translations: #override \n\
    Alt <Key> 0xf6: exec-formatted("xdg-open '%t'", PRIMARY, CUT_BUFFER0) \n\                           
    Ctrl <Key>0x2bb: copy-selection(CLIPBOARD) \n\                              
    Alt <Key>0x2bb: insert-selection(CLIPBOARD) \n\                             
    Ctrl <Key> +:       larger-vt-font() \n\                                    
    Ctrl <Key> -:       smaller-vt-font() \n\
    Ctrl <Btn3Down>: select-start(PRIMARY, CLIPBOARD) \n\
    Ctrl <Btn3Up>: select-end(CLIPBOARD, PRIMARY) 

Issue this in your xterm once to activate the above option:

xrdb -load ~/.Xresources

Create this scrip in your path:

#!/bin/bash                                                                  

filepid=$(xdotool getwindowpid $(xdotool getactivewindow))                   
file=$(ps -p "$filepid" o cmd | grep -o --color=never "/.*")                   

firstline=$(xsel -b)                                                         
lastline=$(xsel)                                                             

sed -n ""$firstline","$lastline"p" "$file" | xsel -b

Assign a global shortcut key to call this script in your WM or DE.

Now when you want to copy a line (paragraph), select only the line number of that line (paragraph) by right mouse button while pressing Shift+Ctrl. After the selection click your custom global key combo you've created before. The line (paragraph) is coppied and ready to be pasted anywhere you like.

If you want to copy multiple lines, do the above for the first line and then for the last line of the range, instead of Shift+Ctrl+Btn3 (right mouse button), just select the number by left mouse button while pressing only Shift. After this, again call the script by your custom global shortcut. The range of lines are coppied and ready to pasted anywhere you like.

Getting URL parameter in java and extract a specific text from that URL

I believe we have a better approach to answer this question.

1: Define a function that returns Map values.

Here we go.

public Map<String, String> getUrlValues(String url) throws UnsupportedEncodingException {
    int i = url.indexOf("?");
    Map<String, String> paramsMap = new HashMap<>();
    if (i > -1) {
        String searchURL = url.substring(url.indexOf("?") + 1);
        String params[] = searchURL.split("&");

        for (String param : params) {
            String temp[] = param.split("=");
            paramsMap.put(temp[0], java.net.URLDecoder.decode(temp[1], "UTF-8"));
        }
    }

    return paramsMap;
}

2: Call your function surrounding with a try catch block

Here we go

try {
     Map<String, String> values = getUrlValues("https://example.com/index.php?form_id=9&page=1&view_id=78");
     String formId = values.get("form_id");
     String page = values.get("page");
     String viewId = values.get("view_id");
     Log.d("FormID", formId);
     Log.d("Page", page);
     Log.d("ViewID", viewId);
} catch (UnsupportedEncodingException e) {
     Log.e("Error", e.getMessage());
} 

How to use PHP OPCache?

I encountered this when setting up moodle. I added the following lines in the php.ini file.

zend_extension=C:\xampp\php\ext\php_opcache.dll

[opcache]
opcache.enable = 1
opcache.memory_consumption = 128
opcache.max_accelerated_files = 4000
opcache.revalidate_freq = 60

; Required for Moodle
opcache.use_cwd = 1
opcache.validate_timestamps = 1
opcache.save_comments = 1
opcache.enable_file_override = 0

; If something does not work in Moodle
;opcache.revalidate_path = 1 ; May fix problems with include paths
;opcache.mmap_base = 0x20000000 ; (Windows only) fix OPcache crashes with event id 487

; Experimental for Moodle 2.6 and later
;opcache.fast_shutdown = 1
;opcache.enable_cli = 1 ; Speeds up CLI cron
;opcache.load_comments = 0 ; May lower memory use, might not be compatible with add-ons and other apps

extension=C:\xampp\php\ext\php_intl.dll

[intl]
intl.default_locale = en_utf8
intl.error_level = E_WARNING

intl -> http://php.net/manual/en/book.intl.php

What are the main performance differences between varchar and nvarchar SQL Server data types?

Disk space is not the issue... but memory and performance will be. Double the page reads, double index size, strange LIKE and = constant behaviour etc

Do you need to store Chinese etc script? Yes or no...

And from MS BOL "Storage and Performance Effects of Unicode"

Edit:

Recent SO question highlighting how bad nvarchar performance can be...

SQL Server uses high CPU when searching inside nvarchar strings

array_push() with key value pair

For Example:

$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');

For changing key value:

$data['firstKey'] = 'changedValue'; 
//this will change value of firstKey because firstkey is available in array

output:

Array ( [firstKey] => changedValue [secondKey] => secondValue )

For adding new key value pair:

$data['newKey'] = 'newValue'; 
//this will add new key and value because newKey is not available in array

output:

Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue )

Java: Static Class?

There's no point in declaring the class as static. Just declare its methods static and call them from the class name as normal, like Java's Math class.

Also, even though it isn't strictly necessary to make the constructor private, it is a good idea to do so. Marking the constructor private prevents other people from creating instances of your class, then calling static methods from those instances. (These calls work exactly the same in Java, they're just misleading and hurt the readability of your code.)

PHP is_numeric or preg_match 0-9 validation

is_numeric checks whether it is any sort of number, while your regex checks whether it is an integer, possibly with leading 0s. For an id, stored as an integer, it is quite likely that we will want to not have leading 0s. Following Spudley's answer, we can do:

/^[1-9][0-9]*$/

However, as Spudley notes, the resulting string may be too large to be stored as a 32-bit or 64-bit integer value. The maximum value of an signed 32-bit integer is 2,147,483,647 (10 digits), and the maximum value of an signed 64-bit integer is 9,223,372,036,854,775,807 (19 digits). However, many 10 and 19 digit integers are larger than the maximum 32-bit and 64-bit integers respectively. A simple regex-only solution would be:

/^[1-9][0-9]{0-8}$/ 

or

/^[1-9][0-9]{0-17}$/

respectively, but these "solutions" unhappily restrict each to 9 and 19 digit integers; hardly a satisfying result. A better solution might be something like:

$expr = '/^[1-9][0-9]*$/';
if (preg_match($expr, $id) && filter_var($id, FILTER_VALIDATE_INT)) {
    echo 'ok';
} else {
    echo 'nok';
}

How do I determine the current operating system with Node.js

Works fine for me

if (/^win/i.test(process.platform)) {
    // TODO: Windows
} else {
    // TODO: Linux, Mac or something else
}

The i modifier is used to perform case-insensitive matching.

How to add a default "Select" option to this ASP.NET DropDownList control?

Private Sub YourWebPage_PreRenderComplete(sender As Object, e As EventArgs) Handles Me.PreRenderComplete

     If Not IsPostBack Then
     DropDownList1.Items.Insert(0, "Select")
     End If

End Sub

How to push elements in JSON from javascript array

var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

Visual Studio 2015 installer hangs during install?

Same thing happened to me, and I also tried to terminate secondary process from task manager. Do not do that. It is not a solution, but rather a hack which may cause issues later. In my case, I was not even able to uninstall Visual Studio. I tried both web installation and ISO, same issue.

Here is how it worked finally. I restored my Windows 7 to earliest restore point as possible, when there was nothing installed, so I was sure that there would be no conflicts between the different tools (Java, Android API, etc.)

I started the installation of Visual Studio 2015 Community Release Candidate at 10 p.m. At 7 a.m., it was working on Android API 19-21. A hour later, it was finally preparing Visual Studio.

This means that all you need to do is to actually wait 8 to 9 hours. Don't terminate the secondary installer at risk of breaking your Visual Studio; just wait.

Changing column names of a data frame

Use the colnames() function:

R> X <- data.frame(bad=1:3, worse=rnorm(3))
R> X
  bad     worse
1   1 -2.440467
2   2  1.320113
3   3 -0.306639
R> colnames(X) <- c("good", "better")
R> X
  good    better
1    1 -2.440467
2    2  1.320113
3    3 -0.306639

You can also subset:

R> colnames(X)[2] <- "superduper"

Convert Year/Month/Day to Day of Year in Python

You could use strftime with a %j format string:

>>> import datetime
>>> today = datetime.datetime.now()
>>> today.strftime('%j')
'065'

but if you wish to do comparisons or calculations with this number, you would have to convert it to int() because strftime() returns a string. If that is the case, you are better off using DzinX's answer.

Remove characters except digits from string using Python?

x.translate(None, string.digits)

will delete all digits from string. To delete letters and keep the digits, do this:

x.translate(None, string.letters)

How to replace captured groups only?

A simplier option is to just capture the digits and replace them.

_x000D_
_x000D_
const name = 'preceding_text_0_following_text';_x000D_
const matcher = /(\d+)/;_x000D_
_x000D_
// Replace with whatever you would like_x000D_
const newName = name.replace(matcher, 'NEW_STUFF');_x000D_
console.log("Full replace", newName);_x000D_
_x000D_
// Perform work on the match and replace using a function_x000D_
// In this case increment it using an arrow function_x000D_
const incrementedName = name.replace(matcher, (match) => ++match);_x000D_
console.log("Increment", incrementedName);
_x000D_
_x000D_
_x000D_

Resources

Set position / size of UI element as percentage of screen size

The above problem can also be solved using ConstraintLayout through Guidelines.

Below is the snippet.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.constraint.Guideline
    android:id="@+id/upperGuideLine"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.68" />

<Gallery
    android:id="@+id/gallery"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/lowerGuideLine"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/upperGuideLine" />

<android.support.constraint.Guideline
    android:id="@+id/lowerGuideLine"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.84" />

</android.support.constraint.ConstraintLayout>

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is guaranteed to be a unsigned integer that is 16 bits large

unsigned short int is guaranteed to be a unsigned short integer, where short integer is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer is 16 bits large.

Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler

Minimum Type Limits

Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.

Type Minimum Range

signed char     -127 to +127
unsigned char      0 to 255
short int     -32767 to +32767
unsigned short int 0 to 65535

Android Studio - How to Change Android SDK Path

  1. Click on File menu.
  2. Select Project Structure.
  3. Edit the path in SDK Location text box. From the next time Android Studio will use this location for all your projects.

N.B.: Avoid having spaces in the path as it may sometimes lead to issues.

C++ convert from 1 char to string?

All of

std::string s(1, c); std::cout << s << std::endl;

and

std::cout << std::string(1, c) << std::endl;

and

std::string s; s.push_back(c); std::cout << s << std::endl;

worked for me.

How to run a shell script in OS X by double-clicking?

The easy way is to change the extension to .command or no extension.

But that will open the Terminal, and you will have to close it. If you don't want to see any output, you can use Automator to create a Mac Application that you can double click, add to the dock, etc.

  1. Open Automator application
  2. Choose "Application" type
  3. Type "run" in the Actions search box
  4. Double click "Run Shell Script"
  5. Click the Run button in upper right corner to test it.
  6. File > Save to create the Application.

enter image description here

What is the iOS 6 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

iPad:

Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

For a complete list and more details about the iOS user agent check out these 2 resources:
Safari User Agent Strings (http://useragentstring.com/pages/Safari/)
Complete List of iOS User-Agent Strings (http://enterpriseios.com/wiki/UserAgent)

Passing properties by reference in C#

To vote on this issue, here is one active suggestion of how this could be added to the language. I'm not saying this is the best way to do this (at all), feel free to put out your own suggestion. But allowing properties to be passed by ref like Visual Basic already can do would hugely help simplify some code, and quite often!

https://github.com/dotnet/csharplang/issues/1235

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

When should I use curly braces for ES6 import?

For a default export we do not use { } when we import.

For example,

File player.js

export default vx;

File index.js

import vx from './player';

File index.js

Enter image description here

File player.js

Enter image description here

If we want to import everything that we export then we use *:

Enter image description here

how to load CSS file into jsp

I use this version

<style><%@include file="/WEB-INF/css/style.css"%></style>

MATLAB, Filling in the area between two sets of data, lines in one figure

Building off of @gnovice's answer, you can actually create filled plots with shading only in the area between the two curves. Just use fill in conjunction with fliplr.

Example:

x=0:0.01:2*pi;                  %#initialize x array
y1=sin(x);                      %#create first curve
y2=sin(x)+.5;                   %#create second curve
X=[x,fliplr(x)];                %#create continuous x value array for plotting
Y=[y1,fliplr(y2)];              %#create y values for out and then back
fill(X,Y,'b');                  %#plot filled area

enter image description here

By flipping the x array and concatenating it with the original, you're going out, down, back, and then up to close both arrays in a complete, many-many-many-sided polygon.

CSS vertical-align: text-bottom;

Vertical align only works in some select cases. The easiest way to make it function is to set display: table in the parent element's CSS and display: table-cell; to the child element and then apply your vertical align attribute.

WCF timeout exception detailed investigation

If you havn't tried it already - encapsulate your Server-side WCF Operations in try/finally blocks, and add logging to ensure they are actually returning.

If those show that the Operations are completing, then my next step would be to go to a lower level, and look at the actual transport layer.

Wireshark or another similar packet capturing tool can be quite helpful at this point. I'm assuming this is running over HTTP on standard port 80.

Run Wireshark on the client. In the Options when you start the capture, set the capture filter to tcp http and host service.example.com - this will reduce the amount of irrelevant traffic.

If you can, modify your client to notify you the exact start time of the call, and the time when the timeout occurred. Or just monitor it closely.

When you get an error, then you can trawl through the Wireshark logs to find the start of the call. Right click on the first packet that has your client calling out on it (Should be something like GET /service.svc or POST /service.svc) and select Follow TCP Stream.

Wireshark will decode the entire HTTP Conversation, so you can ensure that WCF is actually sending back responses.

How to print a dictionary's key?

key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])

Convert .cer certificate to .jks

Just to be sure that this is really the "conversion" you need, please note that jks files are keystores, a file format used to store more than one certificate and allows you to retrieve them programmatically using the Java security API, it's not a one-to-one conversion between equivalent formats.

So, if you just want to import that certificate in a new ad-hoc keystore you can do it with Keystore Explorer, a graphical tool. You'll be able to modify the keystore and the certificates contained therein like you would have done with the java terminal utilities like keytool (but in a more accessible way).

How to resolve git's "not something we can merge" error

For posterity: Like AxeEffect said... if you have no typos check to see if you have ridiculous characters in your local branch name, like commas or apostrophes. Exactly that happened to me just now.

Combine two pandas Data Frames (join on a common column)

Joining fails if the DataFrames have some column names in common. The simplest way around it is to include an lsuffix or rsuffix keyword like so:

restaurant_review_frame.join(restaurant_ids_dataframe, on='business_id', how='left', lsuffix="_review")

This way, the columns have distinct names. The documentation addresses this very problem.

Or, you could get around this by simply deleting the offending columns before you join. If, for example, the stars in restaurant_ids_dataframe are redundant to the stars in restaurant_review_frame, you could del restaurant_ids_dataframe['stars'].

Resource u'tokenizers/punkt/english.pickle' not found

import nltk
nltk.download('punkt')

Open the Python prompt and run the above statements.

The sent_tokenize function uses an instance of PunktSentenceTokenizer from the nltk.tokenize.punkt module. This instance has already been trained and works well for many European languages. So it knows what punctuation and characters mark the end of a sentence and the beginning of a new sentence.

How to get only the date value from a Windows Forms DateTimePicker control?

string shortDate = dateTimePicker1.Value.ToShortDateString();

How do you change the datatype of a column in SQL Server?

The syntax to modify a column in an existing table in SQL Server (Transact-SQL) is:

ALTER TABLE table_name
    ALTER COLUMN column_name column_type;

For example:

ALTER TABLE employees
    ALTER COLUMN last_name VARCHAR(75) NOT NULL;

This SQL Server ALTER TABLE example will modify the column called last_name to be a data type of VARCHAR(75) and force the column to not allow null values.

see here

Mapping many-to-many association table with extra column(s)

As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.

For instance, the implementation code of the extra class should look like that:

@Entity
@Table(name = "USER_SERVICES")
public class UserService{

    // example of auto-generated ID
    @Id
    @Column(name = "USER_SERVICES_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long userServiceID;



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SERVICE_ID")
    private Service service;



    // example of extra column
    @Column(name="VISIBILITY")    
    private boolean visibility;



    public long getUserServiceID() {
        return userServiceID;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(boolean visibility) {
        this.visibility = visibility;
    }

}

How can I get the source code of a Python function?

dis is your friend if the source code is not available:

>>> import dis
>>> def foo(arg1,arg2):
...     #do something with args
...     a = arg1 + arg2
...     return a
...
>>> dis.dis(foo)
  3           0 LOAD_FAST                0 (arg1)
              3 LOAD_FAST                1 (arg2)
              6 BINARY_ADD
              7 STORE_FAST               2 (a)

  4          10 LOAD_FAST                2 (a)
             13 RETURN_VALUE

How can I use SUM() OVER()

Query would be like this:

SELECT ID, AccountID, Quantity, 
       SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT 

       FROM #Empl ORDER BY AccountID

Partition by works like group by. Here we are grouping by AccountID so sum would be corresponding to AccountID.

First first case, AccountID = 1 , then sum(quantity) = 10 + 5 + 2 => 17 & For AccountID = 2, then sum(Quantity) = 7+3 => 10

so result would appear like attached snapshot.

MySQL Install: ERROR: Failed to build gem native extension

In order to resolve

Gem::Ext::BuildError: ERROR: Failed to build gem native extension error for mysql2,

I think libmysql-ruby got changed with ruby-mysql

Simply try with following commands,

sudo apt-get install ruby-mysql

& then

sudo apt-get install libmysqlclient-dev

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

In Tomcat 8.0.44 I did this: create the JNDI on Tomcat's server.xml between the tag "GlobalNamingResources" For example:

_x000D_
_x000D_
<GlobalNamingResources>_x000D_
    <!-- Editable user database that can also be used by_x000D_
         UserDatabaseRealm to authenticate users_x000D_
    -->_x000D_
  <!-- Other previus resouces -->_x000D_
    <Resource auth="Container" driverClassName="org.postgresql.Driver" global="jdbc/your_jndi" _x000D_
    maxActive="100" maxIdle="20" maxWait="1000" minIdle="5" name="jdbc/your_jndi" password="your_password" _x000D_
    type="javax.sql.DataSource" url="jdbc:postgresql://localhost:5432/your_database?user=postgres" username="database_username"/>_x000D_
  </GlobalNamingResources>
_x000D_
_x000D_
_x000D_ In your web application you need a link to that resource (ResourceLink):

project explore

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<Context reloadable="true" >_x000D_
   <ResourceLink name="jdbc/your_jndi"_x000D_
      global="jdbc/your_jndi"_x000D_
      auth="Container"_x000D_
      type="javax.sql.DataSource" />_x000D_
</Context>
_x000D_
_x000D_
_x000D_

So if you're using Hiberte with spring you can tell to him to use the JNDI in your persistence.xml

persistence.xml location

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"_x000D_
 version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">_x000D_
 <persistence-unit name="UNIT_NAME" transaction-type="RESOURCE_LOCAL">_x000D_
  <provider>org.hibernate.ejb.HibernatePersistence</provider>_x000D_
_x000D_
  <properties>_x000D_
   <property name="javax.persistence.jdbc.driver"   value="org.postgresql.Driver" />_x000D_
   <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />_x000D_
   _x000D_
   <!--  <property name="hibernate.jdbc.time_zone" value="UTC"/>-->_x000D_
   <property name="hibernate.hbm2ddl.auto" value="update" />_x000D_
   <property name="hibernate.show_sql" value="false" />_x000D_
   <property name="hibernate.format_sql" value="true"/>     _x000D_
  </properties>_x000D_
 </persistence-unit>_x000D_
</persistence>
_x000D_
_x000D_
_x000D_

So in your spring.xml you can do that:

_x000D_
_x000D_
<bean id="postGresDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">_x000D_
   <property name="jndiName" value="java:comp/env/jdbc/your_jndi" />_x000D_
  </bean>_x000D_
     _x000D_
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">_x000D_
              <property name="persistenceUnitName" value="UNIT_NAME" />_x000D_
              <property name="dataSource" ref="postGresDataSource" />_x000D_
              <property name="jpaVendorAdapter"> _x000D_
                 <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />_x000D_
              </property>_x000D_
        </bean>
_x000D_
_x000D_
_x000D_ Look above that entityManagerFactory bean refers to your UNIT_NAME configured at persistence xml and the bean postGresDataSource has a property that points to your JNDI resource in Tomcat.

_x000D_
_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />
_x000D_
_x000D_
_x000D_

In this example I used spring with xml but you can do this programmaticaly if you prefer.

That's it, I hope helped.

Percentage width in a RelativeLayout

You can use PercentRelativeLayout, It is a recent undocumented addition to the Design Support Library, enables the ability to specify not only elements relative to each other but also the total percentage of available space.

Subclass of RelativeLayout that supports percentage based dimensions and margins. You can specify dimension or a margin of child by using attributes with "Percent" suffix.

<android.support.percent.PercentRelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
  <ImageView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layout_widthPercent="50%"
      app:layout_heightPercent="50%"
      app:layout_marginTopPercent="25%"
      app:layout_marginLeftPercent="25%"/>
</android.support.percent.PercentFrameLayout>

The Percent package provides APIs to support adding and managing percentage based dimensions in your app.

To use, you need to add this library to your Gradle dependency list:

dependencies {
    compile 'com.android.support:percent:22.2.0'//23.1.1
}

Adding headers when using httpClient.GetAsync

Sometimes, you only need this code.

 httpClient.DefaultRequestHeaders.Add("token", token);

How to set env variable in Jupyter notebook

If you need the variable set before you're starting the notebook, the only solution which worked for me was env VARIABLE=$VARIABLE jupyter notebook with export VARIABLE=value in .bashrc.

In my case tensorflow needs the exported variable for successful importing it in a notebook.

Rounded table corners CSS only

Add a <div> wrapper around the table, and apply the following CSS

border-radius: x px;
overflow: hidden;
display: inline-block;

to this wrapper.

Git: Recover deleted (remote) branch

I think that you have a mismatched config for 'fetch' and 'push' so this has caused default fetch/push to not round trip properly. Fortunately you have fetched the branches that you subsequently deleted so you should be able to recreate them with an explicit push.

git push origin origin/contact_page:contact_page origin/new_pictures:new_pictures

react-native: command not found

At first run this command on your terminal.

npm i -g react-native-cli

Then create your react-native project by this command.

React-native init Project name

then move to your project directory by cd command.

How to parse/format dates with LocalDateTime? (Java 8)

Parsing a string with date and time into a particular point in time (Java calls it an "Instant") is quite complicated. Java has been tackling this in several iterations. The latest one, java.time and java.time.chrono, covers almost all needs (except Time Dilation :) ).

However, that complexity brings a lot of confusion.

The key to understand date parsing is:

Why does Java have so many ways to parse a date

  1. There are several systems to measure a time. For instance, the historical Japanese calendars were derived from the time ranges of the reign of the respective emperor or dynasty. Then there is e.g. UNIX timestamp. Fortunately, the whole (business) world managed to use the same.
  2. Historically, the systems were being switched from/to, for various reasons. E.g. from Julian calendar to Gregorian calendar in 1582. So 'western' dates before that need to be treated differently.
  3. And of course the change did not happen at once. Because the calendar came from the headquarteds of some religion and other parts of Europe believed in other dieties, for instance Germany did not switch until the year 1700.

...and why is the LocalDateTime, ZonedDateTime et al. so complicated

  1. There are time zones. A time zone is basically a "stripe"*[1] of the Earth's surface whose authorities follow the same rules of when does it have which time offset. This includes summer time rules.
    The time zones change over time for various areas, mostly based on who conquers whom. And one time zone's rules change over time as well.

  2. There are time offsets. That is not the same as time zones, because a time zone may be e.g. "Prague", but that has summer time offset and winter time offset.
    If you get a timestamp with a time zone, the offset may vary, depending on what part of the year it is in. During the leap hour, the timestamp may mean 2 different times, so without additional information, it can't be reliably converted.
    Note: By timestamp I mean "a string that contains a date and/or time, optionally with a time zone and/or time offset."

  3. Several time zones may share the same time offset for certain periods. For instance, GMT/UTC time zone is the same as "London" time zone when the summer time offset is not in effect.

To make it a bit more complicated (but that's not too important for your use case) :

  1. The scientists observe Earth's dynamic, which changes over time; based on that, they add seconds at the end of individual years. (So 2040-12-31 24:00:00 may be a valid date-time.) This needs regular updates of the metadata that systems use to have the date conversions right. E.g. on Linux, you get regular updates to the Java packages including these new data.
  2. The updates do not always keep the previous behavior for both historical and future timestamps. So it may happen that parsing of the two timestamps around some time zone's change comparing them may give different results when running on different versions of the software. That also applies to comparing between the affected time zone and other time zone.

    Should this cause a bug in your software, consider using some timestamp that does not have such complicated rules, like UNIX timestamp.

  3. Because of 7, for the future dates, we can't convert dates exactly with certainty. So, for instance, current parsing of 8524-02-17 12:00:00 may be off a couple of seconds from the future parsing.

JDK's APIs for this evolved with the contemporary needs

  • The early Java releases had just java.util.Date which had a bit naive approach, assuming that there's just the year, month, day, and time. This quickly did not suffice.
  • Also, the needs of the databases were different, so quite early, java.sql.Date was introduced, with it's own limitations.
  • Because neither covered different calendars and time zones well, the Calendar API was introduced.
  • This still did not cover the complexity of the time zones. And yet, the mix of the above APIs was really a pain to work with. So as Java developers started working on global web applications, libraries that targeted most use cases, like JodaTime, got quickly popular. JodaTime was the de-facto standard for about a decade.
  • But the JDK did not integrate with JodaTime, so working with it was a bit cumbersome. So, after a very long discussion on how to approach the matter, JSR-310 was created mainly based on JodaTime.

How to deal with it in Java's java.time

Determine what type to parse a timestamp to

When you are consuming a timestamp string, you need to know what information it contains. This is the crucial point. If you don't get this right, you end up with a cryptic exceptions like "Can't create Instant" or "Zone offset missing" or "unknown zone id" etc.

Does it contain the date and the time?

  1. Does it have a time offset?
    A time offset is the +hh:mm part. Sometimes, +00:00 may be substituted with Z as 'Zulu time', UTC as Universal Time Coordinated, or GMT as Greenwich Mean Time. These also set the time zone.
    For these timestamps, you use OffsetDateTime.

  2. Does it have a time zone?
    For these timestamps, you use ZonedDateTime.
    Zone is specified either by

    • name ("Prague", "Pacific Standard Time", "PST"), or
    • "zone ID" ("America/Los_Angeles", "Europe/London"), represented by java.time.ZoneId.

    The list of time zones is compiled by a "TZ database", backed by ICAAN.

    According to ZoneId's javadoc, The zone id's can also somehow be specified as Z and offset. I'm not sure how this maps to real zones. If the timestamp, which only has a TZ, falls into a leap hour of time offset change, then it is ambiguous, and the interpretation is subject of ResolverStyle, see below.

  3. If it has neither, then the missing context is assumed or neglected. And the consumer has to decide. So it needs to be parsed as LocalDateTime and converted to OffsetDateTime by adding the missing info:

    • You can assume that it is a UTC time. Add the UTC offset of 0 hours.
    • You can assume that it is a time of the place where the conversion is happening. Convert it by adding the system's time zone.
    • You can neglect and just use it as is. That is useful e.g. to compare or substract two times (see Duration), or when you don't know and it doesn't really matter (e.g. local bus schedule).

Partial time information

  • Based on what the timestamp contains, you can take LocalDate, LocalTime, OffsetTime, MonthDay, Year, or YearMonth out of it.

If you have the full information, you can get a java.time.Instant. This is also internally used to convert between OffsetDateTime and ZonedDateTime.

Figure out how to parse it

There is an extensive documentation on DateTimeFormatter which can both parse a timestamp string and format to string.

The pre-created DateTimeFormatters should cover moreless all standard timestamp formats. For instance, ISO_INSTANT can parse 2011-12-03T10:15:30.123457Z.

If you have some special format, then you can create your own DateTimeFormatter (which is also a parser).

private static final DateTimeFormatter TIMESTAMP_PARSER = new DateTimeFormatterBuilder()
   .parseCaseInsensitive()
   .append(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SX"))
   .toFormatter();

I recommend to look at the source code of DateTimeFormatter and get inspired on how to build one using DateTimeFormatterBuilder. While you're there, also have a look at ResolverStyle which controls whether the parser is LENIENT, SMART or STRICT for the formats and ambiguous information.

TemporalAccessor

Now, the frequent mistake is to go into the complexity of TemporalAccessor. This comes from how the developers were used to work with SimpleDateFormatter.parse(String). Right, DateTimeFormatter.parse("...") gives you TemporalAccessor.

// No need for this!
TemporalAccessor ta = TIMESTAMP_PARSER.parse("2011-... etc");

But, equiped with the knowledge from the previous section, you can conveniently parse into the type you need:

OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z", TIMESTAMP_PARSER);

You do not actually need to the DateTimeFormatter either. The types you want to parse have the parse(String) methods.

OffsetDateTime myTimestamp = OffsetDateTime.parse("2011-12-03T10:15:30.123457Z");

Regarding TemporalAccessor, you can use it if you have a vague idea of what information there is in the string, and want to decide at runtime.

I hope I shed some light of understanding onto your soul :)

Note: There's a backport of java.time to Java 6 and 7: ThreeTen-Backport. For Android it has ThreeTenABP.

[1] Not just that they are not stripes, but there also some weird extremes. For instance, some neighboring pacific islands have +14:00 and -11:00 time zones. That means, that while on one island, there is 1st May 3 PM, on another island not so far, it is still 30 April 12 PM (if I counted correctly :) )

django: TypeError: 'tuple' object is not callable

There is comma missing in your tuple.

insert the comma between the tuples as shown:

pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))

Do the same for all

Private class declaration

Private outer class would be useless as nothing can access it.

See more details:

Java: Why can we define a top level class as private?

How to know if a DateTime is between a DateRange in C#

You could use extension methods to make it a little more readable:

public static class DateTimeExtensions
{
    public static bool InRange(this DateTime dateToCheck, DateTime startDate, DateTime endDate)
    {
        return dateToCheck >= startDate && dateToCheck < endDate;
    }
}

Now you can write:

dateToCheck.InRange(startDate, endDate)

How to throw an exception in C?

As mentioned in numerous threads, the "standard" way of doing this is using setjmp/longjmp. I posted yet another such solution to https://github.com/psevon/exceptions-and-raii-in-c This is to my knowledge the only solution that relies on automatic cleanup of allocated resources. It implements unique and shared smartpointers, and allows intermediate functions to let exceptions pass through without catching and still have their locally allocated resources cleaned up properly.

Is it possible to use jQuery .on and hover?

The jQuery plugin hoverIntent http://cherne.net/brian/resources/jquery.hoverIntent.html goes much further than the naive approaches listed here. While they certainly work, they might not necessarily behave how users expect.

The strongest reason to use hoverIntent is the timeout feature. It allows you to do things like prevent a menu from closing because a user drags their mouse slightly too far to the right or left before they click the item they want. It also provides capabilities for not activating hover events in a barrage and waits for focused hovering.

Usage example:

var config = {    
 sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
 interval: 200, // number = milliseconds for onMouseOver polling interval    
 over: makeTall, // function = onMouseOver callback (REQUIRED)    
 timeout: 500, // number = milliseconds delay before onMouseOut    
 out: makeShort // function = onMouseOut callback (REQUIRED)
};
$("#demo3 li").hoverIntent( config )

Further explaination of this can be found on https://stackoverflow.com/a/1089381/37055

Error Message : Cannot find or open the PDB file

If this happens in visual studio then clean your project and run it again.

Build --> Clean Solution

Run (or F5)

ReactJS - Does render get called any time "setState" is called?

It seems that the accepted answers are no longer the case when using React hooks. You can see in this code sandbox that the class component is rerendered when the state is set to the same value, while in the function component, setting the state to the same value doesn't cause a rerender.

https://codesandbox.io/s/still-wave-wouk2?file=/src/App.js

What's is the difference between train, validation and test set, in neural networks?

The training and validation sets are used during training.

for each epoch
    for each training data instance
        propagate error through the network
        adjust the weights
        calculate the accuracy over training data
    for each validation data instance
        calculate the accuracy over the validation data
    if the threshold validation accuracy is met
        exit training
    else
        continue training

Once you're finished training, then you run against your testing set and verify that the accuracy is sufficient.

Training Set: this data set is used to adjust the weights on the neural network.

Validation Set: this data set is used to minimize overfitting. You're not adjusting the weights of the network with this data set, you're just verifying that any increase in accuracy over the training data set actually yields an increase in accuracy over a data set that has not been shown to the network before, or at least the network hasn't trained on it (i.e. validation data set). If the accuracy over the training data set increases, but the accuracy over the validation data set stays the same or decreases, then you're overfitting your neural network and you should stop training.

Testing Set: this data set is used only for testing the final solution in order to confirm the actual predictive power of the network.

Wait for Angular 2 to load/resolve model before rendering view/template

Implement the routerOnActivate in your @Component and return your promise:

https://angular.io/docs/ts/latest/api/router/OnActivate-interface.html

EDIT: This explicitly does NOT work, although the current documentation can be a little hard to interpret on this topic. See Brandon's first comment here for more information: https://github.com/angular/angular/issues/6611

EDIT: The related information on the otherwise-usually-accurate Auth0 site is not correct: https://auth0.com/blog/2016/01/25/angular-2-series-part-4-component-router-in-depth/

EDIT: The angular team is planning a @Resolve decorator for this purpose.

Nullable types: better way to check for null or zero in c#

I agree with using the ?? operator.

If you're dealing with strings use if(String.IsNullOrEmpty(myStr))

Difference of keywords 'typename' and 'class' in templates?

There is no difference between using OR ; i.e. it is a convention used by C++ programmers. I myself prefer as it more clearly describes it use; i.e. defining a template with a specific type :)

Note: There is one exception where you do have to use class (and not typename) when declaring a template template parameter:

template <template class T> class C { }; // valid!

template <template typename T> class C { }; // invalid!

In most cases, you will not be defining a nested template definition, so either definition will work -- just be consistent in your use...

How to SUM parts of a column which have same text value in different column in the same row

This can be done by using SUMPRODUCT as well. Update the ranges as you see fit

=SUMPRODUCT(($A$2:$A$7=A2)*($B$2:$B$7=B2)*$C$2:$C$7)

A2:A7 = First name range

B2:B7 = Last Name Range

C2:C7 = Numbers Range

This will find all the names with the same first and last name and sum the numbers in your numbers column

Best Timer for using in a Windows service

Either one should work OK. In fact, System.Threading.Timer uses System.Timers.Timer internally.

Having said that, it's easy to misuse System.Timers.Timer. If you don't store the Timer object in a variable somewhere, then it is liable to be garbage collected. If that happens, your timer will no longer fire. Call the Dispose method to stop the timer, or use the System.Threading.Timer class, which is a slightly nicer wrapper.

What problems have you seen so far?

How to check for null/empty/whitespace values with a single test?

you can use

SELECT [column_name] 
FROM [table_name]
WHERE [column_name] LIKE '% %' 
OR [column_name] IS NULL

How to see indexes for a database or table in MySQL?

You could use this query to get the no of indexes as well as the index names of each table in specified database.

SELECT TABLE_NAME,
       COUNT(1) index_count,
       GROUP_CONCAT(DISTINCT(index_name) SEPARATOR ',\n ') indexes
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = 'mydb'
      AND INDEX_NAME != 'primary'
GROUP BY TABLE_NAME
ORDER BY COUNT(1) DESC;

How to call a PHP file from HTML or Javascript

As you have already stated in your question you have more than one option. A very basic approach would be using the tag referencing your PHP file in the method attribute. However as esoteric as it may sound AJAX is a more complete approach. Considering that an AJAX call (in combination with jQuery) can be as simple as:

$.post("yourfile.php", {data : "This can be as long as you want"});

And you get a more flexible solution, for example triggering a function after the server request is completed. Hope this helps.

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

This happened to me after upgrading from angular 1.6 -> 1.7 when using $sce.trustAsResourceUrl() as the return value of a function called from ng-src. You can see this issue mentioned here.

In my case I had to change the following.

<source ng-src="{{trustSrc(someUrl)}}" type='video/mp4' />
trustSrc = function(url){
    return $sce.trustAsResourceUrl(url);
};

to

<source ng-src='{{trustedUrl}} type='video/mp4' />
trustedUrl = $sce.trustAsResourceUrl(someUrl);

Add values to app.config and retrieve them

Are you missing the reference to System.Configuration.dll? ConfigurationManager class lies there.

EDIT: The System.Configuration namespace has classes in mscorlib.dll, system.dll and in system.configuration.dll. Your project always include the mscorlib.dll and system.dll references, but system.configuration.dll must be added to most project types, as it's not there by default...

Difference between DOM parentNode and parentElement

parentElement is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.

In most cases, it is the same as parentNode. The only difference comes when a node's parentNode is not an element. If so, parentElement is null.

As an example:

document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element

document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null

(document.documentElement.parentNode === document);  // true
(document.documentElement.parentElement === document);  // false

Since the <html> element (document.documentElement) doesn't have a parent that is an element, parentElement is null. (There are other, more unlikely, cases where parentElement could be null, but you'll probably never come across them.)

failed to open stream: HTTP wrapper does not support writeable connections

Instead of doing file_put_contents(***WebSiteURL***...) you need to use the server path to /cache/lang/file.php (e.g. /home/content/site/folders/filename.php).

You cannot open a file over HTTP and expect it to be written. Instead you need to open it using the local path.

How to import a module in Python with importlib.import_module

I think it's better to use importlib.import_module('.c', __name__) since you don't need to know about a and b.

I'm also wondering that, if you have to use importlib.import_module('a.b.c'), why not just use import a.b.c?

Google Chrome form autofill and its yellow background

In your tag, simply insert this small line of code.

autocomplete="off"

However, do not place this in the username/email/idname field because if you are still looking to use autocomplete, it will disable it for this field. But I found a way around this, simply place the code in your password input tag because you never autocomplete passwords anyways. This fix should remove the color force, matinain autocomplete ability on your email/username field, and allows you to avoid bulky hacks like Jquery or javascript.

How to remove a web site from google analytics

Feb 2016 version: Admin tab, then select Property in the middle column, click Property Settings, then the Move To Trash Can button at the top right. No need to delete individual views.

How to increase timeout for a single test case in mocha

You might also think about taking a different approach, and replacing the call to the network resource with a stub or mock object. Using Sinon, you can decouple the app from the network service, focusing your development efforts.

How to restore/reset npm configuration to default values?

If you run npm config edit, you'll get an editor showing the current configuration, and also a list of options and their default values.

But I don't think there's a 'reset' command.

How to comment in Vim's config files: ".vimrc"?

"This is a comment in vimrc. It does not have a closing quote 

Source: http://vim.wikia.com/wiki/Backing_up_and_commenting_vimrc

PHP preg_match - only allow alphanumeric strings and - _ characters

if(!preg_match('/^[\w-]+$/', $string1)) {
   echo "String 1 not acceptable acceptable";
   // String2 acceptable
}

Wait till a Function with animations is finished until running another Function

This answer uses promises, a JavaScript feature of the ECMAScript 6 standard. If your target platform does not support promises, polyfill it with PromiseJs.

You can get the Deferred object jQuery creates for the animation using .promise() on the animation call. Wrapping these Deferreds into ES6 Promises results in much cleaner code than using timers.

You can also use Deferreds directly, but this is generally discouraged because they do not follow the Promises/A+ specification.

The resulting code would look like this:

var p1 = Promise.resolve($('#Content').animate({ opacity: 0.5 }, { duration: 500, queue: false }).promise());
var p2 = Promise.resolve($('#Content').animate({ marginLeft: "-100px" }, { duration: 2000, queue: false }).promise());
Promise.all([p1, p2]).then(function () {
    return $('#Content').animate({ width: 0 }, { duration: 500, queue: false }).promise();
});

Note that the function in Promise.all() returns the promise. This is where magic happens. If in a then call a promise is returned, the next then call will wait for that promise to be resolved before executing.

jQuery uses an animation queue for each element. So animations on the same element are executed synchronously. In this case you wouldn't have to use promises at all!

I have disabled the jQuery animation queue to demonstrate how it would work with promises.

Promise.all() takes an array of promises and creates a new Promise that finishes after all promises in the array finished.

Promise.race() also takes an array of promises, but finishes as soon as the first Promise finished.

How to fetch JSON file in Angular 2

_x000D_
_x000D_
public init() {_x000D_
    return from(_x000D_
      fetch("assets/server-config.json").then(response => {_x000D_
        return response.json();_x000D_
      })_x000D_
    )_x000D_
      .pipe(_x000D_
        map(config => {_x000D_
          return config;_x000D_
        })_x000D_
      )_x000D_
      .toPromise();_x000D_
  }
_x000D_
_x000D_
_x000D_

c++ and opencv get and set pixel color to Mat

just use a reference:

Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;

How to make sure you don't get WCF Faulted state exception?


Update:

This linked answer describes a cleaner, simpler way of doing the same thing with C# syntax.


Original post

This is Microsoft's recommended way to handle WCF client calls:

For more detail see: Expected Exceptions

try
{
    ...
    double result = client.Add(value1, value2);
    ...
    client.Close();
}
catch (TimeoutException exception)
{
    Console.WriteLine("Got {0}", exception.GetType());
    client.Abort();
}
catch (CommunicationException exception)
{
    Console.WriteLine("Got {0}", exception.GetType());
    client.Abort();
}

Additional information

So many people seem to be asking this question on WCF that Microsoft even created a dedicated sample to demonstrate how to handle exceptions:

c:\WF_WCF_Samples\WCF\Basic\Client\ExpectedExceptions\CS\client

Download the sample: C# or VB

Considering that there are so many issues involving the using statement, (heated?) Internal discussions and threads on this issue, I'm not going to waste my time trying to become a code cowboy and find a cleaner way. I'll just suck it up, and implement WCF clients this verbose (yet trusted) way for my server applications.

Maven: How to run a .java file from command line passing arguments

In addition to running it with mvn exec:java, you can also run it with mvn exec:exec

mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath your.package.MainClass"

What is the purpose of the vshost.exe file?

It seems to be a long-running framework process for debugging (to decrease load times?). I discovered that when you start your application twice from the debugger often the same vshost.exe process will be used. It just unloads all user-loaded DLLs first. This does odd things if you are fooling around with API hooks from managed processes.

Best way to compare 2 XML documents in Java

The latest version of XMLUnit can help the job of asserting two XML are equal. Also XMLUnit.setIgnoreWhitespace() and XMLUnit.setIgnoreAttributeOrder() may be necessary to the case in question.

See working code of a simple example of XML Unit use below.

import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Assert;

public class TestXml {

    public static void main(String[] args) throws Exception {
        String result = "<abc             attr=\"value1\"                title=\"something\">            </abc>";
        // will be ok
        assertXMLEquals("<abc attr=\"value1\" title=\"something\"></abc>", result);
    }

    public static void assertXMLEquals(String expectedXML, String actualXML) throws Exception {
        XMLUnit.setIgnoreWhitespace(true);
        XMLUnit.setIgnoreAttributeOrder(true);

        DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expectedXML, actualXML));

        List<?> allDifferences = diff.getAllDifferences();
        Assert.assertEquals("Differences found: "+ diff.toString(), 0, allDifferences.size());
    }

}

If using Maven, add this to your pom.xml:

<dependency>
    <groupId>xmlunit</groupId>
    <artifactId>xmlunit</artifactId>
    <version>1.4</version>
</dependency>

How to create a DOM node as an object?

Try this:

var div = $('<div></div>').addClass('bar').text('bla');
var li = $('<li></li>').attr('id', '1234');
li.append(div);

$('body').append(li);

Obviously, it doesn't make sense to append a li to the body directly. Basically, the trick is to construct the DOM elementr tree with $('your html here'). I suggest to use CSS modifiers (.text(), .addClass() etc) as opposed to making jquery parse raw HTML, it will make it much easier to change things later.

How to create a table from select query result in SQL Server 2008

Use following syntax to create new table from old table in SQL server 2008

Select * into new_table  from  old_table 

Where are include files stored - Ubuntu Linux, GCC

gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo" and #include <zap> will search on your system, I recommend:

$ touch a.c
$ gcc -v -E a.c
 ...
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"

This is one way to see the search lists for included files, including (if any) directories into which #include "..." will look but #include <...> won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ... here;-) on any system on which gcc runs properly.

Word count from a txt file program

#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for k,v in wordcount.items():
    print k, v

Sort ArrayList of custom Objects by property

I found most if not all of these answers rely on the underlying class (Object) to implement comparable or to have a helper comparable interface.

Not with my solution! The following code lets you compare object's field by knowing their string name. You could easily modify it not to use the name, but then you need to expose it or construct one of the Objects you want to compare against.

Collections.sort(anArrayListOfSomeObjectPerhapsUsersOrSomething, new ReflectiveComparator(). new ListComparator("name"));

public class ReflectiveComparator {
    public class FieldComparator implements Comparator<Object> {
        private String fieldName;

        public FieldComparator(String fieldName){
            this.fieldName = fieldName;
        }

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public int compare(Object object1, Object object2) {
            try {
                Field field = object1.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);

                Comparable object1FieldValue = (Comparable) field.get(object1);
                Comparable object2FieldValue = (Comparable) field.get(object2);

                return object1FieldValue.compareTo(object2FieldValue);
            }catch (Exception e){}

            return 0;
        }
    }

    public class ListComparator implements Comparator<Object> {
        private String fieldName;

        public ListComparator(String fieldName) {
            this.fieldName = fieldName;
        }

        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public int compare(Object object1, Object object2) {
            try {
                Field field = object1.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                Comparable o1FieldValue = (Comparable) field.get(object1);
                Comparable o2FieldValue = (Comparable) field.get(object2);

                if (o1FieldValue == null){ return -1;}
                if (o2FieldValue == null){ return 1;}
                return o1FieldValue.compareTo(o2FieldValue);
            } catch (NoSuchFieldException e) {
                throw new IllegalStateException("Field doesn't exist", e);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException("Field inaccessible", e);
            }
        }
    }
}

scroll image with continuous scrolling using marquee tag

You cannot scroll images continuously using the HTML marquee tag - it must have JavaScript added for the continuous scrolling functionality.

There is a JavaScript plugin called crawler.js available on the dynamic drive forum for achieving this functionality. This plugin was created by John Davenport Scheuer and has been modified over time to suit new browsers.

I have also implemented this plugin into my blog to document all the steps to use this plugin. Here is the sample code:

<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src="assets/js/crawler.js" type="text/javascript" ></script>
</head>

<div id="mycrawler2" style="margin-top: -3px; " class="productswesupport">
    <img src="assets/images/products/ie.png" />
    <img src="assets/images/products/browser.png" />
    <img src="assets/images/products/chrome.png" />
    <img src="assets/images/products/safari.png" />
</div>

Here is the plugin configration:

marqueeInit({
    uniqueid: 'mycrawler2',
    style: {
    },
    inc: 5, //speed - pixel increment for each iteration of this marquee's movement
    mouse: 'cursor driven', //mouseover behavior ('pause' 'cursor driven' or false)
    moveatleast: 2,
    neutral: 150,
    savedirection: true,
    random: true
});

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

One solution for this can be found with find.

$ mkdir foo bar
$ touch foo/a.txt foo/Music.txt
$ find foo -type f ! -name '*Music*' -exec cp {} bar \;
$ ls bar
a.txt

Find has quite a few options, you can get pretty specific on what you include and exclude.

Edit: Adam in the comments noted that this is recursive. find options mindepth and maxdepth can be useful in controlling this.

vertical align middle in <div>

Use the translateY CSS property to vertically center your text in it's container

<style>
.centertext{

    position: relative;
    top: 50%;
    transform: translateY(40%);

}
</style>

And then apply it to your containing DIV

  <div class="centertext">
        <font style="color:white; font-size:20px;">   Your Text Here </font>
  </div>

Adjust the translateY percentage to suit your needs. Hope this helps

How to create and write to a txt file using VBA

To elaborate on Ben's answer:

If you add a reference to Microsoft Scripting Runtime and correctly type the variable fso you can take advantage of autocompletion (Intellisense) and discover the other great features of FileSystemObject.

Here is a complete example module:

Option Explicit

' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use
' the FileSystemObject which has many useful features for handling files and folders
Public Sub SaveTextToFile()

    Dim filePath As String
    filePath = "C:\temp\MyTestFile.txt"

    ' The advantage of correctly typing fso as FileSystemObject is to make autocompletion
    ' (Intellisense) work, which helps you avoid typos and lets you discover other useful
    ' methods of the FileSystemObject
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim fileStream As TextStream

    ' Here the actual file is created and opened for write access
    Set fileStream = fso.CreateTextFile(filePath)

    ' Write something to the file
    fileStream.WriteLine "something"

    ' Close it, so it is not locked anymore
    fileStream.Close

    ' Here is another great method of the FileSystemObject that checks if a file exists
    If fso.FileExists(filePath) Then
        MsgBox "Yay! The file was created! :D"
    End If

    ' Explicitly setting objects to Nothing should not be necessary in most cases, but if
    ' you're writing macros for Microsoft Access, you may want to uncomment the following
    ' two lines (see https://stackoverflow.com/a/517202/2822719 for details):
    'Set fileStream = Nothing
    'Set fso = Nothing

End Sub

Multi-line strings in PHP

$xml="l\rn";
$xml.="vv";

echo $xml;

But you should really look into http://us3.php.net/simplexml

Resize svg when window is resized in d3.js

_x000D_
_x000D_
d3.select("div#chartId")
   .append("div")
   // Container class to make it responsive.
   .classed("svg-container", true) 
   .append("svg")
   // Responsive SVG needs these 2 attributes and no width and height attr.
   .attr("preserveAspectRatio", "xMinYMin meet")
   .attr("viewBox", "0 0 600 400")
   // Class to make it responsive.
   .classed("svg-content-responsive", true)
   // Fill with a rectangle for visualization.
   .append("rect")
   .classed("rect", true)
   .attr("width", 600)
   .attr("height", 400);
_x000D_
.svg-container {
  display: inline-block;
  position: relative;
  width: 100%;
  padding-bottom: 100%; /* aspect ratio */
  vertical-align: top;
  overflow: hidden;
}
.svg-content-responsive {
  display: inline-block;
  position: absolute;
  top: 10px;
  left: 0;
}

svg .rect {
  fill: gold;
  stroke: steelblue;
  stroke-width: 5px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<div id="chartId"></div>
_x000D_
_x000D_
_x000D_

How can I convert ArrayList<Object> to ArrayList<String>?

Here is another alternative using Guava

List<Object> lst ...    
List<String> ls = Lists.transform(lst, Functions.toStringFunction());

Common HTTPclient and proxy

I had a similar problem with HttpClient version 4.

I couldn't connect to the server because of a SOCKS proxy error and I fixed it using the below configuration:

client.getParams().setParameter("socksProxyHost",proxyHost);
client.getParams().setParameter("socksProxyPort",proxyPort);

Using LINQ to find item in a List but get "Value cannot be null. Parameter name: source"

I think you can get this error if your database model is not correct and the underlying data contains a null which the model is attempting to map to a non-null object.

For example, some auto-generated models can attempt to map nvarchar(1) columns to char rather than string and hence if this column contains nulls it will throw an error when you attempt to access the data.

Note, LinqPad has a compatibility option if you want it to generate a model like that, but probably doesn't do this by default, which might explain it doesn't give you the error.

git replacing LF with CRLF

In a GNU/Linux shell prompt, dos2unix & unix2dos commands allow you to easely convert/format your files coming from MS Windows

jQuery show for 5 seconds then hide

You can use the below effect to animate, you can change the values as per your requirements

$("#myElem").fadeIn('slow').animate({opacity: 1.0}, 1500).effect("pulsate", { times: 2 }, 800).fadeOut('slow'); 

Load CSV file with Spark

If you want to load csv as a dataframe then you can do the following:

from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)

df = sqlContext.read.format('com.databricks.spark.csv') \
    .options(header='true', inferschema='true') \
    .load('sampleFile.csv') # this is your csv file

It worked fine for me.

Accessing a class' member variables in Python?

If you have an instance function (i.e. one that gets passed self) you can use self to get a reference to the class using self.__class__

For example in the code below tornado creates an instance to handle get requests, but we can get hold of the get_handler class and use it to hold a riak client so we do not need to create one for every request.

import tornado.web
import riak

class get_handler(tornado.web.requestHandler):
    riak_client = None

    def post(self):
        cls = self.__class__
        if cls.riak_client is None:
            cls.riak_client = riak.RiakClient(pb_port=8087, protocol='pbc')
        # Additional code to send response to the request ...
    

Can You Get A Users Local LAN IP Address Via JavaScript?

Now supported in internal-ip!

An RTCPeerConnection can be used. In browsers like Chrome where a getUserMedia permission is required, we can just detect available input devices and request for them.

const internalIp = async () => {
    if (!RTCPeerConnection) {
        throw new Error("Not supported.")
    }

    const peerConnection = new RTCPeerConnection({ iceServers: [] })

    peerConnection.createDataChannel('')
    peerConnection.createOffer(peerConnection.setLocalDescription.bind(peerConnection), () => { })

    peerConnection.addEventListener("icecandidateerror", (event) => {
        throw new Error(event.errorText)
    })

    return new Promise(async resolve => {
        peerConnection.addEventListener("icecandidate", async ({candidate}) => {
            peerConnection.close()
            
            if (candidate && candidate.candidate) {
                const result = candidate.candidate.split(" ")[4]
                if (result.endsWith(".local")) {
                    const inputDevices = await navigator.mediaDevices.enumerateDevices()
                    const inputDeviceTypes = inputDevices.map(({ kind }) => kind)

                    const constraints = {}

                    if (inputDeviceTypes.includes("audioinput")) {
                        constraints.audio = true
                    } else if (inputDeviceTypes.includes("videoinput")) {
                        constraints.video = true
                    } else {
                        throw new Error("An audio or video input device is required!")
                    }

                    const mediaStream = await navigator.mediaDevices.getUserMedia(constraints)
                    mediaStream.getTracks().forEach(track => track.stop())
                    resolve(internalIp())
                }
                resolve(result)
            }
        })
    })
}

Why should hash functions use a prime number modulus?

"The nature of math" regarding prime power moduli is that they are one building block of a finite field. The other two building blocks are an addition and a multiplication operation. The special property of prime moduli is that they form a finite field with the "regular" addition and multiplication operations, just taken to the modulus. This means every multiplication maps to a different integer modulo the prime, so does every addition.

Prime moduli are advantageous because:

  • They give the most freedom when choosing the secondary multiplier in secondary hashing, all multipliers except 0 will end up visiting all elements exactly once
  • If all hashes are less than the modulus there will be no collisions at all
  • Random primes mix better than power of two moduli and compress the information of all the bits not just a subset

They however have a big downside, they require an integer division, which takes many (~ 15-40) cycles, even on a modern CPU. With around half the computation one can make sure the hash is mixed up very well. Two multiplications and xorshift operations will mix better than a prime moudulus. Then we can use whatever hash table size and hash reduction is fastest, giving 7 operations in total for power of 2 table sizes and around 9 operations for arbitrary sizes.

I recently looked at many of the fastest hash table implementations and most of them don't use prime moduli.

The distribution of the hash table indices are mainly dependent on the hash function in use. A prime modulus can't fix a bad hash function and a good hash function does not benefit from a prime modulus. There are cases where they can be advantageous however. It can mend a half-bad hash function for example.

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

If you use two databases you can add another DataClasses.dbml and map the second database into it.
It works.

Sorted collection in Java

with Java 8 Comparator, if we want to sort list then Here are the 10 most populated cities in the world and we want to sort it by name, as reported by Time. Osaka, Japan. ... Mexico City, Mexico. ... Beijing, China. ... São Paulo, Brazil. ... Mumbai, India. ... Shanghai, China. ... Delhi, India. ... Tokyo, Japan.

 import java.util.Arrays;
 import java.util.Comparator;
 import java.util.List;

public class SortCityList {

    /*
     * Here are the 10 most populated cities in the world and we want to sort it by
     * name, as reported by Time. Osaka, Japan. ... Mexico City, Mexico. ...
     * Beijing, China. ... São Paulo, Brazil. ... Mumbai, India. ... Shanghai,
     * China. ... Delhi, India. ... Tokyo, Japan.
     */
    public static void main(String[] args) {
        List<String> cities = Arrays.asList("Osaka", "Mexico City", "São Paulo", "Mumbai", "Shanghai", "Delhi",
                "Tokyo");
        System.out.println("Before Sorting List is:-");
        System.out.println(cities);
        System.out.println("--------------------------------");

        System.out.println("After Use of List sort(String.CASE_INSENSITIVE_ORDER) & Sorting List is:-");
        cities.sort(String.CASE_INSENSITIVE_ORDER);
        System.out.println(cities);
        System.out.println("--------------------------------");
        System.out.println("After Use of List sort(Comparator.naturalOrder()) & Sorting List is:-");
        cities.sort(Comparator.naturalOrder());
        System.out.println(cities);

    }

}

C# DropDownList with a Dictionary as DataSource

If the DropDownList is declared in your aspx page and not in the codebehind, you can do it like this.

.aspx:

<asp:DropDownList ID="ddlStatus" runat="server" DataSource="<%# Statuses %>"
     DataValueField="Key" DataTextField="Value"></asp:DropDownList>

.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    ddlStatus.DataBind();
    // or use Page.DataBind() to bind everything
}

public Dictionary<int, string> Statuses
{
    get 
    {
        // do database/webservice lookup here to populate Dictionary
    }
};

Remove last character of a StringBuilder?

To avoid reinit(affect performance) of prefix use TextUtils.isEmpty:

            String prefix = "";
            for (String item : list) {
                sb.append(prefix);
                if (TextUtils.isEmpty(prefix))
                    prefix = ",";
                sb.append(item);
            }

Add a string of text into an input field when user clicks a button

this will do it with just javascript - you can also put the function in a .js file and call it with onclick

//button
<div onclick="
   document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>

Typedef function pointer?

  1. typedef is used to alias types; in this case you're aliasing FunctionFunc to void(*)().

  2. Indeed the syntax does look odd, have a look at this:

    typedef   void      (*FunctionFunc)  ( );
    //         ^                ^         ^
    //     return type      type name  arguments
    
  3. No, this simply tells the compiler that the FunctionFunc type will be a function pointer, it doesn't define one, like this:

    FunctionFunc x;
    void doSomething() { printf("Hello there\n"); }
    x = &doSomething;
    
    x(); //prints "Hello there"
    

Django DateField default options

Your mistake is using the datetime module instead of the date module. You meant to do this:

from datetime import date
date = models.DateField(_("Date"), default=date.today)

If you only want to capture the current date the proper way to handle this is to use the auto_now_add parameter:

date = models.DateField(_("Date"), auto_now_add=True)

However, the modelfield docs clearly state that auto_now_add and auto_now will always use the current date and are not a default value that you can override.

Apache is downloading php files instead of displaying them

I spent two days tracking this and found out that I was putting my PHP scripts in the wrong directory.

On my standard Ubuntu installation, I was putting the scripts in /var/www. They should have been in /var/www/html.

I just started PHP work, so I don't know if my solution relates to the version change you went through.

jQuery: Adding two attributes via the .attr(); method

Multiple Attribute

var tag = "tag name";
createNode(tag, target, attribute);

createNode: function(tag, target, attribute){
    var tag = jQuery("<" + tag + ">");
    jQuery.each(attribute, function(i,v){
        tag.attr(v);
    });
    target.append(tag);
    tag.appendTo(target);
}
var attribute = [
    {"data-level": "3"},
];

javascript regular expression to not match a word

function test(string) {
    return ! string.match(/abc|def/);
}

How to execute a query in ms-access in VBA code?

Take a look at this tutorial for how to use SQL inside VBA:

http://www.ehow.com/how_7148832_access-vba-query-results.html

For a query that won't return results, use (reference here):

DoCmd.RunSQL

For one that will, use (reference here):

Dim dBase As Database
dBase.OpenRecordset