Programs & Examples On #Inputstreamreader

How to convert an Image to base64 string in java?

I think you might want:

String encodedFile = Base64.getEncoder().encodeToString(bytes);

download a file from Spring boot rest service

I would suggest using a StreamingResponseBody since with it the application can write directly to the response (OutputStream) without holding up the Servlet container thread. It is a good approach if you are downloading a file very large.

@GetMapping("download")
public StreamingResponseBody downloadFile(HttpServletResponse response, @PathVariable Long fileId) {

    FileInfo fileInfo = fileService.findFileInfo(fileId);
    response.setContentType(fileInfo.getContentType());
    response.setHeader(
        HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + fileInfo.getFilename() + "\"");

    return outputStream -> {
        int bytesRead;
        byte[] buffer = new byte[BUFFER_SIZE];
        InputStream inputStream = fileInfo.getInputStream();
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
    };
}

Ps.: When using StreamingResponseBody, it is highly recommended to configure TaskExecutor used in Spring MVC for executing asynchronous requests. TaskExecutor is an interface that abstracts the execution of a Runnable.

More info: https://medium.com/swlh/streaming-data-with-spring-boot-restful-web-service-87522511c071

How to convert Java String to JSON Object

The string that you pass to the constructor JSONObject has to be escaped with quote():

public static java.lang.String quote(java.lang.String string)

Your code would now be:

JSONObject jsonObj = new JSONObject.quote(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);

How to get response body using HttpURLConnection, when code other than 2xx is returned?

If the response code isn't 200 or 2xx, use getErrorStream() instead of getInputStream().

Http 415 Unsupported Media type error with JSON

If you are making jquery ajax request, dont forget to add

contentType:'application/json'

Convert InputStream to JSONObject

use JsonReader in order to parse the InputStream. See example inside the API: http://developer.android.com/reference/android/util/JsonReader.html

POST request send json data java HttpUrlConnection

private JSONObject uploadToServer() throws IOException, JSONException {
            String query = "https://example.com";
            String json = "{\"key\":1}";

            URL url = new URL(query);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes("UTF-8"));
            os.close();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
            JSONObject jsonObject = new JSONObject(result);


            in.close();
            conn.disconnect();

            return jsonObject;
    }

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

A first step to diagnose the issue is by starting the client - and if you are running the server yourself, a private test instance of the server - by starting Java with the VM option:

-Djavax.net.debug=all

See also https://blogs.oracle.com/java-platform-group/entry/diagnosing_tls_ssl_and_https

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

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

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

Replace below line of code :

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

with

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

Java String to JSON conversion

Converting the String to JsonNode using ObjectMapper object :

ObjectMapper mapper = new ObjectMapper();

// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)

// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)

// For Json String 
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I had this issue on Android 10,

Changed targetSdkVersion 29 to targetSdkVersion 28 issue resolved. Not sure what is the actual problem.

I think not a good practice, but it worked.

before:

compileSdkVersion 29

minSdkVersion 14

targetSdkVersion 29

Now:

compileSdkVersion 29

minSdkVersion 14

targetSdkVersion 28

Java simple code: java.net.SocketException: Unexpected end of file from server

Most likely the headers you are setting is incorrect or not acceptable.

Example: connnection.setRequestProperty("content-type", "application/json");

HTTP Status 405 - Method Not Allowed Error for Rest API

I also had this problem and was able to solve it by enabling CORS support on the server. In my case it was an Azure server and it was easy: Enable CORS on Azure

So check for your server how it works and enable CORS. I didn't even need a browser plugin or proxy :)

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

How to draw interactive Polyline on route google maps v2 android

You should use options.addAll(allPoints); instead of options.add(point);

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Adding java.util.list will resolve your problem because List interface which you are trying to use is part of java.util.list package.

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

compression and decompression of string data in java

Client send some messages need be compressed, server (kafka) decompress the string meesage

Below is my sample:

compress:

   public static String compress(String str, String inEncoding) {
        if (str == null || str.length() == 0) {
            return str;
        }
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes(inEncoding));
            gzip.close();
            return URLEncoder.encode(out.toString("ISO-8859-1"), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

decompress:

    public static String decompress(String str, String outEncoding) {
        if (str == null || str.length() == 0) {
            return str;
        }

        try {
            String decode = URLDecoder.decode(str, "UTF-8");

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayInputStream in = new ByteArrayInputStream(decode.getBytes("ISO-8859-1"));
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString(outEncoding);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

Convert JSONArray to String Array

String[] arr = jsonArray.toString().replace("},{", " ,").split(" ");

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

SFTP file transfer using Java JSch

Below code works for me

   public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
  Session session = jsch.getSession(user, host);
  session.setPassword(password);
  session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

OR using StrictHostKeyChecking as "NO" (security consequences)

public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
   Session session = jsch.getSession(user, host, 22);
   Properties config = new Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);;
   session.setPassword(password);
   System.out.println("user=="+user+"\n host=="+host);
   session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

reading text file with utf-8 encoding using java

You are reading the file right but the problem seems to be with the default encoding of System.out. Try this to print the UTF-8 string-

PrintStream out = new PrintStream(System.out, true, "UTF-8");
out.println(str);

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

Two solutions for this error:

1. add this permission in your androidManifest.xml of your Android project

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

2. Turn on the Internet Connection of your device first.

Java Read Large Text File With 70million line of text

In Java 8, for anyone looking now to read file large files line by line,

Stream<String> lines = Files.lines(Paths.get("c:\myfile.txt"));
lines.forEach(l -> {
  // Do anything line by line   
});

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

How to add,set and get Header in request of HttpClient?

You can use HttpPost, there are methods to add Header to the Request.

DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);

httpPost.addHeader("header-name" , "header-value");

HttpResponse response = httpclient.execute(httpPost);

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

I also came across the same issue. I was trying to build the project with a clean install goal. I simply changed it to clean package -o in the run configuration. Then I re-built the project and it worked for me.

Taking inputs with BufferedReader in Java

You can't read individual integers in a single line separately using BufferedReader as you do using Scannerclass. Although, you can do something like this in regard to your query :

import java.io.*;
class Test
{
   public static void main(String args[])throws IOException
    {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       int t=Integer.parseInt(br.readLine());
       for(int i=0;i<t;i++)
       {
         String str=br.readLine();
         String num[]=br.readLine().split(" ");
         int num1=Integer.parseInt(num[0]);
         int num2=Integer.parseInt(num[1]);
         //rest of your code
       }
    }
}

I hope this will help you.

Using BufferedReader.readLine() in a while loop properly

In addition to the answer given by @ramin, if you already have BufferedReader or InputStream, it's possible to iterate through lines like this:

reader.lines().forEach(line -> {
    //...
});

or if you need to process it with given order:

reader.lines().forEachOrdered(line -> {
    //...
});

Java and HTTPS url connection without downloading certificate

But why don't I have to install a certificate locally for the site?

Well the code that you are using is explicitly designed to accept the certificate without doing any checks whatsoever. This is not good practice ... but if that is what you want to do, then (obviously) there is no need to install a certificate that your code is explicitly ignoring.

Shouldn't I have to install a certificate locally and load it for this program or is it downloaded behind the covers?

No, and no. See above.

Is the traffic between the client to the remote site still encrypted in transmission?

Yes it is. However, the problem is that since you have told it to trust the server's certificate without doing any checks, you don't know if you are talking to the real server, or to some other site that is pretending to be the real server. Whether this is a problem depends on the circumstances.


If we used the browser as an example, typically a browser doesn't ask the user to explicitly install a certificate for each ssl site visited.

The browser has a set of trusted root certificates pre-installed. Most times, when you visit an "https" site, the browser can verify that the site's certificate is (ultimately, via the certificate chain) secured by one of those trusted certs. If the browser doesn't recognize the cert at the start of the chain as being a trusted cert (or if the certificates are out of date or otherwise invalid / inappropriate), then it will display a warning.

Java works the same way. The JVM's keystore has a set of trusted certificates, and the same process is used to check the certificate is secured by a trusted certificate.

Does the java https client api support some type of mechanism to download certificate information automatically?

No. Allowing applications to download certificates from random places, and install them (as trusted) in the system keystore would be a security hole.

How can I iterate JSONObject to get individual items

You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .

public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
    Iterator<String> keys = json.keys();
    while(keys.hasNext()){
        String key = keys.next();
        String val = null;
        try{
             JSONObject value = json.getJSONObject(key);
             parse(value,out);
        }catch(Exception e){
            val = json.getString(key);
        }

        if(val != null){
            out.put(key,val);
        }
    }
    return out;
}

 public static void main(String[] args) throws JSONException {

    String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";

    JSONObject object = new JSONObject(json);

    JSONObject info = object.getJSONObject("ipinfo");

    Map<String,String> out = new HashMap<String, String>();

    parse(info,out);

    String latitude = out.get("latitude");
    String longitude = out.get("longitude");
    String city = out.get("city");
    String state = out.get("state");
    String country = out.get("country");
    String postal = out.get("postal_code");

    System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);

    System.out.println("ALL VALUE " + out);

}

Output:

    Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}

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

You can call the get() method of AsyncTask (or the overloaded get(long, TimeUnit)). This method will block until the AsyncTask has completed its work, at which point it will return you the Result.

It would be wise to be doing other work between the creation/start of your async task and calling the get method, otherwise you aren't utilizing the async task very efficiently.

How can I read a text file in Android?

Shortest form for small text files (in Kotlin):

val reader = FileReader(path)
val txt = reader.readText()
reader.close()

The system cannot find the file specified in java

Try to list all files' names in the directory by calling:

File file = new File(".");
for(String fileNames : file.list()) System.out.println(fileNames);

and see if you will find your files in the list.

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

Try moving <uses-permission> outside the <application> tag.

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

Just wanted to point out another reason this error can be thrown is if you defined a string resource for one translation of your app but did not provide a default string resource.

Example of the Issue:

As you can see below, I had a string resource for a Spanish string "get_started". It can still be referenced in code, but if the phone is not in Spanish it will have no resource to load and crash when calling getString().

values-es/strings.xml

<string name="get_started">SIGUIENTE</string>

Reference to resource

textView.setText(getString(R.string.get_started)

Logcat:

06-11 11:46:37.835    7007-7007/? E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.app.test PID: 7007
android.content.res.Resources$NotFoundException: String resource ID #0x7f0700fd
        at android.content.res.Resources.getText(Resources.java:299)
        at android.content.res.Resources.getString(Resources.java:385)
        at com.juvomobileinc.tigousa.ui.signin.SignInFragment$4.onClick(SignInFragment.java:188)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Solution to the Issue

Preventing this is quite simple, just make sure that you always have a default string resource in values/strings.xml so that if the phone is in another language it will always have a resource to fall back to.

values/strings.xml

<string name="get_started">Get Started</string>

values-en/strings.xml

<string name="get_started">Get Started</string>

values-es/strings.xml

<string name="get_started">Siguiente</string>

values-de/strings.xml

<string name="get_started">Ioslegen</string>

JSONException: Value of type java.lang.String cannot be converted to JSONObject

For me, I just needed to use getString() vs. getJSONObject() (the latter threw that error):

JSONObject jsonObject = new JSONObject(jsonString);
String valueIWanted = jsonObject.getString("access_token"))

Get JSONArray without array name?

JSONArray has a constructor which takes a String source (presumed to be an array).

So something like this

JSONArray array = new JSONArray(yourJSONArrayAsString);

socket programming multiple client to one server

I guess the problem is that you need to start a separate thread for each connection and call serverSocket.accept() in a loop to accept more than one connection.

It is not a problem to have more than one connection on the same port.

Why am I getting this error Premature end of file?

You are getting the error because the SAXBuilder is not intelligent enough to deal with "blank states". So it looks for at least an <xml ..> declaration, and when that causes a no data response it creates the exception you see rather than report the empty state.

Open URL in Java to get the content

I found this question while Googling. Note that if you just want to make use of the URI's content via something like a string, consider using Apache's IOUtils.toString() method.

For example, a sample line of code could be:

String pageContent = IOUtils.toString("http://maps.google.at/maps?saddr=4714&daddr=Marchtrenk&hl=de", Charset.UTF_8);

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

Try closing and reopening the file, then press Ctrl+F11.

Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.

Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.

How to get a web page's source code from Java

I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site

package javasandbox;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {

private static String sURL;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws MalformedURLException, IOException {
    sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
    System.out.println(sURL);
    URL url = new URL(sURL);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    //set http request headers
            httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
            httpCon.addRequestProperty("Connection", "keep-alive");
            httpCon.addRequestProperty("Cache-Control", "max-age=0");
            httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
            httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
            httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            //httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
            HttpURLConnection.setFollowRedirects(false);
            httpCon.setInstanceFollowRedirects(false);
            httpCon.setDoOutput(true);
            httpCon.setUseCaches(true);

            httpCon.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
            String inputLine;
            StringBuilder a = new StringBuilder();
            while ((inputLine = in.readLine()) != null)
                a.append(inputLine);
            in.close();

            System.out.println(a.toString());

            httpCon.disconnect();
}
}

compilation error: identifier expected

You also will have to catch or throw the IOException. See below. Not always the best way, but it will get you a result:

public class details {
    public static void main( String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

Masking password input from the console : Java

If you're dealing with a Java character array (such as password characters that you read from the console), you can convert it to a JRuby string with the following Ruby code:

# GIST: "pw_from_console.rb" under "https://gist.github.com/drhuffman12"

jconsole = Java::java.lang.System.console()
password = jconsole.readPassword()
ruby_string = ''
password.to_a.each {|c| ruby_string << c.chr}

# .. do something with 'password' variable ..    
puts "password_chars: #{password_chars.inspect}"
puts "password_string: #{password_string}"

See also "https://stackoverflow.com/a/27628738/4390019" and "https://stackoverflow.com/a/27628756/4390019"

The split() method in Java does not work on a dot (.)

The documentation on split() says:

Splits this string around matches of the given regular expression.

(Emphasis mine.)

A dot is a special character in regular expression syntax. Use Pattern.quote() on the parameter to split() if you want the split to be on a literal string pattern:

String[] words = temp.split(Pattern.quote("."));

What’s the best way to load a JSONObject from a json text file?

With java 8 you can try this:

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JSONUtil {

    public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
        String content = new String(Files.readAllBytes(Paths.get(filename)));
        return new JSONObject(content);
    }

    public static void main(String[] args) throws IOException, JSONException {
        String filename = "path/to/file/abc.json";
        JSONObject jsonObject = parseJSONFile(filename);

        //do anything you want with jsonObject
    }
}

Code for download video from Youtube on Java, Android

METHOD 1 ( Recommanded )

Library YouTubeExtractor

Add into your gradle file

 allprojects {
        repositories {
            maven { url "https://jitpack.io" }
        }
    }

And dependencies

 compile 'com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'

Add this small code and you done. Demo HERE

public class MainActivity extends AppCompatActivity {

    private static final String YOUTUBE_ID = "ea4-5mrpGfE";

    private final YouTubeExtractor mExtractor = YouTubeExtractor.create();


    private Callback<YouTubeExtractionResult> mExtractionCallback = new Callback<YouTubeExtractionResult>() {
        @Override
        public void onResponse(Call<YouTubeExtractionResult> call, Response<YouTubeExtractionResult> response) {
            bindVideoResult(response.body());
        }

        @Override
        public void onFailure(Call<YouTubeExtractionResult> call, Throwable t) {
            onError(t);
        }
    };


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


//        For android youtube extractor library  com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'
        mExtractor.extract(YOUTUBE_ID).enqueue(mExtractionCallback);

    }


    private void onError(Throwable t) {
        t.printStackTrace();
        Toast.makeText(MainActivity.this, "It failed to extract. So sad", Toast.LENGTH_SHORT).show();
    }


    private void bindVideoResult(YouTubeExtractionResult result) {

//        Here you can get download url link
        Log.d("OnSuccess", "Got a result with the best url: " + result.getBestAvailableQualityVideoUri());

        Toast.makeText(this, "result : " + result.getSd360VideoUri(), Toast.LENGTH_SHORT).show();
    }
}

You can get download link in bindVideoResult() method.

METHOD 2

Using this library android-youtubeExtractor

Add into gradle file

repositories {
    maven { url "https://jitpack.io" }
}

compile 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT'

Here is the code for getting download url.

       String youtubeLink = "http://youtube.com/watch?v=xxxx";

    YouTubeUriExtractor ytEx = new YouTubeUriExtractor(this) {
        @Override
        public void onUrisAvailable(String videoId, String videoTitle, SparseArray<YtFile> ytFiles) {
            if (ytFiles != null) {
                int itag = 22;
// Here you can get download url
                String downloadUrl = ytFiles.get(itag).getUrl();
            }
        }
    };

    ytEx.execute(youtubeLink);

Android app unable to start activity componentinfo

The question is answered already, but I want add more information about the causes.

Android app unable to start activity componentinfo

This error often comes with appropriate logs. You can read logs and can solve this issue easily.

Here is a sample log. In which you can see clearly ClassCastException. So this issue came because TextView cannot be cast to EditText.

Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText

11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Looper.loop(Looper.java:137)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:45)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:24:10.543: E/AndroidRuntime(1050):     ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Looper.loop(Looper.java:137)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:31:32.194: E/AndroidRuntime(1109):     ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Looper.loop(Looper.java:137)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 02:11:09.855: E/AndroidRuntime(1167):     ... 11 more

Some Common Mistakes.

1.findViewById() of non existing view

Like when you use findViewById(R.id.button) when button id does not exist in layout XML.

2. Wrong cast.

If you wrong cast some class, then you get this error. Like you cast RelativeLayout to LinearLayout or EditText to TextView.

3. Activity not registered in manifest.xml

If you did not register Activity in manifest.xml then this error comes.

4. findViewById() with declaration at top level

Below code is incorrect. This will create error. Because you should do findViewById() after calling setContentView(). Because an View can be there after it is created.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect way

  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mainImage = (ImageView) findViewById(R.id.imageViewMain); //correct way
    //...
  }
}

5. Starting abstract Activity class.

When you try to start an Activity which is abstract, you will will get this error. So just remove abstract keyword before activity class name.

6. Using kotlin but kotlin not configured.

If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.

More information

Read about Downcast and Upcast

Read about findViewById() method of Activity class

Super keyword in Java

How to register activity in manifest

java.net.ConnectException: Connection refused

You probably didn't initialize the server or client is trying to connect to wrong ip/port.

Where to get "UTF-8" string literal in Java?

In Java 1.7+

Do not use "UTF-8" string, instead use Charset type parameter:

import java.nio.charset.StandardCharsets

...

new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);

Received fatal alert: handshake_failure through SSLHandshakeException

I had a similar issue; upgrading to Apache HTTPClient 4.5.3 fixed it.

Reading a simple text file

try this,

package example.txtRead;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class txtRead extends Activity {
    String labels="caption";
    String text="";
    String[] s;
    private Vector<String> wordss;
    int j=0;
    private StringTokenizer tokenizer;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        wordss = new Vector<String>();
        TextView helloTxt = (TextView)findViewById(R.id.hellotxt);
        helloTxt.setText(readTxt());
 }

    private String readTxt(){

     InputStream inputStream = getResources().openRawResource(R.raw.toc);
//     InputStream inputStream = getResources().openRawResource(R.raw.internals);
     System.out.println(inputStream);
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

     int i;
  try {
   i = inputStream.read();
   while (i != -1)
      {
       byteArrayOutputStream.write(i);
       i = inputStream.read();
      }
      inputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

     return byteArrayOutputStream.toString();
    }
}

Java Runtime.getRuntime(): getting output from executing a command line program

Also we can use streams for obtain command output:

public static void main(String[] args) throws IOException {

        Runtime runtime = Runtime.getRuntime();
        String[] commands  = {"free", "-h"};
        Process process = runtime.exec(commands);

        BufferedReader lineReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        lineReader.lines().forEach(System.out::println);

        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        errorReader.lines().forEach(System.out::println);
    }

Java Programming: call an exe from Java and passing parameters

Below works for me if your exe depend on some dll or certain dependency then you need to set directory path. As mention below exePath mean folder where exe placed along with it's references files.

Exe application creating any temporaray file so it will create in folder mention in processBuilder.directory(...)

**

ProcessBuilder processBuilder = new ProcessBuilder(arguments);
processBuilder.redirectOutput(Redirect.PIPE);
processBuilder.directory(new File(exePath));
process = processBuilder.start();
int waitFlag = process.waitFor();// Wait to finish application execution.
if (waitFlag == 0) {
...
 int returnVal = process.exitValue();
} 

**

Reading inputStream using BufferedReader.readLine() is too slow

I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader's fault. Try measuring this:

InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing

I think you'll find it's almost exactly the same time as when you're parsing the text.

Note that you should also give InputStreamReader an appropriate encoding - the platform default encoding is almost certainly not what you should be using.

process.waitFor() never returns

There are many reasons that waitFor() doesn't return.

But it usually boils down to the fact that the executed command doesn't quit.

This, again, can have many reasons.

One common reason is that the process produces some output and you don't read from the appropriate streams. This means that the process is blocked as soon as the buffer is full and waits for your process to continue reading. Your process in turn waits for the other process to finish (which it won't because it waits for your process, ...). This is a classical deadlock situation.

You need to continually read from the processes input stream to ensure that it doesn't block.

There's a nice article that explains all the pitfalls of Runtime.exec() and shows ways around them called "When Runtime.exec() won't" (yes, the article is from 2000, but the content still applies!)

FileNotFoundException while getting the InputStream object from HttpURLConnection

For anybody else stumbling over this, the same happened to me while trying to send a SOAP request header to a SOAP service. The issue was a wrong order in the code, I requested the input stream first before sending the XML body. In the code snipped below, the line InputStream in = conn.getInputStream(); came immediately after ByteArrayOutputStream out = new ByteArrayOutputStream(); which is the incorrect order of things.

ByteArrayOutputStream out = new ByteArrayOutputStream();
// send SOAP request as part of HTTP body 
byte[] data = request.getHttpBody().getBytes("UTF-8");
conn.getOutputStream().write(data); 

if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
  Log.d(TAG, "http response code is " + conn.getResponseCode());
  return null;
}

InputStream in = conn.getInputStream();

FileNotFound in this case was an unfortunate way to encode HTTP response code 400.

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

Reading InputStream as UTF-8

String file = "";

try {

    InputStream is = new FileInputStream(filename);
    String UTF8 = "utf8";
    int BUFFER_SIZE = 8192;

    BufferedReader br = new BufferedReader(new InputStreamReader(is,
            UTF8), BUFFER_SIZE);
    String str;
    while ((str = br.readLine()) != null) {
        file += str;
    }
} catch (Exception e) {

}

Try this,.. :-)

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

Android read text raw resource file

Rather do it this way:

// reads resources regardless of their size
public byte[] getResource(int id, Context context) throws IOException {
    Resources resources = context.getResources();
    InputStream is = resources.openRawResource(id);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    byte[] readBuffer = new byte[4 * 1024];

    try {
        int read;
        do {
            read = is.read(readBuffer, 0, readBuffer.length);
            if(read == -1) {
                break;
            }
            bout.write(readBuffer, 0, read);
        } while(true);

        return bout.toByteArray();
    } finally {
        is.close();
    }
}

    // reads a string resource
public String getStringResource(int id, Charset encoding) throws IOException {
    return new String(getResource(id, getContext()), encoding);
}

    // reads an UTF-8 string resource
public String getStringResource(int id) throws IOException {
    return new String(getResource(id, getContext()), Charset.forName("UTF-8"));
}

From an Activity, add

public byte[] getResource(int id) throws IOException {
        return getResource(id, this);
}

or from a test case, add

public byte[] getResource(int id) throws IOException {
        return getResource(id, getContext());
}

And watch your error handling - don't catch and ignore exceptions when your resources must exist or something is (very?) wrong.

How to capitalize the first letter of a String in Java?

class CapitalizeWords
{
    public static void main(String[] args) 
    {
        String input ="welcome to kashmiri geeks...";

        System.out.println(input);

        String[] str = input.split(" ");

        for(int i=0; i< str.length; i++)
        {
            str[i] = (str[i]).substring(0,1).toUpperCase() + (str[i]).substring(1);
        }

        for(int i=0;i<str.length;i++)
        {
            System.out.print(str[i]+" ");
        }


    }
}

Why java.security.NoSuchProviderException No such provider: BC?

you can add security provider by editing java.security by adding security.provider.=org.bouncycastle.jce.provider.BouncyCastleProvider

or add a line in your top of your class

Security.addProvider(new BouncyCastleProvider());

you can use below line to specify provider while specifying algorithms

Cipher cipher = Cipher.getInstance("AES", "SunJCE");

if you are using other provider like Bouncy Castle then

Cipher cipher =  Cipher.getInstance("AES", "BC");

Java Process with Input/Output Stream

Firstly, I would recommend replacing the line

Process process = Runtime.getRuntime ().exec ("/bin/bash");

with the lines

ProcessBuilder builder = new ProcessBuilder("/bin/bash");
builder.redirectErrorStream(true);
Process process = builder.start();

ProcessBuilder is new in Java 5 and makes running external processes easier. In my opinion, its most significant improvement over Runtime.getRuntime().exec() is that it allows you to redirect the standard error of the child process into its standard output. This means you only have one InputStream to read from. Before this, you needed to have two separate Threads, one reading from stdout and one reading from stderr, to avoid the standard error buffer filling while the standard output buffer was empty (causing the child process to hang), or vice versa.

Next, the loops (of which you have two)

while ((line = reader.readLine ()) != null) {
    System.out.println ("Stdout: " + line);
}

only exit when the reader, which reads from the process's standard output, returns end-of-file. This only happens when the bash process exits. It will not return end-of-file if there happens at present to be no more output from the process. Instead, it will wait for the next line of output from the process and not return until it has this next line.

Since you're sending two lines of input to the process before reaching this loop, the first of these two loops will hang if the process hasn't exited after these two lines of input. It will sit there waiting for another line to be read, but there will never be another line for it to read.

I compiled your source code (I'm on Windows at the moment, so I replaced /bin/bash with cmd.exe, but the principles should be the same), and I found that:

  • after typing in two lines, the output from the first two commands appears, but then the program hangs,
  • if I type in, say, echo test, and then exit, the program makes it out of the first loop since the cmd.exe process has exited. The program then asks for another line of input (which gets ignored), skips straight over the second loop since the child process has already exited, and then exits itself.
  • if I type in exit and then echo test, I get an IOException complaining about a pipe being closed. This is to be expected - the first line of input caused the process to exit, and there's nowhere to send the second line.

I have seen a trick that does something similar to what you seem to want, in a program I used to work on. This program kept around a number of shells, ran commands in them and read the output from these commands. The trick used was to always write out a 'magic' line that marks the end of the shell command's output, and use that to determine when the output from the command sent to the shell had finished.

I took your code and I replaced everything after the line that assigns to writer with the following loop:

while (scan.hasNext()) {
    String input = scan.nextLine();
    if (input.trim().equals("exit")) {
        // Putting 'exit' amongst the echo --EOF--s below doesn't work.
        writer.write("exit\n");
    } else {
        writer.write("((" + input + ") && echo --EOF--) || echo --EOF--\n");
    }
    writer.flush();

    line = reader.readLine();
    while (line != null && ! line.trim().equals("--EOF--")) {
        System.out.println ("Stdout: " + line);
        line = reader.readLine();
    }
    if (line == null) {
        break;
    }
}

After doing this, I could reliably run a few commands and have the output from each come back to me individually.

The two echo --EOF-- commands in the line sent to the shell are there to ensure that output from the command is terminated with --EOF-- even in the result of an error from the command.

Of course, this approach has its limitations. These limitations include:

  • if I enter a command that waits for user input (e.g. another shell), the program appears to hang,
  • it assumes that each process run by the shell ends its output with a newline,
  • it gets a bit confused if the command being run by the shell happens to write out a line --EOF--.
  • bash reports a syntax error and exits if you enter some text with an unmatched ).

These points might not matter to you if whatever it is you're thinking of running as a scheduled task is going to be restricted to a command or a small set of commands which will never behave in such pathological ways.

EDIT: improve exit handling and other minor changes following running this on Linux.

java.io.IOException: Server returned HTTP response code: 500

I had this problem i.e. works fine when pasted into browser but 505s when done through java. It was simply the spaces that needed to be escaped/encoded.

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Solutions:

Solution A:

  1. Download http://www.servlets.com/cos/index.html
  2. Invoke getParameters() on com.oreilly.servlet.MultipartRequest

Solution B:

  1. Download http://jakarta.Apache.org/commons/fileupload/
  2. Invoke readHeaders() in org.apache.commons.fileupload.MultipartStream

Solution C:

  1. Download http://users.boone.net/wbrameld/multipartformdata/
  2. Invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData

Solution D:

Use Struts. Struts 1.1 handles this automatically.

Reference: http://www.jguru.com/faq/view.jsp?EID=1045507

Http Basic Authentication in Java using HttpClient?

An easy way to login with a HTTP POST without doing any Base64 specific calls is to use the HTTPClient BasicCredentialsProvider

import java.io.IOException;
import static java.lang.System.out;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;

//code
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password);
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

HttpResponse response = client.execute(new HttpPost("http://address/test/login"));//Replace HttpPost with HttpGet if you need to perform a GET to login
int statusCode = response.getStatusLine().getStatusCode();
out.println("Response Code :"+ statusCode);

Get Memory Usage in Android

enter the android terminal and then you can type the following commands :dumpsys cpuinfo

shell@android:/ $ dumpsys cpuinfo                                              
Load: 0.8 / 0.75 / 1.15
CPU usage from 69286ms to 9283ms ago with 99% awake:
  47% 1118/com.wxg.sodproject: 12% user + 35% kernel
  1.6% 1225/android.process.media: 1% user + 0.6% kernel
  1.3% 263/mpdecision: 0.1% user + 1.2% kernel
  0.1% 32747/kworker/u:1: 0% user + 0.1% kernel
  0.1% 883/com.android.systemui: 0.1% user + 0% kernel
  0.1% 521/system_server: 0.1% user + 0% kernel / faults: 14 minor
  0.1% 1826/com.quicinc.trepn: 0.1% user + 0% kernel
  0.1% 2462/kworker/0:2: 0.1% user + 0% kernel
  0.1% 32649/kworker/0:0: 0% user + 0.1% kernel
  0% 118/mmcqd/0: 0% user + 0% kernel
  0% 179/surfaceflinger: 0% user + 0% kernel
  0% 46/kinteractiveup: 0% user + 0% kernel
  0% 141/jbd2/mmcblk0p26: 0% user + 0% kernel
  0% 239/sdcard: 0% user + 0% kernel
  0% 1171/com.xiaomi.channel:pushservice: 0% user + 0% kernel / faults: 1 minor
  0% 1207/com.xiaomi.channel: 0% user + 0% kernel / faults: 1 minor
  0% 32705/kworker/0:1: 0% user + 0% kernel
12% TOTAL: 3.2% user + 9.4% kernel + 0% iowait

CertificateException: No name matching ssl.someUrl.de found

In case, it helps someone:

Use case: i am using a self-signed certificate for my development on localhost.

Error: Caused by: java.security.cert.CertificateException: No name matching localhost found

Solution: When you generate your self-signed certicate, make sure you answer this question like that(See Bruno's answer for the why):

What is your first and last name?
  [Unknown]:  localhost



As a bonus, here are my steps:
1. Generate self-signed certificate:

keytool -genkeypair -alias netty -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 4000
Enter keystore password: ***
Re-enter new password: ***
What is your first and last name?
  [Unknown]:  localhost
...

2. Copy the certificate in src/main/resources(if necessary)

3. Update the cacerts
keytool -v -importkeystore -srckeystore keystore.p12 -srcstoretype pkcs12 -destkeystore "%JAVA_HOME%\jre\lib\security\cacerts" -deststoretype jks

4. Update your config(in my case application.properties):

server.port=8443
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=jumping_monkey
server.ssl.key-store-type=pkcs12
server.ssl.key-alias=netty



Cheers

How do I parse JSON from a Java HTTPResponse?

Jackson appears to support some amount of JSON parsing straight from an InputStream. My understanding is that it runs on Android and is fairly quick. On the other hand, it is an extra JAR to include with your app, increasing download and on-flash size.

Android Reading from an Input stream efficiently

    byte[] buffer = new byte[1024];  // buffer store for the stream
    int bytes; // bytes returned from read()

    // Keep listening to the InputStream until an exception occurs
    while (true) {
        try {
            // Read from the InputStream
            bytes = mmInStream.read(buffer);

            String TOKEN_ = new String(buffer, "UTF-8");

            String xx = TOKEN_.substring(0, bytes);

Why do I get the "Unhandled exception type IOException"?

add "throws IOException" to your method like this:

public static void main(String args[]) throws  IOException{

        FileReader reader=new FileReader("db.properties");

        Properties p=new Properties();
        p.load(reader);


    }

How to read input with multiple lines in Java

I finally got it, submited it 13 times rejected for whatever reasons, 14th "the judge" accepted my answer, here it is :

import java.io.BufferedInputStream;
import java.util.Scanner;

public class HashmatWarrior {

    public static void main(String args[]) {
        Scanner stdin = new Scanner(new BufferedInputStream(System.in));
        while (stdin.hasNext()) {
            System.out.println(Math.abs(stdin.nextLong() - stdin.nextLong()));
        }
    }
}

Simple Java Client/Server Program

My try to do client socket program

server reads file and print it to console and copies it to output file

Server Program:

package SocketProgramming.copy;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerRecieveFile {
    public static void main(String[] args) throws IOException {
        // TODO Auto-enerated method stub
        int filesize = 1022386;
        int bytesRead;
        int currentTot;
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        ServerSocket serverSocket = new ServerSocket(15123);
        while (true) {
            Socket socket = serverSocket.accept();
            byte[] bytearray = new byte[filesize];
            InputStream is = socket.getInputStream();
            File copyFileName = new File("C:/Users/Username/Desktop/Output_file.txt");
            FileOutputStream fos = new FileOutputStream(copyFileName);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(bytearray, 0, bytearray.length);
            currentTot = bytesRead;
            do {
                bytesRead = is.read(bytearray, currentTot,
                        (bytearray.length - currentTot));
                if (bytesRead >= 0)
                    currentTot += bytesRead;
            } while (bytesRead > -1);
            bos.write(bytearray, 0, currentTot);
            bos.flush();
            bos.close();
            socket.close();
        }
    }
}

Client program:

package SocketProgramming.copy;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientSendFile {
    public static void main(String[] args) throws UnknownHostException,
            IOException {
        // final String FILE_NAME="C:/Users/Username/Desktop/Input_file.txt";
        final String FILE_NAME = "C:/Users/Username/Desktop/Input_file.txt";
        ServerSocket s = new ServerSocket(0);
        int port = s.getLocalPort();
        Socket socket = new Socket(InetAddress.getLocalHost(), 15123);
        System.out.println("Accepted connection : " + socket);
        File transferFile = new File(FILE_NAME);
        byte[] bytearray = new byte[(int) transferFile.length()];
        FileInputStream fin = new FileInputStream(transferFile);
        BufferedInputStream bin = new BufferedInputStream(fin);
        bin.read(bytearray, 0, bytearray.length);
        OutputStream os = socket.getOutputStream();
        System.out.println("Sending Files...");

        os.write(bytearray, 0, bytearray.length);

        BufferedReader r = new BufferedReader(new FileReader(FILE_NAME));
        String as = "", line = null;
        while ((line = r.readLine()) != null) {
            as += line + "\n";
            // as += line;

        }
        System.out.print("Input File contains following data: " + as);
        os.flush();
        fin.close();
        bin.close();
        os.close();
        socket.close();

        System.out.println("File transfer complete");
    }
}

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

I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:

// HTTP POST request
private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:

static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.

The encode function translates the string into application/x-www-form-urlencoded.

Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.

For this particular scenario, the following should work:

String data = "product[title]=" + title +
                "&product[content]=" + content + 
                "&product[price]=" + price.toString() +
                "&tags=" + tags;

Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.

How to write console output to a txt file

In addition to the several programatic approaches discussed, another option is to redirect standard output from the shell. Here are several Unix and DOS examples.

How to read a single char from the console in Java (as the user types it)?

There is no portable way to read raw characters from a Java console.

Some platform-dependent workarounds have been presented above. But to be really portable, you'd have to abandon console mode and use a windowing mode, e.g. AWT or Swing.

read file in classpath

Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.

In your class, do something like this:

public void setSqlResource(Resource sqlResource) {
    this.sqlResource = sqlResource;
}

And then in your application context file, in the bean definition, just set a property:

<bean id="someBean" class="...">
    <property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>

And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.

You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.

How to Consume WCF Service with Android

Another option might be to avoid WCF all-together and just use a .NET HttpHandler. The HttpHandler can grab the query-string variables from your GET and just write back a response to the Java code.

Java : How to determine the correct charset encoding of a stream

You cannot determine the encoding of a arbitrary byte stream. This is the nature of encodings. A encoding means a mapping between a byte value and its representation. So every encoding "could" be the right.

The getEncoding() method will return the encoding which was set up (read the JavaDoc) for the stream. It will not guess the encoding for you.

Some streams tell you which encoding was used to create them: XML, HTML. But not an arbitrary byte stream.

Anyway, you could try to guess an encoding on your own if you have to. Every language has a common frequency for every char. In English the char e appears very often but ê will appear very very seldom. In a ISO-8859-1 stream there are usually no 0x00 chars. But a UTF-16 stream has a lot of them.

Or: you could ask the user. I've already seen applications which present you a snippet of the file in different encodings and ask you to select the "correct" one.

How do I turn a String into a InputStreamReader in java?

I also found the apache commons IOUtils class , so :

InputStreamReader isr = new InputStreamReader(IOUtils.toInputStream(myString));

java.net.SocketException: Software caused connection abort: recv failed

Try adding 'autoReconnect=true' to the jdbc connection string

Today`s date in an excel macro

Here's an example that puts the Now() value in column A.

Sub move()
    Dim i As Integer
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim nextRow As Long
    Dim copyRange As Range
    Dim destRange As Range

    Application.ScreenUpdating = False

        Set sh1 = ActiveWorkbook.Worksheets("Sheet1")
        Set sh2 = ActiveWorkbook.Worksheets("Sheet2")
        Set copyRange = sh1.Range("A1:A5")

        i = Application.WorksheetFunction.CountA(sh2.Range("B:B")) + 4

        Set destRange = sh2.Range("B" & i)

        destRange.Resize(1, copyRange.Rows.Count).Value = Application.Transpose(copyRange.Value)
        destRange.Offset(0, -1).Value = Format(Now(), "MMM-DD-YYYY")

        copyRange.Clear

    Application.ScreenUpdating = True

End Sub

There are better ways of getting the last row in column B than using a While loop, plenty of examples around here. Some are better than others but depend on what you're doing and what your worksheet structure looks like. I used one here which assumes that column B is ALL empty except the rows/records you're moving. If that's not the case, or if B1:B3 have some values in them, you'd need to modify or use another method. Or you could just use your loop, but I'd search for alternatives :)

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

jQuery: how to find first visible input/select/textarea excluding buttons?

This is my summary of the above and works perfectly for me. Thanks for the info!

<script language='javascript' type='text/javascript'>
    $(document).ready(function () {
        var firstInput = $('form').find('input[type=text],input[type=password],input[type=radio],input[type=checkbox],textarea,select').filter(':visible:first');
        if (firstInput != null) {
            firstInput.focus();
        }
    });
</script>

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I have faced same problem since I have updated the latest react version. Solved like below.

My code was

async componentDidMount() {
  const { default: Component } = await importComponent();
  Nprogress.done();
  this.setState({
    component: <Component {...this.props} />
  });
}

Changed to

componentWillUnmount() {
  this.mounted = false;
}
async componentDidMount() {
  this.mounted = true;
  const { default: Component } = await importComponent();
  if (this.mounted) {
    this.setState({
      component: <Component {...this.props} />
    });
  }
}

Left Join without duplicate rows from left table

You can do this using generic SQL with group by:

SELECT C.Content_ID, C.Content_Title, MAX(M.Media_Id)
FROM tbl_Contents C LEFT JOIN
     tbl_Media M
     ON M.Content_Id = C.Content_Id 
GROUP BY C.Content_ID, C.Content_Title
ORDER BY MAX(C.Content_DatePublished) ASC;

Or with a correlated subquery:

SELECT C.Content_ID, C.Contt_Title,
       (SELECT M.Media_Id
        FROM tbl_Media M
        WHERE M.Content_Id = C.Content_Id
        ORDER BY M.MEDIA_ID DESC
        LIMIT 1
       ) as Media_Id
FROM tbl_Contents C 
ORDER BY C.Content_DatePublished ASC;

Of course, the syntax for limit 1 varies between databases. Could be top. Or rownum = 1. Or fetch first 1 rows. Or something like that.

Escape Character in SQL Server

You could use the **\** character before the value you want to escape e.g insert into msglog(recipient) values('Mr. O\'riely') select * from msglog where recipient = 'Mr. O\'riely'

Sqlite in chrome

Chrome supports WebDatabase API (which is powered by sqlite), but looks like W3C stopped its development.

Most recent previous business day in Python

This will give a generator of working days, of course without holidays, stop is datetime.datetime object. If you need holidays just make additional argument with list of holidays and check with 'IFology' ;-)

def workingdays(stop, start=datetime.date.today()):
    while start != stop:
        if start.weekday() < 5:
            yield start
        start += datetime.timedelta(1)

Later on you can count them like

workdays = workingdays(datetime.datetime(2015, 8, 8))
len(list(workdays))

How to add jQuery code into HTML Page

Make sure that you embedd the jQuery library into your page by adding the below shown line into your <head> block:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Writing an mp4 video using python opencv

just change the codec to "DIVX". This codec works with all formats.

fourcc = cv2.VideoWriter_fourcc(*'DIVX')

i hope this works for you!

Difference between Pragma and Cache-Control headers?

There is no difference, except that Pragma is only defined as applicable to the requests by the client, whereas Cache-Control may be used by both the requests of the clients and the replies of the servers.

So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:

HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.

  Note: because the meaning of "Pragma: no-cache as a response
  header field is not actually specified, it does not provide a
  reliable replacement for "Cache-Control: no-cache" in a response

The way I would read the above:

  • if you're writing a client and need no-cache:

    • just use Pragma: no-cache in your requests, since you may not know if Cache-Control is supported by the server;
    • but in replies, to decide on whether to cache, check for Cache-Control
  • if you're writing a server:

    • in parsing requests from the clients, check for Cache-Control; if not found, check for Pragma: no-cache, and execute the Cache-Control: no-cache logic;
    • in replies, provide Cache-Control.

Of course, reality might be different from what's written or implied in the RFC!

Importing from a relative path in Python

Funny enough, a same problem I just met, and I get this work in following way:

combining with linux command ln , we can make thing a lot simper:

1. cd Proj/Client
2. ln -s ../Common ./

3. cd Proj/Server
4. ln -s ../Common ./

And, now if you want to import some_stuff from file: Proj/Common/Common.py into your file: Proj/Client/Client.py, just like this:

# in Proj/Client/Client.py
from Common.Common import some_stuff

And, the same applies to Proj/Server, Also works for setup.py process, a same question discussed here, hope it helps !

How to open a Bootstrap modal window using jQuery?

Most often, when $('#myModal').modal('show'); doesn't work, it's caused by having included jQuery twice. Including jQuery 2 times makes modals not to work.

Remove one of the links to make it work again.

Furthermore, some plugins cause errors too, in this case add

jQuery.noConflict(); 
$('#myModal').modal('show'); 

See :hover state in Chrome Developer Tools

Changing to hover status in Chrome is pretty easy, just follow these steps below:

1) Right click in your page and select inspect

enter image description here

2) Select the element you like to have inspect in the DOM

enter image description here

3) Select the pin icon enter image description here (Toggle Element State)

4) Then tick the hover

Now you can see the hover state of the selected DOM in the browser!

SQL Server Installation - What is the Installation Media Folder?

For the SQL Server 2019 (Express Edition) installation, I did the following:

  1. Open SQL Server Installation Center
  2. Click on Installation
  3. Click on New SQL Server stand-alone installation or add features to an existing installation
  4. Browse to C:\SQL2019\Express_ENU and click OK

Image encryption/decryption using AES256 symmetric block ciphers

Old question but I upgrade the answers supporting Android prior and post 4.2 and considering all recent changes according to Android developers blog

Plus I leave a working example on my github repo.

import java.nio.charset.Charset;
import java.security.AlgorithmParameters;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;


/*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will Google be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, as long as the origin is not misrepresented.
* 
* @author: Ricardo Champa
* 
*/

public class MyCipher {

    private final static String ALGORITHM = "AES";
    private String mySecret;

    public MyCipher(String mySecret){
        this.mySecret = mySecret;
    }

    public MyCipherData encryptUTF8(String data){
        try{
            byte[] bytes = data.toString().getBytes("utf-8");
            byte[] bytesBase64 = Base64.encodeBase64(bytes);
            return encrypt(bytesBase64);
        }
        catch(Exception e){
            MyLogs.show(e.getMessage());
            return null;
        }

    }

    public String decryptUTF8(byte[] encryptedData, IvParameterSpec iv){
        try {
            byte[] decryptedData = decrypt(encryptedData, iv);
            byte[] decodedBytes = Base64.decodeBase64(decryptedData);
            String restored_data = new String(decodedBytes, Charset.forName("UTF8"));
            return restored_data;
        } catch (Exception e) {
            MyLogs.show(e.getMessage());;
            return null;
        }
    }

    //AES
    private MyCipherData encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        //solved using PRNGFixes class
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] data = cipher.doFinal(clear);

        AlgorithmParameters params = cipher.getParameters();
        byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
        return new MyCipherData(data, iv);
    }

    private byte[] decrypt(byte[] raw, byte[] encrypted, IvParameterSpec iv) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

    private byte[] getKey() throws Exception{
        byte[] keyStart = this.mySecret.getBytes("utf-8");
        KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);

        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
        //      if (android.os.Build.VERSION.SDK_INT >= 17) {
        //          sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
        //      } else {
        //          sr = SecureRandom.getInstance("SHA1PRNG");
        //      }
        sr.setSeed(keyStart);
        kgen.init(128, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();
        byte[] key = skey.getEncoded();
        return key;

    }
    ////////////////////////////////////////////////////////////
    private MyCipherData encrypt(byte[] data) throws Exception{
        return encrypt(getKey(),data);
    }
    private byte[] decrypt(byte[] encryptedData, IvParameterSpec iv) throws Exception{
        return decrypt(getKey(),encryptedData, iv);
    }
}

Howto? Parameters and LIKE statement SQL

Your visual basic code would look something like this:

Dim cmd as New SqlCommand("SELECT * FROM compliance_corner WHERE (body LIKE '%' + @query + '%') OR (title LIKE '%' + @query + '%')")

cmd.Parameters.Add("@query", searchString)

Javascript to stop HTML5 video playback on modal window close

I searched all over the internet for an answer for this question. none worked for me except this code. Guaranteed. It work perfectly.

$('body').on('hidden.bs.modal', '.modal', function () {
$('video').trigger('pause');
});

How to sort an array of objects with jquery or javascript

the sort method contains an optional argument to pass a custom compare function.

Assuming you wanted an array of arrays:

var arr = [[3, "Mike", 20],[5, "Alex", 15]];

function compareName(a, b)
{

  if (a[1] < b[1]) return -1;
  if (a[1] > b[1]) return 1;
  return 0;
}
arr.sort(compareName);

Otherwise if you wanted an array of objects, you could do:

function compareName(a, b)
{

  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return 0;
}

Using Gulp to Concatenate and Uglify files

It turns out that I needed to use gulp-rename and also output the concatenated file first before 'uglification'. Here's the code:

var gulp = require('gulp'),
    gp_concat = require('gulp-concat'),
    gp_rename = require('gulp-rename'),
    gp_uglify = require('gulp-uglify');

gulp.task('js-fef', function(){
    return gulp.src(['file1.js', 'file2.js', 'file3.js'])
        .pipe(gp_concat('concat.js'))
        .pipe(gulp.dest('dist'))
        .pipe(gp_rename('uglify.js'))
        .pipe(gp_uglify())
        .pipe(gulp.dest('dist'));
});

gulp.task('default', ['js-fef'], function(){});

Coming from grunt it was a little confusing at first but it makes sense now. I hope it helps the gulp noobs.

And, if you need sourcemaps, here's the updated code:

var gulp = require('gulp'),
    gp_concat = require('gulp-concat'),
    gp_rename = require('gulp-rename'),
    gp_uglify = require('gulp-uglify'),
    gp_sourcemaps = require('gulp-sourcemaps');

gulp.task('js-fef', function(){
    return gulp.src(['file1.js', 'file2.js', 'file3.js'])
        .pipe(gp_sourcemaps.init())
        .pipe(gp_concat('concat.js'))
        .pipe(gulp.dest('dist'))
        .pipe(gp_rename('uglify.js'))
        .pipe(gp_uglify())
        .pipe(gp_sourcemaps.write('./'))
        .pipe(gulp.dest('dist'));
});

gulp.task('default', ['js-fef'], function(){});

See gulp-sourcemaps for more on options and configuration.

SQL Case Sensitive String Compare

You can also convert that attribute as case sensitive using this syntax :

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CS_AS

Now your search will be case sensitive.

If you want to make that column case insensitive again, then use

ALTER TABLE Table1
ALTER COLUMN Column1 VARCHAR(200)
COLLATE SQL_Latin1_General_CP1_CI_AS

How to apply multiple transforms in CSS?

I'm adding this answer not because it's likely to be helpful but just because it's true.

In addition to using the existing answers explaining how to make more than one translation by chaining them, you can also construct the 4x4 matrix yourself

I grabbed the following image from some random site I found while googling which shows rotational matrices:

Rotation around x axis: Rotation around x axis
Rotation around y axis: Rotation around y axis
Rotation around z axis: Rotation around z axis

I couldn't find a good example of translation, so assuming I remember/understand it right, translation:

[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[x y z 1]

See more at the Wikipedia article on transformation as well as the Pragamatic CSS3 tutorial which explains it rather well. Another guide I found which explains arbitrary rotation matrices is Egon Rath's notes on matrices

Matrix multiplication works between these 4x4 matrices of course, so to perform a rotation followed by a translation, you make the appropriate rotation matrix and multiply it by the translation matrix.

This can give you a bit more freedom to get it just right, and will also make it pretty much completely impossible for anyone to understand what it's doing, including you in five minutes.

But, you know, it works.

Edit: I just realized that I missed mentioning probably the most important and practical use of this, which is to incrementally create complex 3D transformations via JavaScript, where things will make a bit more sense.

How to browse for a file in java swing library?

I ended up using this quick piece of code that did exactly what I needed:

final JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);

try {
    // Open an input stream
    Scanner reader = new Scanner(fc.getSelectedFile());
}

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

I fixed this issue by adding following code in my file.

@Component
@Scope(value = "session",  proxyMode = ScopedProxyMode.TARGET_CLASS)

XML configuration -

<listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener 
        </listener-class>
</listener>

Above we can do using Java configuration -

@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}

How to add a RequestContextListener with no-xml configuration?

I am using spring version 5.1.4.RELEASE and no need to add below changes in pom.

<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.2.10</version>
</dependency>

How to stop a thread created by implementing runnable interface?

The simplest way is to interrupt() it, which will cause Thread.currentThread().isInterrupted() to return true, and may also throw an InterruptedException under certain circumstances where the Thread is waiting, for example Thread.sleep(), otherThread.join(), object.wait() etc.

Inside the run() method you would need catch that exception and/or regularly check the Thread.currentThread().isInterrupted() value and do something (for example, break out).

Note: Although Thread.interrupted() seems the same as isInterrupted(), it has a nasty side effect: Calling interrupted() clears the interrupted flag, whereas calling isInterrupted() does not.

Other non-interrupting methods involve the use of "stop" (volatile) flags that the running Thread monitors.

How to install Laravel's Artisan?

You just have to read the laravel installation page:

  1. Install Composer if not already installed
  2. Open a command line and do:
composer global require "laravel/installer"

Inside your htdocs or www directory, use either:

laravel new appName

(this can lead to an error on windows computers while using latest Laravel (1.3.2)) or:

composer create-project --prefer-dist laravel/laravel appName

(this works also on windows) to create a project called "appName".

To use "php artisan xyz" you have to be inside your project root! as artisan is a file php is going to use... Simple as that ;)

How do I create a pause/wait function using Qt?

@kshark27's answer didn't work for me for some reason (because I use Qt 5.7?) so I ended up doing this:

while (someCondition) {

   // do something

   QApplication::processEvents();
   QThread::sleep(1); // 1 second

};

If this is done in the GUI thread, it obviously introduces a 1 second GUI lag before responding to user events. But if you can live with it, this solution is probably an easiest to implement and even Qt endorses it in their Threading Basics article (see When to Use Alternatives to Threads section).

String Comparison in Java

Java lexicographically order:

  1. Numbers -before-
  2. Uppercase -before-
  3. Lowercase

Odd as this seems, it is true...
I have had to write comparator chains to be able to change the default behavior.
Play around with the following snippet with better examples of input strings to verify the order (you will need JSE 8):

import java.util.ArrayList;

public class HelloLambda {

public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add("Kambiz");
    names.add("kambiz");
    names.add("k1ambiz");
    names.add("1Bmbiza");
    names.add("Samantha");
    names.add("Jakey");
    names.add("Lesley");
    names.add("Hayley");
    names.add("Benjamin");
    names.add("Anthony");

    names.stream().
        filter(e -> e.contains("a")).
        sorted().
        forEach(System.out::println);
}
}

Result

1Bmbiza
Benjamin
Hayley
Jakey
Kambiz
Samantha
k1ambiz
kambiz

Please note this is answer is Locale specific.
Please note that I am filtering for a name containing the lowercase letter a.

Why am I getting a "401 Unauthorized" error in Maven?

As stated in @John's answer, the fact that there is already a 0.1.2-SNAPSHOT, interfered with my new non-SNAPSHOT version 0.1.2. Since the 401 Unauthorized error is nebulous and unhelpful--and is normally associated to user/pass problems--it's no surprise that I was unable to figure this out on my own.

Changing the version to 0.1.3 brings me back to my original error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-install-plugin:2.4:install (default-install) on project xbnjava: Failed to install artifact com.github.aliteralmind:xbnjava:jar:0.1.3: R:\jeffy\programming\build\xbnjava-0.1.3\download\xbnjava-0.1.3-all.jar (The system cannot find the path specified) -> [Help 1].

A sonatype support person also recommended that I remove the <parent> block from my POM (it's only there because it's in the one from ez-vcard, which is what I started with) and replace my <distributionManagement> block with

<distributionManagement>
  <snapshotRepository>
    <id>ossrh</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
  </snapshotRepository>
  <repository>
    <id>ossrh</id>
    <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
  </repository>
</distributionManagement>
and then make sure that lines up with what's in your settings.xml:
<settings>
  <servers>
    <server>
      <id>ossrh</id>
      <username>your-jira-id</username>
      <password>your-jira-pwd</password>
    </server>
  </servers>
</settings>

After doing this, running mvn deploy actually uploaded one of my jars for the very first time!!!

Output:

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building XBN-Java 0.1.3
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- build-helper-maven-plugin:1.8:attach-artifact (attach-artifacts) @ xbnjava ---
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ xbnjava ---
[INFO] Installing R:\jeffy\programming\sandbox\z__for_git_commit_only\xbnjava\pom.xml to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.3\xbnjava-0.1.3.pom
[INFO] Installing R:\jeffy\programming\build\xbnjava-0.1.3\download\xbnjava-0.1.3.jar to C:\Users\jeffy\.m2\repository\com\github\aliteralmind\xbnjava\0.1.3\xbnjava-0.1.3.jar
[INFO]
[INFO] --- maven-deploy-plugin:2.7:deploy (default-deploy) @ xbnjava ---
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.pom
2/6 KB
4/6 KB
6/6 KB

Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.pom (6 KB at 4.6 KB/sec)
Downloading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml
310/310 B

Downloaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (310 B at 1.6 KB/sec)
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml
310/310 B

Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/maven-metadata.xml (310 B at 1.4 KB/sec)
Uploading: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.jar
2/630 KB
4/630 KB
6/630 KB
8/630 KB
10/630 KB
12/630 KB
14/630 KB
...
618/630 KB
620/630 KB
622/630 KB
624/630 KB
626/630 KB
628/630 KB
630/630 KB

(Success portion:)

Uploaded: https://oss.sonatype.org/service/local/staging/deploy/maven2/com/github/aliteralmind/xbnjava/0.1.3/xbnjava-0.1.3.jar (630 KB at 474.7 KB/sec)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.632 s
[INFO] Finished at: 2014-07-18T15:09:25-04:00
[INFO] Final Memory: 6M/19M
[INFO] ------------------------------------------------------------------------

Here's the full updated POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.github.aliteralmind</groupId>
  <artifactId>xbnjava</artifactId>
  <packaging>pom</packaging>
  <version>0.1.3</version>
  <name>XBN-Java</name>
  <url>https://github.com/aliteralmind/xbnjava</url>
  <inceptionYear>2014</inceptionYear>
  <organization>
     <name>Jeff Epstein</name>
  </organization>
  <description>XBN-Java is a collection of generically-useful backend (server side, non-GUI) programming utilities, featuring RegexReplacer and FilteredLineIterator. XBN-Java is the foundation of Codelet (http://codelet.aliteralmind.com).</description>

  <licenses>
     <license>
        <name>Lesser General Public License (LGPL) version 3.0</name>
        <url>https://www.gnu.org/licenses/lgpl-3.0.txt</url>
     </license>
     <license>
        <name>Apache Software License (ASL) version 2.0</name>
        <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
     </license>
  </licenses>

  <developers>
     <developer>
        <name>Jeff Epstein</name>
        <email>[email protected]</email>
        <roles>
           <role>Lead Developer</role>
        </roles>
     </developer>
  </developers>

  <issueManagement>
     <system>GitHub Issue Tracker</system>
     <url>https://github.com/aliteralmind/xbnjava/issues</url>
  </issueManagement>

  <distributionManagement>
    <snapshotRepository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </snapshotRepository>
    <repository>
      <id>ossrh</id>
      <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
    </repository>
  </distributionManagement>

  <scm>
     <connection>scm:git:[email protected]:aliteralmind/xbnjava.git</connection>
     <url>scm:git:[email protected]:aliteralmind/xbnjava.git</url>
     <developerConnection>scm:git:[email protected]:aliteralmind/xbnjava.git</developerConnection>
  </scm>

  <properties>
     <java.version>1.7</java.version>
     <jarprefix>R:\jeffy\programming\build\/${project.artifactId}-${project.version}/download/${project.artifactId}-${project.version}</jarprefix>
  </properties>
  <build>
     <plugins>
        <plugin>
           <groupId>org.codehaus.mojo</groupId>
           <artifactId>build-helper-maven-plugin</artifactId>
           <version>1.8</version>
           <executions>
              <execution>
                 <id>attach-artifacts</id>
                 <phase>package</phase>
                 <goals>
                    <goal>attach-artifact</goal>
                 </goals>
                 <configuration>
                    <artifacts>
                       <artifact>
                          <file>${jarprefix}.jar</file>
                          <type>jar</type>
                       </artifact>
                    </artifacts>
                 </configuration>
              </execution>
           </executions>
        </plugin>
     </plugins>
  </build>

  <profiles>
     <!--
     This profile will sign the JAR file, sources file, and javadocs file using the GPG key on the local machine.
     See: https://docs.sonatype.org/display/Repository/How+To+Generate+PGP+Signatures+With+Maven
     -->
     <profile>
        <id>release-sign-artifacts</id>
        <activation>
           <property>
              <name>release</name>
              <value>true</value>
           </property>
        </activation>
     </profile>
  </profiles>
</project>

That's one big Maven problem out of the way. Only 627 more to go.

Put request with simple string as request body

Another simple solution is to surround the content variable in your given code with braces like this:

 let content = 'Hello world' 
 axios.put(url, {content}).then(response => {
    resolve(response.data.content)
  }, response => {
    this.handleEditError(response)
  })

Caveat: But this will not send it as string; it will wrap it in a json body that will look like this: {content: "Hello world"}

Connect to mysql on Amazon EC2 from a remote server

as mentioned in the responses above, it could be related to AWS security groups, and other things. but if you created a user and gave it remote access '%' and still getting this error, check your mysql config file, on debian, you can find it here: /etc/mysql/my.cnf and find the line:

bind-address            = 127.0.0.1

and change it to:

bind-address            = 0.0.0.0

and restart mysql.

on debian/ubuntu:

/etc/init.d/mysql restart

I hope this works for you.

Nginx: stat() failed (13: permission denied)

You can also add which user will run the nginx. In the nginx.conf file, make the following changes:

user root;

You can add the above line as the first line in your nginx conf. You can write the name of any user who has the permission to write in that directory.

How to search contents of multiple pdf files?

There is another utility called ripgrep-all, which is based on ripgrep.

It can handle more than just PDF documents, like Office documents and movies, and the author claims it is faster than pdfgrep.

Command syntax for recursively searching the current directory, and the second one limits to PDF files only:

rga 'pattern' .
rga --type pdf 'pattern' .

Download and open PDF file using Ajax

The following code worked for me

//Parameter to be passed
var data = 'reportid=R3823&isSQL=1&filter=[]';
var xhr = new XMLHttpRequest();
xhr.open("POST", "Reporting.jsp"); //url.It can pdf file path
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.responseType = "blob";
xhr.onload = function () {
    if (this.status === 200) {
        var blob = new Blob([xhr.response]);
        const url = window.URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = url;
        a.download = 'myFile.pdf';
        a.click();
        setTimeout(function () {
            // For Firefox it is necessary to delay revoking the ObjectURL
            window.URL.revokeObjectURL(data)
                , 100
        })
    }
};
xhr.send(data);

How to pass in password to pg_dump?

You can pass a password into pg_dump directly by using the following:

pg_dump "host=localhost port=5432 dbname=mydb user=myuser password=mypass" > mydb_export.sql

In vb.net, how to get the column names from a datatable

Look at

For Each c as DataColumn in dt.Columns
  '... = c.ColumnName
Next

or:

dt.GetDataTableSchema(...)

How to see indexes for a database or table in MySQL?

we can directly see the indexes on to the table if we know the index name with below :

select * from all_indexes where index_name= 'your index'

Working with UTF-8 encoding in Python source

Do not forget to verify if your text editor encodes properly your code in UTF-8.

Otherwise, you may have invisible characters that are not interpreted as UTF-8.

Media Queries: How to target desktop, tablet, and mobile?

Don't target specific devices or sizes!

The general wisdom is not to target specific devices or sizes, but to reframe the term 'breakpoint':

  • develop the site for mobile first using percentages or ems, not pixels,
  • then try it in a larger viewport and note where it begins to fail,
  • redesign the layout and add a CSS media query just to handle the broken parts,
  • repeat the process until you reach the next breakpoint.

You can use responsivepx.com to find the 'natural' breakpoints, as in 'breakpoints are dead' by Marc Drummond.

Use natural breakpoints

The 'breakpoints' then become the actual point at which your mobile design begins to 'break' i.e. cease to be usable or visually pleasing. Once you have a good working mobile site, without media queries, you can stop being concerned about specific sizes and simply add media queries that handle successively larger viewports.

If you're not trying to pin design to exact screen size, this approach works by removing the need to target specific devices. The integrity of the design itself at each breakpoint ensures that it will hold up at any size. In other words, if a menu/content section/whatever stops being usable at a certain size, design a breakpoint for that size, not for a specific device size.

See Lyza Gardner's post on behavioral breakpoints, and also Zeldman's post about Ethan Marcotte and how responsive web design evolved from the initial idea.

Use semantic markup

Further, the simpler and more semantic the DOM structure with nav, header, main, section, footer etc. (avoiding abominations like div class="header" with nested inner div tags) the easier it will be to engineer responsiveness, especially avoiding floats by using CSS Grid Layout (Sarah Drasner's grid generator is a great tool for this) and flexbox for arranging and re-ordering according to your RWD design plan.

Fastest method to replace all instances of a character in a string

var mystring = 'This is a string';
var newString = mystring.replace(/i/g, "a");

newString now is 'Thas as a strang'

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

The ngRoute module is no longer part of the core angular.js file. If you are continuing to use $routeProvider then you will now need to include angular-route.js in your HTML:

<script src="angular.js">
<script src="angular-route.js">

API Reference

You also have to add ngRoute as a dependency for your application:

var app = angular.module('MyApp', ['ngRoute', ...]);

If instead you are planning on using angular-ui-router or the like then just remove the $routeProvider dependency from your module .config() and substitute it with the relevant provider of choice (e.g. $stateProvider). You would then use the ui.router dependency:

var app = angular.module('MyApp', ['ui.router', ...]);

How to convert <font size="10"> to px?

This is really old, but <font size="10"> would be about <p style= "font-size:55px">

Android ViewPager with bottom dots

My handmade solution:

In the layout:

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dots"
        />

And in the Activity

private final static int NUM_PAGES = 5;
private ViewPager mViewPager;
private List<ImageView> dots;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...
    addDots();
}

public void addDots() {
    dots = new ArrayList<>();
    LinearLayout dotsLayout = (LinearLayout)findViewById(R.id.dots);

    for(int i = 0; i < NUM_PAGES; i++) {
        ImageView dot = new ImageView(this);
        dot.setImageDrawable(getResources().getDrawable(R.drawable.pager_dot_not_selected));

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        dotsLayout.addView(dot, params);

        dots.add(dot);
    }

    mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            selectDot(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });
}

public void selectDot(int idx) {
    Resources res = getResources();
    for(int i = 0; i < NUM_PAGES; i++) {
        int drawableId = (i==idx)?(R.drawable.pager_dot_selected):(R.drawable.pager_dot_not_selected);
        Drawable drawable = res.getDrawable(drawableId);
        dots.get(i).setImageDrawable(drawable);
    }
}

HTML5 Audio Looping

You could try a setInterval, if you know the exact length of the sound. You could have the setInterval play the sound every x seconds. X would be the length of your sound.

VBA error 1004 - select method of range class failed

You have to select the sheet before you can select the range.

I've simplified the example to isolate the problem. Try this:

Option Explicit


Sub RangeError()

    Dim sourceBook As Workbook
    Dim sourceSheet As Worksheet
    Dim sourceSheetSum As Worksheet

    Set sourceBook = ActiveWorkbook
    Set sourceSheet = sourceBook.Sheets("Sheet1")
    Set sourceSheetSum = sourceBook.Sheets("Sheet2")

    sourceSheetSum.Select

    sourceSheetSum.Range("C3").Select           'THIS IS THE PROBLEM LINE

End Sub

Replace Sheet1 and Sheet2 with your sheet names.

IMPORTANT NOTE: Using Variants is dangerous and can lead to difficult-to-kill bugs. Use them only if you have a very specific reason for doing so.

How to get the index of an element in an IEnumerable?

An alternative to finding the index after the fact is to wrap the Enumerable, somewhat similar to using the Linq GroupBy() method.

public static class IndexedEnumerable
{
    public static IndexedEnumerable<T> ToIndexed<T>(this IEnumerable<T> items)
    {
        return IndexedEnumerable<T>.Create(items);
    }
}

public class IndexedEnumerable<T> : IEnumerable<IndexedEnumerable<T>.IndexedItem>
{
    private readonly IEnumerable<IndexedItem> _items;

    public IndexedEnumerable(IEnumerable<IndexedItem> items)
    {
        _items = items;
    }

    public class IndexedItem
    {
        public IndexedItem(int index, T value)
        {
            Index = index;
            Value = value;
        }

        public T Value { get; private set; }
        public int Index { get; private set; }
    }

    public static IndexedEnumerable<T> Create(IEnumerable<T> items)
    {
        return new IndexedEnumerable<T>(items.Select((item, index) => new IndexedItem(index, item)));
    }

    public IEnumerator<IndexedItem> GetEnumerator()
    {
        return _items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Which gives a use case of:

var items = new[] {1, 2, 3};
var indexedItems = items.ToIndexed();
foreach (var item in indexedItems)
{
    Console.WriteLine("items[{0}] = {1}", item.Index, item.Value);
}

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

Cannot read property 'length' of null (javascript)

From the code that you have provided, not knowing the language that you are programming in. The variable capital is null. When you are trying to read the property length, the system cant as it is trying to deference a null variable. You need to define capital.

Math.random() explanation

The Random class of Java located in the java.util package will serve your purpose better. It has some nextInt() methods that return an integer. The one taking an int argument will generate a number between 0 and that int, the latter not inclusive.

Are there any standard exit status codes in Linux?

Programs return a 16 bit exit code. If the program was killed with a signal then the high order byte contains the signal used, otherwise the low order byte is the exit status returned by the programmer.

How that exit code is assigned to the status variable $? is then up to the shell. Bash keeps the lower 7 bits of the status and then uses 128 + (signal nr) for indicating a signal.

The only "standard" convention for programs is 0 for success, non-zero for error. Another convention used is to return errno on error.

How can I remove a commit on GitHub?

It is not very good to re-write the history. If we use git revert <commit_id>, it creates a clean reverse-commit of the said commit id.

This way, the history is not re-written, instead, everyone knows that there has been a revert.

Resize UIImage by keeping Aspect ratio and width

Ryan's Solution @Ryan in swift code

use:

 func imageWithSize(image: UIImage,size: CGSize)->UIImage{
    if UIScreen.mainScreen().respondsToSelector("scale"){
        UIGraphicsBeginImageContextWithOptions(size,false,UIScreen.mainScreen().scale);
    }
    else
    {
         UIGraphicsBeginImageContext(size);
    }

    image.drawInRect(CGRectMake(0, 0, size.width, size.height));
    var newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

//Summon this function VVV
func resizeImageWithAspect(image: UIImage,scaledToMaxWidth width:CGFloat,maxHeight height :CGFloat)->UIImage
{
    let oldWidth = image.size.width;
    let oldHeight = image.size.height;

    let scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight;

    let newHeight = oldHeight * scaleFactor;
    let newWidth = oldWidth * scaleFactor;
    let newSize = CGSizeMake(newWidth, newHeight);

    return imageWithSize(image, size: newSize);
}

How to find the sum of an array of numbers

Considering you have the array

const arr = [1, 2, 3, 4];

For me, the most intuitive way is using a for-in

let sum = 0;
for(var value in arr) {
    sum += arr[value];
}

console.log('Array:', arr);
console.log('Sum:', sum);

Yet, you can also use Arrow Functions and the reduce function

const sum = arr.reduce(function (a, b) {
    return a + b;
}, 0);

console.log('Array:', arr);
console.log('Sum:', sum);

They're both gonna output

Array: [ 1, 2, 3, 4]
Sum: 10

How can I decode HTML characters in C#?

Use Server.HtmlDecode to decode the HTML entities. If you want to escape the HTML, i.e. display the < and > character to the user, use Server.HtmlEncode.

How to output an Excel *.xls file from classic ASP

There's a 'cheap and dirty' trick that I have used... shhhh don't tell anyone. If you output tab delimited text and make the file name *.xls then Excel opens it without objection, question or warning. So just crank the data out into a text file with tab delimitation and you can open it with Excel or Open Office.

How to read from input until newline is found using scanf()?

I am too late, but you can try this approach as well.

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

int main() {
    int i=0, j=0, arr[100];
    char temp;
    while(scanf("%d%c", &arr[i], &temp)){
        i++;
        if(temp=='\n'){
            break;
        }
    }
    for(j=0; j<i; j++) {
        printf("%d ", arr[j]);
    }

    return 0;
}

How can I check the size of a collection within a Django template?

If you tried myList|length and myList|length_is and its not getting desired results, then you should use myList.count

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64 macro and other printf issues altogether:

#include <fmt/core.h>

int main() {
  uint64_t ui64 = 90;
  fmt::print("test uint64_t : {}\n", ui64);
}

The formatting facility based on this library is proposed for standardization in C++20: P0645.

Disclaimer: I'm the author of {fmt}.

Web scraping with Java

Normally I use selenium, which is software for testing automation. You can control a browser through a webdriver, so you will not have problems with javascripts and it is usually not very detected if you use the full version. Headless browsers can be more identified.

How to use the IEqualityComparer

Your GetHashCode implementation always returns the same value. Distinct relies on a good hash function to work efficiently because it internally builds a hash table.

When implementing interfaces of classes it is important to read the documentation, to know which contract you’re supposed to implement.1

In your code, the solution is to forward GetHashCode to Class_reglement.Numf.GetHashCode and implement it appropriately there.

Apart from that, your Equals method is full of unnecessary code. It could be rewritten as follows (same semantics, ¼ of the code, more readable):

public bool Equals(Class_reglement x, Class_reglement y)
{
    return x.Numf == y.Numf;
}

Lastly, the ToList call is unnecessary and time-consuming: AddRange accepts any IEnumerable so conversion to a List isn’t required. AsEnumerable is also redundant here since processing the result in AddRange will cause this anyway.


1 Writing code without knowing what it actually does is called cargo cult programming. It’s a surprisingly widespread practice. It fundamentally doesn’t work.

Counting the number of non-NaN elements in a numpy ndarray in Python

To determine if the array is sparse, it may help to get a proportion of nan values

np.isnan(ndarr).sum() / ndarr.size

If that proportion exceeds a threshold, then use a sparse array, e.g. - https://sparse.pydata.org/en/latest/

Add params to given URL in Python

python3, self explanatory I guess

from urllib.parse import urlparse, urlencode, parse_qsl

url = 'https://www.linkedin.com/jobs/search?keywords=engineer'

parsed = urlparse(url)
current_params = dict(parse_qsl(parsed.query))
new_params = {'location': 'United States'}
merged_params = urlencode({**current_params, **new_params})
parsed = parsed._replace(query=merged_params)

print(parsed.geturl())
# https://www.linkedin.com/jobs/search?keywords=engineer&location=United+States

How to get autocomplete in jupyter notebook without using tab?

Without doing this %config IPCompleter.greedy=True after you import a package like numpy or pandas in this way; import numpy as np import pandas as pd.

Then you type in pd. then tap the tab button it brings out all the possible methods to use very easy and straight forward.

SQL Client for Mac OS X that works with MS SQL Server

This doesn't specifically answer your question, because I'm not sure in any clients exist in Mac OS X, but I generally just Remote Desktop into the server and work through that. Another option is VMware Fusion (which is much better than Parallels in my opinion) + Windows XP + SQL Server Management Studio.

What is the difference between a data flow diagram and a flow chart?

Data flow diagram: A modeling notation that represents a functional decomposition of a system.

Flow chart: Step by step flow of a programe.

google maps v3 marker info window on mouseover

var icon1 = "imageA.png";
var icon2 = "imageB.png";

var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: icon1,
    title: "some marker"
});

google.maps.event.addListener(marker, 'mouseover', function() {
    marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
    marker.setIcon(icon1);
});

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

How to prepend a string to a column value in MySQL?

Many string update functions in MySQL seems to be working like this: If one argument is null, then concatenation or other functions return null too. So, to update a field with null value, first set it to a non-null value, such as ''

For example:

update table set field='' where field is null;
update table set field=concat(field,' append');

Can you recommend a free light-weight MySQL GUI for Linux?

i suggest using phpmyadmin

it’s definitely the best free tool out there and it works on every system with php+mysql

Jquery $(this) Child Selector

In the click event "this" is the a tag that was clicked

jQuery('.class1 a').click( function() {
   var divToSlide = $(this).parent().find(".class2");
   if (divToSlide.is(":hidden")) {
      divToSlide.slideDown("slow");
   } else {
      divToSlide.slideUp();
   }
});

There's multiple ways to get to the div though you could also use .siblings, .next etc

.trim() in JavaScript not working in IE

It looks like that function isn't implemented in IE. If you're using jQuery, you could use $.trim() instead (http://api.jquery.com/jQuery.trim/).

Recover unsaved SQL query scripts

Go to SSMS >> Tools >> Options >> Environment >> AutoRecover

There are two different settings:

1) Save AutoRecover Information Every Minutes

This option will save the SQL Query file at certain interval. Set this option to minimum value possible to avoid loss. If you have set this value to 5, in the worst possible case, you can lose last 5 minutes of the work.

2) Keep AutoRecover Information for Days

This option will preserve the AutoRecovery information for specified days. Though, I suggest in case of accident open SQL Server Management Studio right away and recover your file. Do not procrastinate this important task for future dates.

Is there an XSLT name-of element?

Nobody did point the subtle difference in the semantics of the functions name() and local-name().

  • name(someNode) returns the full name of the node, and that includes the prefix and colon in case the node is an element or an attribute.
  • local-name(someNode) returns only the local name of the node, and that doesn't include the prefix and colon in case the node is an element or an attribute.

Therefore, in situations where a name may belong to two different namespaces, one must use the name() function in order for these names to be still distinguished.

And, BTW, it is possible to specify both functions without any argument:

name() is an abbreviation for name(.)

local-name() is an abbreviation for local-name(.)

Finally, do remember that not only elements and attributes have names, these two functions can also be used on PIs and on these they are identical).

How to use PHP string in mySQL LIKE query?

DO it like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the % at the end

Easiest way to convert a Blob into a byte array

The easiest way is this.

byte[] bytes = rs.getBytes("my_field");

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

Adding @WebAppConfiguration (org.springframework.test.context.web.WebAppConfiguration) annotation to your DemoApplicationTests class will work.

Change Spinner dropdown icon

I have had a lot of difficulty with this as I have a custom spinner, if I setBackground then the Drawable would stretch. My solution to this was to add a drawable to the right of the Spinner TextView. Heres a code snippet from my Custom Spinner. The trick is to Override getView and customize the Textview as you wish.

public class NoTextSpinnerArrayAdapter extends ArrayAdapter<String> {

    private String text = "0";

    public NoTextSpinnerArrayAdapter(Context context, int textViewResourceId, List<String> objects) {
        super(context, textViewResourceId, objects);
    }

    public void updateText(String text){
        this.text = text;
        notifyDataSetChanged();
    }

    public String getText(){
        return text;
    }

    @NonNull
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        TextView textView = view.findViewById(android.R.id.text1);
        textView.setCompoundDrawablePadding(16);
        textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_menu_white_24dp, 0);

        textView.setGravity(Gravity.END);
        textView.setText(text);
        return view;
    }
}

You also need to set the Spinner background to transparent:

<lifeunlocked.valueinvestingcheatsheet.views.SelectAgainSpinner
            android:id="@+id/saved_tickers_spinner"
            android:background="@android:color/transparent"
            android:layout_width="60dp"
            android:layout_height="match_parent"
            tools:layout_editor_absoluteX="248dp"
            tools:layout_editor_absoluteY="16dp" />

and my custom spinner if you want it....

public class SelectAgainSpinner extends android.support.v7.widget.AppCompatSpinner {
    public SelectAgainSpinner(Context context) {
        super(context);
    }

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

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

    @Override
    public void setPopupBackgroundDrawable(Drawable background) {
        super.setPopupBackgroundDrawable(background);
    }

    @Override
    public void setSelection(int position, boolean animate) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position, animate);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }

    @Override
    public void setSelection(int position) {
        boolean sameSelected = position == getSelectedItemPosition();
        super.setSelection(position);
        if (sameSelected) {
            // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now
            if (getOnItemSelectedListener() != null) {
                getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId());
            }
        }
    }
}

What datatype to use when storing latitude and longitude data in SQL databases?

You can easily store a lat/lon decimal number in an unsigned integer field, instead of splitting them up in a integer and decimal part and storing those separately as somewhat suggested here using the following conversion algorithm:

as a stored mysql function:

CREATE DEFINER=`r`@`l` FUNCTION `PositionSmallToFloat`(s INT) 
RETURNS decimal(10,7)
DETERMINISTIC
RETURN if( ((s > 0) && (s >> 31)) , (-(0x7FFFFFFF - 
(s & 0x7FFFFFFF))) / 600000, s / 600000)

and back

CREATE DEFINER=`r`@`l` FUNCTION `PositionFloatToSmall`(s DECIMAL(10,7)) 
RETURNS int(10)
DETERMINISTIC
RETURN s * 600000

That needs to be stored in an unsigned int(10), this works in mysql as well as in sqlite which is typeless.

through experience, I find that this works really fast, if all you need to to is store coordinates and retrieve those to do some math with.

in php those 2 functions look like

function LatitudeSmallToFloat($LatitudeSmall){
   if(($LatitudeSmall>0)&&($LatitudeSmall>>31)) 
     $LatitudeSmall=-(0x7FFFFFFF-($LatitudeSmall&0x7FFFFFFF))-1;
   return (float)$LatitudeSmall/(float)600000;
}

and back again:

function LatitudeFloatToSmall($LatitudeFloat){
   $Latitude=round((float)$LatitudeFloat*(float)600000);
   if($Latitude<0) $Latitude+=0xFFFFFFFF;
   return $Latitude;
}

This has some added advantage as well in term of creating for example memcached unique keys with integers. (ex: to cache a geocode result). Hope this adds value to the discussion.

Another application could be when you are without GIS extensions and simply want to keep a few million of those lat/lon pairs, you can use partitions on those fields in mysql to benefit from the fact they are integers:

Create Table: CREATE TABLE `Locations` (
  `lat` int(10) unsigned NOT NULL,
  `lon` int(10) unsigned NOT NULL,
  `location` text,
  PRIMARY KEY (`lat`,`lon`) USING BTREE,
  KEY `index_location` (`locationText`(30))
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/*!50100 PARTITION BY KEY ()
PARTITIONS 100 */

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

extract column value based on another column pandas dataframe

It's easier for me to think in these terms, but borrowing from other answers. The value you want is located in the series:

df[*column*][*row*]

where column and row point to the value you want returned. For your example, column is 'A' and for row you use a mask:

df['B'] == 3

To get the value from the series there are several options:

df['A'][df['B'] == 3].values[0]
df['A'][df['B'] == 3].iloc[0]
df['A'][df['B'] == 3].to_numpy()[0]

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

I think that this is as easy as I can explain it. Please, anyone is welcome to correct me or add to this.

SOAP is a message format used by disconnected systems (like across the internet) to exchange information / data. It does with XML messages going back and forth.

Web services transmit or receive SOAP messages. They work differently depending on what language they are written in.

c# write text on bitmap

Bitmap bmp = new Bitmap("filename.bmp");

RectangleF rectf = new RectangleF(70, 90, 90, 50);

Graphics g = Graphics.FromImage(bmp);

g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf);

g.Flush();

image.Image=bmp;

Create Pandas DataFrame from a string

In one line, but first import IO

import pandas as pd
import io   

TESTDATA="""col1;col2;col3
1;4.4;99
2;4.5;200
3;4.7;65
4;3.2;140
"""

df = pd.read_csv(  io.StringIO(TESTDATA)  , sep=";")
print ( df )

Convert date to day name e.g. Mon, Tue, Wed

$date = new \DateTime("now", new \DateTimeZone('Asia/Calcutta') );
         $day = $date->format('D');
         $weekendnaame = weekedName();
         $weekid =$weekendnaame[$day];
          $dayname = 0;
        $weekiarray = weekendArray($weekid);
        foreach ($weekiarray as $key => $value) {
            if (in_array($value, $request->get('week_id')))
          {
            $dayname = $key+1;
            break;
          }
        }


weeknDate($dayname),

function weeked(){
  $week = array("1"=>"Sunday", "2"=>"Monday", "3"=>"Tuesday", "4"=>"Wednesday", "5"=>"Thursday", "6"=>"Friday", "7"=>"Saturday");
  return $week;
}
function weekendArray($day){
        $favcolor = $day;

switch ($favcolor) {
  case 1:
    $array = array(2,3,4,5,6,7,1);
    break;
  case 2:
    $array = array(3,4,5,6,7,1,2);
    break;
  case 3:
    $array = array(4,5,6,7,1,2,3);
    break;
    case 4:
    $array = array(5,6,7,1,2,3,4);
    break;
    case 5:
    $array = array(6,7,1,2,3,4,5);
    break;
    case 6:
    $array = array(7,1,2,3,4,5,6);
    break;
     case 7:
    $array = array(1,2,3,4,5,6,7);
    break;
  default:
    $array = array(1,2,3,4,5,6,7);
}
return  $array;
}
function weekedName(){
  $week = array("Sun"=>0,"Mun"=>1,"Tue"=>3,"Wed"=>4,"Thu"=>5,"Fri"=>6,"Sat"=>7);
  return $week;
}

How do I get a Date without time in Java?

Here is a clean solution with no conversion to string and back, and also it doesn't re-calculate time several times as you reset each component of the time to zero. It also uses % (modulus) rather than divide followed by multiply to avoid the double operation.

It requires no third-party dependencies, and it RESPECTS THE TIMEZONE OF THE Calender object passed in. This function returns the moment in time at 12 AM in the timezone of the date (Calendar) you pass in.

public static Calendar date_only(Calendar datetime) {
    final long LENGTH_OF_DAY = 24*60*60*1000;
    long millis = datetime.getTimeInMillis();
    long offset = datetime.getTimeZone().getOffset(millis);
    millis = millis - ((millis + offset) % LENGTH_OF_DAY);
    datetime.setTimeInMillis(millis);
    return datetime;
}

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are the same. Numeric is functionally equivalent to decimal.

MSDN: decimal and numeric

Support for "border-radius" in IE

It is not planned for IE8. See the CSS Compatibility page.

Beyond that no plans have been released. Rumors exist that IE8 will be the last version for Windows XP

How to remove border of drop down list : CSS

You could simply use:

select {
    border: none;
    outline: none;
    scroll-behavior: smooth;
}

As the drop down list border is non editable you can not do anything with that but surely this will fix your initial outlook.

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

On Xampp edit apache config

  1. Click Apache 'config'
  2. Select 'httpd-ssl.conf'
  3. Look for 'Listen 443', change it to 'Listen 4430'

How to convert image file data in a byte array to a Bitmap?

Just try this:

Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();

If bitmapdata is the byte array then getting Bitmap is done like this:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

Returns the decoded Bitmap, or null if the image could not be decoded.

String length in bytes in JavaScript

You can try this:

function getLengthInBytes(str) {
  var b = str.match(/[^\x00-\xff]/g);
  return (str.length + (!b ? 0: b.length)); 
}

It works for me.

How to draw a filled triangle in android canvas?

enter image description here

this function shows how to create a triangle from bitmap. That is, create triangular shaped cropped image. Try the code below or download demo example

 public static Bitmap getTriangleBitmap(Bitmap bitmap, int radius) {
        Bitmap finalBitmap;
        if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
            finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                    false);
        else
            finalBitmap = bitmap;
        Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                finalBitmap.getHeight());

        Point point1_draw = new Point(75, 0);
        Point point2_draw = new Point(0, 180);
        Point point3_draw = new Point(180, 180);

        Path path = new Path();
        path.moveTo(point1_draw.x, point1_draw.y);
        path.lineTo(point2_draw.x, point2_draw.y);
        path.lineTo(point3_draw.x, point3_draw.y);
        path.lineTo(point1_draw.x, point1_draw.y);
        path.close();
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor("#BAB399"));
        canvas.drawPath(path, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(finalBitmap, rect, rect, paint);

        return output;
    }

The function above returns an triangular image drawn on canvas. Read more

Posting array from form

What you are doing is not necessarily bad practice but it does however require an extraordinary amount of typing. I would accomplish what you are trying to do like this.

foreach($_POST as $var => $val){
    $$var = $val;
}

This will take all the POST variables and put them in their own individual variables. So if you have a input field named email and the luser puts in [email protected] you will have a var named $email with a value of "[email protected]".

ImportError: cannot import name

This can also happen if you've been working on your scripts and functions and have been moving them around (i.e. changed the location of the definition) which could have accidentally created a looping reference.

You may find that the situation is solved if you just reset the iPython kernal to clear any old assignments:

%reset

or menu->restart terminal

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

Newer versions of ARC(Advaced Rest client) also provides file upload option:

enter image description here

Visual Studio Code includePath

My c_cpp_properties.json config-

{
    "configurations": [
        {
            "name": "Win32",
            "compilerPath": "C:/MinGW/bin/g++.exe",
            "includePath": [
                "C:/MinGW/lib/gcc/mingw32/9.2.0/include/c++"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "windows-gcc-x64"
       }
    ],
    "version": 4
}

How to check permissions of a specific directory?

$ ls -ld directory

ls is the list command.

- indicates the beginning of the command options.

l asks for a long list which includes the permissions.

d indicates that the list should concern the named directory itself; not its contents. If no directory name is given, the list output will pertain to the current directory.

Test if a string contains a word in PHP?

_x000D_
_x000D_
use _x000D_
_x000D_
if(stripos($str,'job')){_x000D_
   // do your work_x000D_
}
_x000D_
_x000D_
_x000D_

Difference between window.location.href=window.location.href and window.location.reload()

If you add the boolean true to the reload window.location.reload(true) it will load from server.

It is not clear how supported this boolean is, W3Org mentions that NS used to support it

There MIGHT be a difference between the content of window.location.href and document.URL - there at least used to be a difference between location.href and the non-standard and deprecated document.location that had to do with redirection, but that is really last millennium.

For documentation purposes I would use window.location.reload() because that is what you want to do.

How to remove element from array in forEach loop?

Although Xotic750's answer provides several good points and possible solutions, sometimes simple is better.

You know the array being iterated on is being mutated in the iteration itself (i.e. removing an item => index changes), thus the simplest logic is to go backwards in an old fashioned for (à la C language):

_x000D_
_x000D_
let arr = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];_x000D_
_x000D_
for (let i = arr.length - 1; i >= 0; i--) {_x000D_
  if (arr[i] === 'a') {_x000D_
    arr.splice(i, 1);_x000D_
  }_x000D_
}_x000D_
_x000D_
document.body.append(arr.join());
_x000D_
_x000D_
_x000D_

If you really think about it, a forEach is just syntactic sugar for a for loop... So if it's not helping you, just please stop breaking your head against it.

Difference between setUp() and setUpBeforeClass()

From the Javadoc:

Sometimes several tests need to share computationally expensive setup (like logging into a database). While this can compromise the independence of tests, sometimes it is a necessary optimization. Annotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those the current class.

fill an array in C#

You could try something like this:

I have initialzed the array for having value 5, you could put your number similarly.

int[] arr = new int[10]; // your initial array

arr = arr.Select(i => 5).ToArray(); // array initialized to 5.

Merge two (or more) lists into one, in C# .NET

Assuming you want a list containing all of the products for the specified category-Ids, you can treat your query as a projection followed by a flattening operation. There's a LINQ operator that does that: SelectMany.

// implicitly List<Product>
var products = new[] { CategoryId1, CategoryId2, CategoryId3 }
                     .SelectMany(id => GetAllProducts(id))
                     .ToList();

In C# 4, you can shorten the SelectMany to: .SelectMany(GetAllProducts)

If you already have lists representing the products for each Id, then what you need is a concatenation, as others point out.

How to compare LocalDate instances Java 8

I believe this snippet will also be helpful in a situation where the dates comparison spans more than two entries.

static final int COMPARE_EARLIEST = 0;

static final int COMPARE_MOST_RECENT = 1;


public LocalDate getTargetDate(List<LocalDate> datesList, int comparatorType) { 
   LocalDate refDate = null;
   switch(comparatorType)
   {
       case COMPARE_EARLIEST:         
       //returns the most earliest of the date entries
          refDate = (LocalDate) datesList.stream().min(Comparator.comparing(item -> 
                      item.toDateTimeAtCurrentTime())).get();
          break;

       case COMPARE_MOST_RECENT:
          //returns the most recent of the date entries 
          refDate = (LocalDate) datesList.stream().max(Comparator.comparing(item -> 
                    item.toDateTimeAtCurrentTime())).get();
          break;
   }

   return refDate;
}

Get remote registry value

If you need user's SID and browse remote HKEY_USERS folder, you can follow this script :

<# Replace following domain.name with yours and userAccountName with remote username #>
$userLogin = New-Object System.Security.Principal.NTAccount(“domain.name“,”userAccountName“)
$userSID = $userLogin.Translate([System.Security.Principal.SecurityIdentifier])

<# We will open HKEY_USERS and with accurate user’s SID from remoteComputer #>
$remoteRegistry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(‘Users’,”remoteComputer“)

<# We will then retrieve LocalName value from Control Panel / International subkeys #>

$key = $userSID.value+”\Control Panel\International”
$openKey = $remoteRegistry.OpenSubKey($key)

<# We can now retrieve any values #>

$localName = $openKey.GetValue(‘LocaleName’)

Source : http://techsultan.com/how-to-browse-remote-registry-in-powershell/

How to import a SQL Server .bak file into MySQL?

SQL Server databases are very Microsoft proprietary. Two options I can think of are:

  1. Dump the database in CSV, XML or similar format that you'd then load into MySQL.

  2. Setup ODBC connection to MySQL and then using DTS transport the data. As Charles Graham has suggested, you may need to build the tables before doing this. But that's as easy as a cut and paste from SQL Enterprise Manager windows to the corresponding MySQL window.

Usage of sys.stdout.flush() method

Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling sys.stdout.flush() forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.

Here's some good information about (un)buffered I/O and why it's useful:
http://en.wikipedia.org/wiki/Data_buffer
Buffered vs unbuffered IO

OpenCV in Android Studio

In your build.gradle

repositories {
  jcenter()
}

implementation 'com.quickbirdstudios:opencv:4.1.0'

More information

How to rotate a 3D object on axis three.js?

In Three.js R59, object.rotation.setEulerFromRotationMatrix(object.matrix); has been changed to object.rotation.setFromRotationMatrix(object.matrix);

3js is changing so rapidly :D

Convert a String to int?

With a recent nightly, you can do this:

let my_int = from_str::<int>(&*my_string);

What's happening here is that String can now be dereferenced into a str. However, the function wants an &str, so we have to borrow again. For reference, I believe this particular pattern (&*) is called "cross-borrowing".

.htaccess redirect http to https

Insert this code in your .htaccess file. And it should work

RewriteCond %{HTTP_HOST} yourDomainName\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourDomainName.com/$1 [R,L]

How can I create a link to a local file on a locally-run web page?

I've a way and work like this:

<'a href="FOLDER_PATH" target="_explorer.exe">Link Text<'/a>

git clone from another directory

Use git clone c:/folder1 c:/folder2

git clone [--template=<template_directory>] [-l] [-s] [--no-hardlinks]
[-q] [-n] [--bare] [--mirror] [-o <name>] [-b <name>] [-u <upload-pack>]
[--reference <repository>] [--separate-git-dir <git dir>] [--depth <depth>]
[--[no-]single-branch] [--recursive|--recurse-submodules] [--]<repository>
[<directory>]


<repository>

    The (possibly remote) repository to clone from.
    See the URLS section below for more information on specifying repositories.
<directory>

    The name of a new directory to clone into.
    The "humanish" part of the source repository is used if no directory 
    is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
    Cloning into an existing directory is only allowed if the directory is empty.

How to use \n new line in VB msgbox() ...?

This work for me: MessageBox.Show("YourString" & vbcrlf & "YourNewLineString")

Preloading images with jQuery

Thanks for this! I'd liek to add a little riff on the J-P's answer - I don't know if this will help anyone, but this way you don't have to create an array of images, and you can preload all your large images if you name your thumbs correctly. This is handy because I have someone who is writing all the pages in html, and it ensures one less step for them to do - eliminating the need to create the image array, and another step where things could get screwed up.

$("img").each(function(){
    var imgsrc = $(this).attr('src');
    if(imgsrc.match('_th.jpg') || imgsrc.match('_home.jpg')){
      imgsrc = thumbToLarge(imgsrc);
      (new Image()).src = imgsrc;   
    }
});

Basically, for each image on the page it grabs the src of each image, if it matches certain criteria (is a thumb, or home page image) it changes the name(a basic string replace in the image src), then loads the images.

In my case the page was full of thumb images all named something like image_th.jpg, and all the corresponding large images are named image_lg.jpg. The thumb to large just replaces the _th.jpg with _lg.jpg and then preloads all the large images.

Hope this helps someone.

How do I programmatically get the GUID of an application in .NET 2.0

For an out-of-the-box working example, this is what I ended up using based on the previous answers.

using System.Reflection;
using System.Runtime.InteropServices;

label1.Text = "GUID: " + ((GuidAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute), false)).Value.ToUpper();

Alternatively, this way allows you to use it from a static class:

    /// <summary>
    /// public GUID property for use in static class </summary>
    /// <returns>
    /// Returns the application GUID or "" if unable to get it. </returns>
    static public string AssemblyGuid
    {
        get
        {
            object[] attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(GuidAttribute), false);
            if (attributes.Length == 0) { return String.Empty; }
            return ((System.Runtime.InteropServices.GuidAttribute)attributes[0]).Value.ToUpper();
        }
    }

Comment out HTML and PHP together

Instead of using HTML comments (which have no effect on PHP code -- which will still be executed), you should use PHP comments:

<?php /*
<tr>
      <td><?php echo $entry_keyword; ?></td>
      <td><input type="text" name="keyword" value="<?php echo $keyword; ?>" /></td>
    </tr>
    <tr>
      <td><?php echo $entry_sort_order; ?></td>
      <td><input name="sort_order" value="<?php echo $sort_order; ?>" size="1" /></td>
    </tr>
*/ ?>


With that, the PHP code inside the HTML will not be executed; and nothing (not the HTML, not the PHP, not the result of its non-execution) will be displayed.


Just one note: you cannot nest C-style comments... which means the comment will end at the first */ encountered.

What is a "callback" in C and how are they implemented?

Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function on_event() and data pointers to a framework function watch_events() (for example). When an event happens, your function is called with your data and some event-specific data.

Callbacks are also used in GUI programming. The GTK+ tutorial has a nice section on the theory of signals and callbacks.

Entity framework self referencing loop detected

I just had the same issue on my .net core site. The accepted answer didn't work for me but i found that a combination of ReferenceLoopHandling.Ignore and PreserveReferencesHandling.Objects fixed it.

//serialize item
var serializedItem = JsonConvert.SerializeObject(data, Formatting.Indented, 
new JsonSerializerSettings
{
     PreserveReferencesHandling = PreserveReferencesHandling.Objects,
     ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});

How to configure Git post commit hook

I want to add to the answers above that it becomes a little more difficult if Jenkins authorization is enabled.

After enabling it I got an error message that anonymous user needs read permission.

I saw two possible solutions:

1: Changing my hook to:

curl --user name:passwd -s http://domain?token=whatevertokenuhave

2: setting project based authorization.

The former solutions has the disadvantage that I had to expose my passwd in the hook file. Unacceptable in my case.

The second works for me. In the global auth settings I had to enable Overall>Read for Anonymous user. In the project I wanted to trigger I had to enable Job>Build and Job>Read for Anonymous.

This is still not a perfect solution because now you can see the project in Jenkins without login. There might be an even better solution using the former approach with http login but I haven't figured it out.

Round double in two decimal places in C#?

Another easy way is to use ToString with a parameter. Example:

float d = 54.9700F;    
string s = d.ToString("N2");
Console.WriteLine(s);

Result:

54.97

How to set <iframe src="..."> without causing `unsafe value` exception?

I usually add separate safe pipe reusable component as following

# Add Safe Pipe

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {
    }

    public transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}
# then create shared pipe module as following 

import { NgModule } from '@angular/core'; 
import { SafePipe } from './safe.pipe';
@NgModule({
    declarations: [
        SafePipe
    ],
    exports: [
        SafePipe
    ]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module

@NgModule({
    declarations: [],
    imports: [
        SharedPipesModule,
    ],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
    <iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>

Get all files that have been modified in git branch

Considering you're on a feature branch and you want to check which files have changed compared to master... just this:

git diff --name-only master

Cannot install packages using node package manager in Ubuntu

Simple solution from here

curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash --
sudo apt-get install nodejs

You can specify version by changing setup_x.x value, for example to setup_5.x

Padding zeros to the left in postgreSQL

The to_char() function is there to format numbers:

select to_char(column_1, 'fm000') as column_2
from some_table;

The fm prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000 simply defines the number of digits you want to have.

psql (9.3.5)
Type "help" for help.

postgres=> with sample_numbers (nr) as (
postgres(>     values (1),(11),(100)
postgres(> )
postgres-> select to_char(nr, 'fm000')
postgres-> from sample_numbers;
 to_char
---------
 001
 011
 100
(3 rows)

postgres=>

For more details on the format picture, please see the manual:
http://www.postgresql.org/docs/current/static/functions-formatting.html

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You may need to handle javax.persistence.RollbackException

C# Error: Parent does not contain a constructor that takes 0 arguments

The compiler cannot guess what should be passed for the base constructor argument. You have to do it explicitly:

public class child : parent {
    public child(int i) : base(i) {
        Console.WriteLine("child");
    }
}

What does 'low in coupling and high in cohesion' mean

Low coupling is in the context of two or many modules. If a change in one module results in many changes in other module then they are said to be highly coupled. This is where interface based programming helps. Any change within the module will not impact the other module as the interface (the mean of interaction ) between them has not changed.

High cohesion- Put the similar things together. So a class should have method or behaviors to do related job. Just to give an exaggerated bad example: An implementation of List interface should not have operation related to String. String class should have methods, fields which is relevant for String and similarly, the implementation of List should have corresponding things.

Hope that helps.

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

For me the problem was with my targets tests. I already had the $(inherited) flag in my main app target.

I added it to MyAppTests Other Linker flags. After that when I ran pod install the warning message was gone. enter image description here

Is it possible to run CUDA on AMD GPUs?

You can run NVIDIA® CUDA™ code on Mac, and indeed on OpenCL 1.2 GPUs in general, using Coriander . Disclosure: I'm the author. Example usage:

cocl cuda_sample.cu
./cuda_sample

Result: enter image description here

What's the difference between a word and byte?

It seems all the answers assume high level languages and mainly C/C++.

But the question is tagged "assembly" and in all assemblers I know (for 8bit, 16bit, 32bit and 64bit CPUs), the definitions are much more clear:

byte  = 8 bits 
word  = 2 bytes
dword = 4 bytes = 2Words (dword means "double word")
qword = 8 bytes = 2Dwords = 4Words ("quadruple word")

Stop Excel from automatically converting certain text values to dates

WARNING: Excel '07 (at least) has a(nother) bug: if there's a comma in the contents of a field, it doesn't parse the ="field, contents" correctly, but rather puts everything after the comma into the following field, regardless of the quotation marks.

The only workaround I've found that works is to eliminate the = when the field contents include a comma.

This may mean that there are some fields that are impossible to represent exactly "right" in Excel, but by now I trust no-one is too surprised.

How to use workbook.saveas with automatic Overwrite

I recommend that before executing SaveAs, delete the file it exists.

If Dir("f:ull\path\with\filename.xls") <> "" Then
    Kill "f:ull\path\with\filename.xls"
End If

It's easier than setting DisplayAlerts off and on, plus if DisplayAlerts remains off due to code crash, it can cause problems if you work with Excel in the same session.

How can I submit a POST form using the <a href="..."> tag?

You have to use Javascript submit function on your form object. Take a look in other functions.

<form action="showMessage.jsp" method="post">
    <a href="javascript:;" onclick="parentNode.submit();"><%=n%></a>
    <input type="hidden" name="mess" value=<%=n%>/>
</form>

How to Make A Chevron Arrow Using CSS?

This can be solved much easier than the other suggestions.

Simply draw a square and apply a border property to just 2 joining sides.

Then rotate the square according to the direction you want the arrow to point, for exaple: transform: rotate(<your degree here>)

_x000D_
_x000D_
.triangle {_x000D_
    border-right: 10px solid; _x000D_
    border-bottom: 10px solid;_x000D_
    height: 30px;_x000D_
    width: 30px;_x000D_
    transform: rotate(-45deg);_x000D_
}
_x000D_
<div class="triangle"></div>
_x000D_
_x000D_
_x000D_

It says that TypeError: document.getElementById(...) is null

You can use JQuery to ensure that all elements of the documents are ready before it starts the client side scripting

$(document).ready(
    function()
    {
        document.getElementById(elmId).innerHTML = value;
    }
);

HTTP 1.0 vs 1.1

Proxy support and the Host field:

HTTP 1.1 has a required Host header by spec.

HTTP 1.0 does not officially require a Host header, but it doesn't hurt to add one, and many applications (proxies) expect to see the Host header regardless of the protocol version.

Example:

GET / HTTP/1.1
Host: www.blahblahblahblah.com

This header is useful because it allows you to route a message through proxy servers, and also because your web server can distinguish between different sites on the same server.

So this means if you have blahblahlbah.com and helohelohelo.com both pointing to the same IP. Your web server can use the Host field to distinguish which site the client machine wants.

Persistent connections:

HTTP 1.1 also allows you to have persistent connections which means that you can have more than one request/response on the same HTTP connection.

In HTTP 1.0 you had to open a new connection for each request/response pair. And after each response the connection would be closed. This lead to some big efficiency problems because of TCP Slow Start.

OPTIONS method:

HTTP/1.1 introduces the OPTIONS method. An HTTP client can use this method to determine the abilities of the HTTP server. It's mostly used for Cross Origin Resource Sharing in web applications.

Caching:

HTTP 1.0 had support for caching via the header: If-Modified-Since.

HTTP 1.1 expands on the caching support a lot by using something called 'entity tag'. If 2 resources are the same, then they will have the same entity tags.

HTTP 1.1 also adds the If-Unmodified-Since, If-Match, If-None-Match conditional headers.

There are also further additions relating to caching like the Cache-Control header.

100 Continue status:

There is a new return code in HTTP/1.1 100 Continue. This is to prevent a client from sending a large request when that client is not even sure if the server can process the request, or is authorized to process the request. In this case the client sends only the headers, and the server will tell the client 100 Continue, go ahead with the body.

Much more:

  • Digest authentication and proxy authentication
  • Extra new status codes
  • Chunked transfer encoding
  • Connection header
  • Enhanced compression support
  • Much much more.

datetime datatype in java

I used this import:

import java.util.Date;

And declared my variable like this:

Date studentEnrollementDate;

Iterating through a List Object in JSP

you can read empList directly in forEach tag.Try this

 <table>
       <c:forEach items="${sessionScope.empList}" var="employee">
            <tr>
                <td>Employee ID: <c:out value="${employee.eid}"/></td>
                <td>Employee Pass: <c:out value="${employee.ename}"/></td>  
            </tr>
        </c:forEach>
    </table>

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

Angular2 dynamic change CSS property

You don't have any example code but I assume you want to do something like this?

@View({
directives: [NgClass],
styles: [`
    .${TodoModel.COMPLETED}  {
        text-decoration: line-through;
    }
    .${TodoModel.STARTED} {
        color: green;
    }
`],
template: `<div>
                <span [ng-class]="todo.status" >{{todo.title}}</span>
                <button (click)="todo.toggle()" >Toggle status</button>
            </div>`
})

You assign ng-class to a variable which is dynamic (a property of a model called TodoModel as you can guess).

todo.toggle() is changing the value of todo.status and there for the class of the input is changing.

This is an example for class name but actually you could do the same think for css properties.

I hope this is what you meant.

This example is taken for the great egghead tutorial here.

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//span[@class='y2' and contains(text(), 'Your Text')] ") 
private WebElementFacade emailLinkToVerifyAccount;

This approach will work for you, hopefully.

how to initialize a char array?

memset(msg, 0, 65546)

What does LPCWSTR stand for and how should it be handled with?

It's a long pointer to a constant, wide string (i.e. a string of wide characters).

Since it's a wide string, you want to make your constant look like: L"TestWindow". I wouldn't create the intermediate a either, I'd just pass L"TestWindow" for the parameter:

ghTest = FindWindowEx(NULL, NULL, NULL, L"TestWindow");

If you want to be pedantically correct, an "LPCTSTR" is a "text" string -- a wide string in a Unicode build and a narrow string in an ANSI build, so you should use the appropriate macro:

ghTest = FindWindow(NULL, NULL, NULL, _T("TestWindow"));

Few people care about producing code that can compile for both Unicode and ANSI character sets though, and if you don't getting it to really work correctly can be quite a bit of extra work for little gain. In this particular case, there's not much extra work, but if you're manipulating strings, there's a whole set of string manipulation macros that resolve to the correct functions.

internet explorer 10 - how to apply grayscale filter?

IE10 does not support DX filters as IE9 and earlier have done, nor does it support a prefixed version of the greyscale filter.

However, you can use an SVG overlay in IE10 to accomplish the greyscaling. Example:

img.grayscale:hover {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
}

svg {
    background:url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);
}

(from: http://www.karlhorky.com/2012/06/cross-browser-image-grayscale-with-css.html)

Simplified JSFiddle: http://jsfiddle.net/KatieK/qhU7d/2/

More about the IE10 SVG filter effects: http://blogs.msdn.com/b/ie/archive/2011/10/14/svg-filter-effects-in-ie10.aspx

How to load/edit/run/save text files (.py) into an IPython notebook cell?

Drag and drop a Python file in the Ipython notebooks "home" notebooks table, click upload. This will create a new notebook with only one cell containing your .py file content

Else copy/paste from your favorite editor ;)

Getting ORA-01031: insufficient privileges while querying a table instead of ORA-00942: table or view does not exist

ORA-01031: insufficient privileges Solution: Go to Your System User. then Write This Code:

SQL> grant dba to UserName; //Put This username which user show this error message.

Grant succeeded.

C# Inserting Data from a form into an access Database

My Code to insert data is not working. It showing no error but data is not showing in my database.

public partial class Form1 : Form { OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString); public Form1() { InitializeComponent(); }

    private void Form1_Load(object sender, EventArgs e)
    {
        
    }

    private void btn_add_Click(object sender, EventArgs e)
    {
        OleDbDataAdapter items = new OleDbDataAdapter();
        connection.Open();
        OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName,  SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
        command.CommandType = CommandType.Text;
        command.ExecuteReader();
        connection.Close();
        MessageBox.Show("Insertd!");
    }
}

C++ catching all exceptions

Let me just mention this here: the Java

try 
{
...
}
catch (Exception e)
{
...
}

may NOT catch all exceptions! I've actually had this sort of thing happen before, and it's insantiy-provoking; Exception derives from Throwable. So literally, to catch everything, you DON'T want to catch Exceptions; you want to catch Throwable.

I know it sounds nitpicky, but when you've spent several days trying to figure out where the "uncaught exception" came from in code that was surrounded by a try ... catch (Exception e)" block comes from, it sticks with you.

How do I use typedef and typedef enum in C?

typedef enum state {DEAD,ALIVE} State;
|     | |                     | |   |^ terminating semicolon, required! 
|     | |   type specifier    | |   |
|     | |                     | ^^^^^  declarator (simple name)
|     | |                     |    
|     | ^^^^^^^^^^^^^^^^^^^^^^^  
|     |
^^^^^^^-- storage class specifier (in this case typedef)

The typedef keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern or static is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.

After the above declaration, the State identifier becomes an alias for the type enum state {DEAD,ALIVE}. The declaration also provides that type itself. However that isn't typedef doing it. Any declaration in which enum state {DEAD,ALIVE} appears as a type specifier introduces that type into the scope:

enum state {DEAD, ALIVE} stateVariable;

If enum state has previously been introduced the typedef has to be written like this:

typedef enum state State;

otherwise the enum is being redefined, which is an error.

Like other declarations (except function parameter declarations), the typedef declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:

typedef unsigned long ulong, *ulongptr;
|     | |           | |  1 | |   2   |
|     | |           | |    | ^^^^^^^^^--- "pointer to" declarator
|     | |           | ^^^^^^------------- simple declarator
|     | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier

This typedef introduces two type names ulong and ulongptr, based on the unsigned long type given in the specifier-qualifier list. ulong is just a straight alias for that type. ulongptr is declared as a pointer to unsigned long, thanks to the * syntax, which in this role is a kind of type construction operator which deliberately mimics the unary * for pointer dereferencing used in expressions. In other words ulongptr is an alias for the "pointer to unsigned long" type.

Alias means that ulongptr is not a distinct type from unsigned long *. This is valid code, requiring no diagnostic:

unsigned long *p = 0;
ulongptr q = p;

The variables q and p have exactly the same type.

The aliasing of typedef isn't textual. For instance if user_id_t is a typedef name for the type int, we may not simply do this:

unsigned user_id_t uid;  // error! programmer hoped for "unsigned int uid". 

This is an invalid type specifier list, combining unsigned with a typedef name. The above can be done using the C preprocessor:

#define user_id_t int
unsigned user_id_t uid;

whereby user_id_t is macro-expanded to the token int prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.

Among the disadvantages that it doesn't work well for derived types:

 #define silly_macro int *

 silly_macro not, what, you, think;

This declaration doesn't declare what, you and think as being of type "pointer to int" because the macro-expansion is:

 int * not, what, you, think;

The type specifier is int, and the declarators are *not, what, you and think. So not has the expected pointer type, but the remaining identifiers do not.

And that's probably 99% of everything about typedef and type aliasing in C.

Replacement for "rename" in dplyr

It is not listed as a function in dplyr (yet): http://cran.rstudio.org/web/packages/dplyr/dplyr.pdf

The function below works (almost) the same if you don't want to load both plyr and dplyr

rename <- function(dat, oldnames, newnames) {
  datnames <- colnames(dat)
  datnames[which(datnames %in% oldnames)] <- newnames
  colnames(dat) <- datnames
  dat
}

dat <- rename(mtcars,c("mpg","cyl"), c("mympg","mycyl"))
head(dat)

                  mympg mycyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4          21.0     6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag      21.0     6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710         22.8     4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive     21.4     6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout  18.7     8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant            18.1     6  225 105 2.76 3.460 20.22  1  0    3    1

Edit: The comment by Romain produces the following (note that the changes function requires dplyr .1.1)

> dplyr:::changes(mtcars, dat)
Changed variables:
          old         new        
disp      0x108b4b0e0 0x108b4e370
hp        0x108b4b210 0x108b4e4a0
drat      0x108b4b340 0x108b4e5d0
wt        0x108b4b470 0x108b4e700
qsec      0x108b4b5a0 0x108b4e830
vs        0x108b4b6d0 0x108b4e960
am        0x108b4b800 0x108b4ea90
gear      0x108b4b930 0x108b4ebc0
carb      0x108b4ba60 0x108b4ecf0
mpg       0x1033ee7c0            
cyl       0x10331d3d0            
mympg                 0x108b4e110
mycyl                 0x108b4e240

Changed attributes:
          old         new        
names     0x10c100558 0x10c2ea3f0
row.names 0x108b4bb90 0x108b4ee20
class     0x103bd8988 0x103bd8f58

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

I know this is an old question, but I wanted to make sure a couple of other options are noted.

Since you can't store a TimeSpan greater than 24 hours in a time sql datatype field; a couple of other options might be.

  1. Use a varchar(xx) to store the ToString of the TimeSpan. The benefit of this is the precision doesn't have to be baked into the datatype or the calculation, (seconds vs milliseconds vs days vs fortnights) All you need to to is use TimeSpan.Parse/TryParse. This is what I would do.

  2. Use a second date, datetime or datetimeoffset, that stores the result of first date + timespan. Reading from the db is a matter of TimeSpan x = SecondDate - FirstDate. Using this option will protect you for other non .NET data access libraries access the same data but not understanding TimeSpans; in case you have such an environment.

Insert HTML with React Variable Statements (JSX)

By using '' you are making it to string. Use without inverted commas it will work fine.

Fill formula down till last row in column

For people with a similar question and find this post (like I did); you can do this even without lastrow if your dataset is formatted as a table.

Range("tablename[columnname]").Formula = "=G3&"",""&L3"

Making it a true one liner. Hope it helps someone!

Make a div fill the height of the remaining screen space

Spinning off the idea of Mr. Alien...

This seems a cleaner solution than the popular flex box one for CSS3 enabled browsers.

Simply use min-height(instead of height) with calc() to the content block.

The calc() starts with 100% and subtracts heights of headers and footers (need to include padding values)

Using "min-height" instead of "height" is particularly useful so it can work with javascript rendered content and JS frameworks like Angular2. Otherwise, the calculation will not push the footer to the bottom of the page once the javascript rendered content is visible.

Here is a simple example of a header and footer using 50px height and 20px padding for both.

Html:

<body>
    <header></header>
    <div class="content"></div>
    <footer></footer>
</body>

Css:

.content {
    min-height: calc(100% - (50px + 20px + 20px + 50px + 20px + 20px));
}

Of course, the math can be simplified but you get the idea...

"Unable to find remote helper for 'https'" during git clone

The easiest way to fix this problem is to ensure that the git-core is added to the path for your current user

If you add the following to your bash profile file in ~/.bash_profile this should normally resolve the issue

PATH=$PATH:/usr/libexec/git-core

What does the NS prefix mean?

Basically NS comes from NextSTEP, the original operating system that became Mac OS X when Apple acquired Next.

I want to explain something else and this is why exactly it's needed.

In C++ there are namespaces and almost anything goes in std

This is why you have std::string.

Namespaces are used so it's harder for you to make a mistake and you can write your own class string without conflicting with the system one.

Objective-C is superset of C, but it doesn't include namespaces and for the same reason above all system classes are prefixed with NS or some other strange prefix.

This thing is the same of how all DirectX classes are prefixed with D3D and how all OpenGL classes are prefixed with gl.

This means that you should not use NS to name your own classes and when you see NS, CA in Core Animation or CG in Core Graphics you understand that this is a call to a system framework.

Swift changes this convention, because Swift supports namespacing and it maps its core types like String to the NS equivalents.

php error: Class 'Imagick' not found

On an EC2 at AWS, I did this:

 yum list | grep imagick

Then found a list of ones I could install...

 php -v

told me which version of php I had and thus which version of imagick

yum install php56-pecl-imagick.x86_64

Did the trick. Enjoy!

Is there any way to debug chrome in any IOS device

Old Answer (July 2016):

You can't directly debug Chrome for iOS due to restrictions on the published WKWebView apps, but there are a few options already discussed in other SO threads:

  1. If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.

  2. WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.

  3. You could try and create a simple WKWebView browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.

There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView, Chrome for iOS would be debuggable.

Update January 2018:

Since my answer back in 2016, some work has been done to improve things.

There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.

Check out the getting started guide in the repo, which is quite detailed.

If you are interesting, you can read up on the background and architecture here.

How can I make a list of installed packages in a certain virtualenv?

why don't you try pip list

Remember I'm using pip version 19.1 on python version 3.7.3

How do I correctly use "Not Equal" in MS Access?

In Access, you will probably find a Join is quicker unless your tables are very small:

SELECT DISTINCT Table1.Column1
FROM Table1 
LEFT JOIN Table2
ON Table1.Column1 = Table2.Column1  
WHERE Table2.Column1 Is Null

This will exclude from the list all records with a match in Table2.

Best C# API to create PDF

My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)

Android - SMS Broadcast receiver

The Updated code is :

 private class SMSReceiver extends BroadcastReceiver {
                private Bundle bundle;
                private SmsMessage currentSMS;
                private String message;

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

                    if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
                        bundle = intent.getExtras();
                        if (bundle != null) {
                            Object[] pdu_Objects = (Object[]) bundle.get("pdus");
                            if (pdu_Objects != null) {

                                for (Object aObject : pdu_Objects) {

                                    currentSMS = getIncomingMessage(aObject, bundle);

                                    String senderNo = currentSMS.getDisplayOriginatingAddress();

                                    message = currentSMS.getDisplayMessageBody();
                                    Toast.makeText(OtpActivity.this, "senderNum: " + senderNo + " :\n message: " + message, Toast.LENGTH_LONG).show();
                                }
                                this.abortBroadcast();
                                // End of loop
                            }
                        }
                    } // bundle null
                }
            }

        private SmsMessage getIncomingMessage(Object aObject, Bundle bundle) {
            SmsMessage currentSMS;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                String format = bundle.getString("format");
                currentSMS = SmsMessage.createFromPdu((byte[]) aObject, format);
            } else {
                currentSMS = SmsMessage.createFromPdu((byte[]) aObject);
            }
    return currentSMS;
}

older code was :

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

    messages = new SmsMessage[pdus.length];

    for (int i = 0; i < messages.length; i++)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String format = myBundle.getString("format");
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
        }
        else {
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
        }
        strMessage += "SMS From: " + messages[i].getOriginatingAddress();
        strMessage += " : ";
        strMessage += messages[i].getMessageBody();
        strMessage += "\n";
    } 

The simple SYntax of code is :

private class SMSReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
            SmsMessage[] smsMessages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
            for (SmsMessage message : smsMessages) {
                // Do whatever you want to do with SMS.
            }
        }
    }
}

Android Studio - How to Change Android SDK Path

Changing the sdk location in Project Settings will solve the problem partially. When Android Studio is used to download a new SDK, it will place the new SDK in the internal SDK folder (inside Android Studio).

Existing android developers will already have a large sdks folder (hereinafter referred to as external SDK folder) containing all the SDKs downloaded before Android Studio came around.

For Mac/Linux users though there is a good way out. Soft links!

Exit Android Studio and perform the following steps:

cp -r <Android Studio>/sdk/ <external SDK folder>/
cd <Android Studio>/
mv <Android Studio>/sdk/ mv <Android Studio>/sdk.orig
ln -s <external SDK folder>/ sdk

And we're good to go. Launch SDK Manager after starting Android Studio, watch as it discovers all your existing SDKs like a charm :).

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

Yes. Run ssh-add on the client machine. Then repeat command ssh-copy-id [email protected]

Linux shell sort file according to the second column?

sort -nk2 file.txt

Accordingly you can change column number.

Lists in ConfigParser

Only primitive types are supported for serialization by config parser. I would use JSON or YAML for that kind of requirement.

What is the most accurate way to retrieve a user's correct IP address in PHP?

I'm surprised no one has mentioned filter_input, so here is Alix Axel's answer condensed to one-line:

function get_ip_address(&$keys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'])
{
    return empty($keys) || ($ip = filter_input(INPUT_SERVER, array_pop($keys), FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE))? $ip : get_ip_address($keys);
}

How to draw a filled circle in Java?

/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
    g.setColor(Color.RED);
    g.fillOval(50,50,20,20);
}

g.fillOval(x-axis,y-axis,width,height);

Set QLineEdit to accept only numbers

You could also set an inputMask:

QLineEdit.setInputMask("9")

This allows the user to type only one digit ranging from 0 to 9. Use multiple 9's to allow the user to enter multiple numbers. See also the complete list of characters that can be used in an input mask.

(My answer is in Python, but it should not be hard to transform it to C++)

SQL Server stored procedure parameters

Why would you pass a parameter to a stored procedure that doesn't use it?

It sounds to me like you might be better of building dynamic SQL statements and then executing them. What you are trying to do with the SP won't work, and even if you could change what you are doing in such a way to accommodate varying numbers of parameters, you would then essentially be using dynamically generated SQL you are defeating the purpose of having/using a SP in the first place. SP's have a role, but there are not the solution in all cases.

Determine a user's timezone

If you happen to be using OpenID for authentication, Simple Registration Extension would solve the problem for authenticated users (You'll need to convert from tz to numeric).

Another option would be to infer the time zone from the user agent's country preference. This is a somewhat crude method (won't work for en-US), but makes a good approximation.

Get height of div with no height set in css

jQuery .height will return you the height of the element. It doesn't need CSS definition as it determines the computed height.

DEMO

You can use .height(), .innerHeight() or outerHeight() based on what you need.

enter image description here

.height() - returns the height of element excludes padding, border and margin.

.innerHeight() - returns the height of element includes padding but excludes border and margin.

.outerHeight() - returns the height of the div including border but excludes margin.

.outerHeight(true) - returns the height of the div including margin.

Check below code snippet for live demo. :)

_x000D_
_x000D_
$(function() {_x000D_
  var $heightTest = $('#heightTest');_x000D_
  $heightTest.html('Div style set as "height: 180px; padding: 10px; margin: 10px; border: 2px solid blue;"')_x000D_
    .append('<p>Height (.height() returns) : ' + $heightTest.height() + ' [Just Height]</p>')_x000D_
    .append('<p>Inner Height (.innerHeight() returns): ' + $heightTest.innerHeight() + ' [Height + Padding (without border)]</p>')_x000D_
    .append('<p>Outer Height (.outerHeight() returns): ' + $heightTest.outerHeight() + ' [Height + Padding + Border]</p>')_x000D_
    .append('<p>Outer Height (.outerHeight(true) returns): ' + $heightTest.outerHeight(true) + ' [Height + Padding + Border + Margin]</p>')_x000D_
});
_x000D_
div { font-size: 0.9em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="heightTest" style="height: 150px; padding: 10px; margin: 10px; border: 2px solid blue; overflow: hidden; ">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to work with string fields in a C struct?

You could just use an even simpler typedef:

typedef char *string;

Then, your malloc would look like a usual malloc:

string s = malloc(maxStringLength);

With CSS, how do I make an image span the full width of the page as a background image?

You set the CSS to :

#elementID {
    background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
    height: 200px;
}

It centers the image, but does not scale it.

FIDDLE

In newer browsers you can use the background-size property and do:

#elementID {
    height: 200px; 
    width: 100%;
    background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
    background-size: 100% 100%;
}

FIDDLE

Other than that, a regular image is one way to do it, but then it's not really a background image.

?

How to add a reference programmatically

Browsing the registry for guids or using paths, which method is best. If browsing the registry is no longer necessary, won't it be the better way to use guids? Office is not always installed in the same directory. The installation path can be manually altered. Also the version number is a part of the path. I could have never predicted that Microsoft would ever add '(x86)' to 'Program Files' before the introduction of 64 bits processors. If possible I would try to avoid using a path.

The code below is derived from Siddharth Rout's answer, with an additional function to list all the references that are used in the active workbook. What if I open my workbook in a later version of Excel? Will the workbook still work without adapting the VBA code? I have already checked that the guids for office 2003 and 2010 are identical. Let's hope that Microsoft doesn't change guids in future versions.

The arguments 0,0 (from .AddFromGuid) should use the latest version of a reference (which I have not been able to test).

What are your thoughts? Of course we cannot predict the future but what can we do to make our code version proof?

Sub AddReferences(wbk As Workbook)
    ' Run DebugPrintExistingRefs in the immediate pane, to show guids of existing references
    AddRef wbk, "{00025E01-0000-0000-C000-000000000046}", "DAO"
    AddRef wbk, "{00020905-0000-0000-C000-000000000046}", "Word"
    AddRef wbk, "{91493440-5A91-11CF-8700-00AA0060263B}", "PowerPoint"
End Sub

Sub AddRef(wbk As Workbook, sGuid As String, sRefName As String)
    Dim i As Integer
    On Error GoTo EH
    With wbk.VBProject.References
        For i = 1 To .Count
            If .Item(i).Name = sRefName Then
               Exit For
            End If
        Next i
        If i > .Count Then
           .AddFromGuid sGuid, 0, 0 ' 0,0 should pick the latest version installed on the computer
        End If
    End With
EX: Exit Sub
EH: MsgBox "Error in 'AddRef'" & vbCrLf & vbCrLf & err.Description
    Resume EX
    Resume ' debug code
End Sub

Public Sub DebugPrintExistingRefs()
    Dim i As Integer
    With Application.ThisWorkbook.VBProject.References
        For i = 1 To .Count
            Debug.Print "    AddRef wbk, """ & .Item(i).GUID & """, """ & .Item(i).Name & """"
        Next i
    End With
End Sub

The code above does not need the reference to the "Microsoft Visual Basic for Applications Extensibility" object anymore.

How to find out what group a given user has?

Below is the script which is integrated into ansible and generating dashboard in CSV format.

sh collection.sh

#!/bin/bash

HOSTNAME=`hostname -s`

for i in `cat /etc/passwd| grep -vE "nologin|shutd|hal|sync|root|false"|awk -F':' '{print$1}' | sed 's/[[:space:]]/,/g'`; do groups $i; done|sed s/\:/\,/g|tr -d ' '|sed -e "s/^/$HOSTNAME,/"> /tmp/"$HOSTNAME"_inventory.txt

sudo cat /etc/sudoers| grep -v "^#"|awk '{print $1}'|grep -v Defaults|sed '/^$/d;s/[[:blank:]]//g'>/tmp/"$HOSTNAME"_sudo.txt

paste -d , /tmp/"$HOSTNAME"_inventory.txt /tmp/"$HOSTNAME"_sudo.txt|sed 's/,[[:blank:]]*$//g' >/tmp/"$HOSTNAME"_inventory_users.txt

My output stored in below text files.

cat /tmp/ANSIBLENODE_sudo.txt
cat /tmp/ANSIBLENODE_inventory.txt
cat /tmp/ANSIBLENODE_inventory_users.txt

How can I search sub-folders using glob.glob module?

To find files in immediate subdirectories:

configfiles = glob.glob(r'C:\Users\sam\Desktop\*\*.txt')

For a recursive version that traverse all subdirectories, you could use ** and pass recursive=True since Python 3.5:

configfiles = glob.glob(r'C:\Users\sam\Desktop\**\*.txt', recursive=True)

Both function calls return lists. You could use glob.iglob() to return paths one by one. Or use pathlib:

from pathlib import Path

path = Path(r'C:\Users\sam\Desktop')
txt_files_only_subdirs = path.glob('*/*.txt')
txt_files_all_recursively = path.rglob('*.txt') # including the current dir

Both methods return iterators (you can get paths one by one).

Convert Difference between 2 times into Milliseconds?

If you are only dealing with Times and no dates you will want to only deal with TimeSpan and handle crossing over midnight.

TimeSpan time1 = ...;  // assume TimeOfDay
TimeSpan time2 = ...;  // assume TimeOfDay
TimeSpan diffTime = time2 - time1;
if (time2 < time1)  // crosses over midnight
    diffTime += TimeSpan.FromTicks(TimeSpan.TicksPerDay);
int totalMilliSeconds = (int)diffTime.TotalMilliseconds;

When to use single quotes, double quotes, and backticks in MySQL

The string literals in MySQL and PHP are the same.

A string is a sequence of bytes or characters, enclosed within either single quote (“'”) or double quote (“"”) characters.

So if your string contains single quotes, then you could use double quotes to quote the string, or if it contains double quotes, then you could use single quotes to quote the string. But if your string contains both single quotes and double quotes, you need to escape the one that used to quote the string.

Mostly, we use single quotes for an SQL string value, so we need to use double quotes for a PHP string.

$query = "INSERT INTO table (id, col1, col2) VALUES (NULL, 'val1', 'val2')";

And you could use a variable in PHP's double-quoted string:

$query = "INSERT INTO table (id, col1, col2) VALUES (NULL, '$val1', '$val2')";

But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)

Sublime Text 2 - View whitespace characters

http://sublimetexttips.com/show-whitespace-sublime-text/

  1. open

Ctrl+Shift+P

  1. search

Preferences: Settings –> User

  1. just paste below codes

_x000D_
_x000D_
{_x000D_
    "draw_white_space": "all",_x000D_
    "translate_tabs_to_spaces": true_x000D_
}
_x000D_
_x000D_
_x000D_

Convert UTC datetime string to local datetime

I traditionally defer this to the frontend -- send times from the backend as timestamps or some other datetime format in UTC, then let the client figure out the timezone offset and render this data in the proper timezone.

For a webapp, this is pretty easy to do in javascript -- you can figure out the browser's timezone offset pretty easily using builtin methods and then render the data from the backend properly.

Image convert to Base64

Function convert image to base64 using jquery (you can convert to vanila js). Hope it help to you!

Usage: input is your nameId input has file image

<input type="file" id="asd"/>
<button onclick="proccessData()">Submit</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

async function converImageToBase64(inputId) {
  let image = $('#'+inputId)[0]['files']

  if (image && image[0]) {
    const reader = new FileReader();

    return new Promise(resolve => {
      reader.onload = ev => {
        resolve(ev.target.result)
      }
      reader.readAsDataURL(image[0])
    })
  }
}

async function proccessData() {
  const image = await converImageToBase64('asd')
  console.log(image)
}

</script>

Example: converImageToBase64('yourFileInputId')

https://codepen.io/mariohandsome/pen/yLadmVb

JavaScript equivalent to printf/String.Format

Just in case someone needs a function to prevent polluting global scope, here is the function that does the same:

  function _format (str, arr) {
    return str.replace(/{(\d+)}/g, function (match, number) {
      return typeof arr[number] != 'undefined' ? arr[number] : match;
    });
  };

How to convert NSNumber to NSString

You can do it with:

NSNumber *myNumber = @15;
NSString *myNumberInString = [myNumber stringValue];

How to remove trailing whitespace in code, using another script?

It's a bit surprising seeing multiple answers suggesting to use python for this task, as there's no need to write a multi-line program for this.

Standard Unix tools like sed, awk or perl can achieve this easily straight from the command-line.

e.g anywhere you have perl (Windows, Mac, Linux) the following should achieve what the OP asked:

perl -i -pe 's/[ \t]+$//;' files...

Explanation of the arguments to perl:

-i   # run the edit "in place" (modify the original file)
-p   # implies a loop with a final print over every input line
-e   # next arg is the perl expression to apply (to every line)

s/[ \t]$// is a substitution regex s/FROM/TO/: replace every trailing (end of line) non-empty space (spaces or tabs) with nothing.

Advantages:

  • One liner, no programming needed
  • Works on multiple (any number) of files
  • Works correctly on standard-input (no file arguments given)

Edit:

Newer versions of perl support \h (any horizontal-space character), so the solution becomes even shorter:

perl -i -pe 's/\h+$//;' files...

More generally, if you want to modify any number of files directly from the command line, replacing every appearance of FOO with BAR, you may always use this generic template:

perl -i -pe 's/FOO/BAR/' files...

Is there such a thing as min-font-size and max-font-size?

CSS min() and max() have fairly good usage rates in 2020.

The code below uses max() to get the largest of the [variablevalue] and [minimumvalue] and then passes that through to min() against the [maximumvalue] to get the smaller of the two. This creates an allowable font range (3.5rem is minimum, 6.5rem is maximum, 6vw is used only when in between).

font-size: min(max([variablevalue], [minimumvalue]), [maximumvalue]);
font-size: min(max(6vw, 3.5rem), 6.5rem);

I'm using this specifically with font-awesome as a video-play icon over an image within a bootstrap container element where max-width is set.

How to advance to the next form input when the current input has a value?

you just need to give focus to the next input field (by invoking focus()method on that input element), for example if you're using jQuery this code will simulate the tab key when enter is pressed:

var inputs = $(':input').keypress(function(e){ 
    if (e.which == 13) {
       e.preventDefault();
       var nextInput = inputs.get(inputs.index(this) + 1);
       if (nextInput) {
          nextInput.focus();
       }
    }
});

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I would rather use plt.clf() after every plt.show() to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.

Similarly, you could do plt.cla() to just clear the current axes.

To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:

fig, axes = plt.subplots(nrows=2, ncols=2)

axes[0, 1].clear()

Error: No module named psycopg2.extensions

you can install gcc for macos from https://github.com/kennethreitz/osx-gcc-installer
after instalation of gcc you'll be able to install psycopg with easy_install or with pip

Strtotime() doesn't work with dd/mm/YYYY format

Are you getting this value from a database? If so, consider formatting it in the database (use date_format in mysql, for example). If not, exploding the value may be the best bet, since strtotime just doesn't seem to appreciate dd/mm/yyyy values.

VS2010 How to include files in project, to copy them to build output directory automatically during build or publish

Try adding a reference to the missing dll's from your service/web project directly. Adding the references to a different project didn't work for me.

I only had to do this when publishing my web app because it wasn't copying all the required dll's.

Android ListView with onClick items

for what kind of Hell implementing Parcelable ?

he is passing to adapter String[] so

  • get item(String) at position
  • create intent
  • put it as extra
  • start activity
  • in activity get extra

to store product list you can use here HashMap (for example as STATIC object)

example class describing product:

public class Product {
    private String _name;
    private String _description;
    private int _id

    public Product(String name, String description,int id) {
        _name = name;
        _desctription = description;
        _id = id;
    }

    public String getName() {
        return _name;
    }

    public String getDescription() {
        return _description;
    }
}

Product dell = new Product("dell","this is dell",1);

HashMap<String,Product> _hashMap = new HashMap<>();
_hashMap.put(dell.getName(),dell);

then u pass to adapter set of keys as:

String[] productNames =  _hashMap.keySet().toArray(new String[_hashMap.size()]);

when in adapter u return view u set listener like this for example:

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {

     Context context = parent.getContext(); 

     String itemName = getItem(position)

     someView.setOnClikListener(new MyOnClickListener(context, itemName));

 }


 private class MyOnClickListener implements View.OnClickListener { 

     private  String _itemName; 
     private  Context _context

     public MyOnClickListener(Context context, String itemName) {
         _context = context;
         _itemName = itemName; 
     }

     @Override 
     public void onClick(View view) {
         //------listener onClick example method body ------
         Intent intent = new Intent(_context, SomeClassToHandleData.class);
         intent.putExtra(key_to_product_name,_itemName);
         _context.startActivity(intent);
     }
 }

then in other activity:

@Override 
public void onCreate(Bundle) {

    String productName = getIntent().getExtra(key_to_product_name);
    Product product = _hashMap.get(productName);

}

*key_to_product_name is a public static String to serve as key for extra

ps. sorry for typo i was in hurry :) ps2. this shoud give you a idea how to do it ps3. when i will have more time i I'll add a detailed description

MY COMMENT:

  • DO NOT USE ANY SWITCH STATEMENT
  • DO NOT CREATE SEPARATE ACTIVITIES FOR EACH PRODUCT ( U NEED ONLY ONE)

Package doesn't exist error in intelliJ

Maven reimport, rebuild and invalidate caches did not work. I solved it by opening a terminal and executing maven clean install in the root folder project. (IntelliJ was opened and I was able to see the IDE updating and triggering reindexation while maven was doing his job)