Programs & Examples On #Struts2

Apache Struts 2 is an extensible framework based on servlets and implements model–view–controller (MVC) pattern in its architecture for creating enterprise-ready Java web applications.

Could not resolve placeholder in string value

I had the same problem, resolved it by adding

<filtering>true</filtering> 

in pom.xml :

before (didn't work):

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>               
        </resource>
    </resources>
</build>

after(it worked):

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

After that you just run mvn clean install and deploy application.

Maven Java EE Configuration Marker with Java Server Faces 1.2

This is an older thread,but I will post my answer for others. I have to recreate the project in a different workspace after the changes to make it work, as discussed in JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer

Amazon S3 upload file and get URL

Similarly if you want link through s3Client you can use below.

System.out.println("filelink: " + s3Client.getUrl("your_bucket_name", "your_file_key"));

Configure hibernate to connect to database via JNDI Datasource

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

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

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

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

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

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

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

Gson: How to exclude specific fields from Serialization without annotations

I used this strategy: i excluded every field which is not marked with @SerializedName annotation, i.e.:

public class Dummy {

    @SerializedName("VisibleValue")
    final String visibleValue;
    final String hiddenValue;

    public Dummy(String visibleValue, String hiddenValue) {
        this.visibleValue = visibleValue;
        this.hiddenValue = hiddenValue;
    }
}


public class SerializedNameOnlyStrategy implements ExclusionStrategy {

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return f.getAnnotation(SerializedName.class) == null;
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }
}


Gson gson = new GsonBuilder()
                .setExclusionStrategies(new SerializedNameOnlyStrategy())
                .create();

Dummy dummy = new Dummy("I will see this","I will not see this");
String json = gson.toJson(dummy);

It returns

{"VisibleValue":"I will see this"}

jQuery multiselect drop down menu

You can use chosen.i download all file from this link Chosen download Link

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link href="prism.css" rel="stylesheet" type="text/css" />
    <link href="chosen.css" rel="stylesheet" type="text/css" />
    <script src="jquery-2.1.4.min.js" type="text/javascript"></script>
    <script src="chosen.jquery.js" type="text/javascript"></script>
    <script src="prism.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $(".chzn-select").chosen();
        });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>

<ion-view view-title="Profile">
<ion-content class="padding">

<div>
    <label class="item item-input">
        <div class="input-label">Enter Your Option</div>
            <select class="chzn-select" multiple="true" name="faculty" style="width:1000px;">
                <option value="Option 2.1">Option 2.1</option>
                <option value="Option 2.2">Option 2.2</option>
                <option value="Option 2.3">Option 2.3</option>
            </select>   
    </label>
</div>
</ion-content>
</ion-view> 
    </div>
    </form>
</body>
</html>

All file on all same folder

Download a file by jQuery.Ajax

You can with HTML5

NB: The file data returned MUST be base64 encoded because you cannot JSON encode binary data

In my AJAX response I have a data structure that looks like this:

{
    result: 'OK',
    download: {
        mimetype: string(mimetype in the form 'major/minor'),
        filename: string(the name of the file to download),
        data: base64(the binary data as base64 to download)
    }
}

That means that I can do the following to save a file via AJAX

var a = document.createElement('a');
if (window.URL && window.Blob && ('download' in a) && window.atob) {
    // Do it the HTML5 compliant way
    var blob = base64ToBlob(result.download.data, result.download.mimetype);
    var url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = result.download.filename;
    a.click();
    window.URL.revokeObjectURL(url);
}

The function base64ToBlob was taken from here and must be used in compliance with this function

function base64ToBlob(base64, mimetype, slicesize) {
    if (!window.atob || !window.Uint8Array) {
        // The current browser doesn't have the atob function. Cannot continue
        return null;
    }
    mimetype = mimetype || '';
    slicesize = slicesize || 512;
    var bytechars = atob(base64);
    var bytearrays = [];
    for (var offset = 0; offset < bytechars.length; offset += slicesize) {
        var slice = bytechars.slice(offset, offset + slicesize);
        var bytenums = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            bytenums[i] = slice.charCodeAt(i);
        }
        var bytearray = new Uint8Array(bytenums);
        bytearrays[bytearrays.length] = bytearray;
    }
    return new Blob(bytearrays, {type: mimetype});
};

This is good if your server is dumping filedata to be saved. However, I've not quite worked out how one would implement a HTML4 fallback

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

As an addition to msangel answer I would like to add the following code block:

private static CompletableFuture<Boolean> redirectToLogger(final InputStream inputStream, final Consumer<String> logLineConsumer) {
        return CompletableFuture.supplyAsync(() -> {
            try (
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            ) {
                String line = null;
                while((line = bufferedReader.readLine()) != null) {
                    logLineConsumer.accept(line);
                }
                return true;
            } catch (IOException e) {
                return false;
            }
        });
    }

It allows to redirect the input stream (stdout, stderr) of the process to some other consumer. This might be System.out::println or anything else consuming strings.

Usage:

...
Process process = processBuilder.start()
CompletableFuture<Boolean> stdOutRes = redirectToLogger(process.getInputStream(), System.out::println);
CompletableFuture<Boolean> stdErrRes = redirectToLogger(process.getErrorStream(), System.out::println);
System.out.println(stdOutRes.get());
System.out.println(stdErrRes.get());
System.out.println(process.waitFor());

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.

If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).

This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.

https://support.microsoft.com/en-us/kb/938397

For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:

http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe

What is the difference between an int and an Integer in Java and C#?

"int" is primitive data-type and "Integer" in Wrapper Class in Java. "Integer" can be used as an argument to a method which requires an object, where as "int" can be used as an argument to a method which requires an integer value, that can be used for arithmetic expression.

IllegalArgumentException or NullPointerException for a null parameter?

Ideally runtime exceptions should not be thrown. A checked exception(business exception) should be created for your scenario. Because if either of these exception is thrown and logged, it misguides the developer while going through the logs. Instead business exceptions do not create that panic and usually ignored while troubleshooting logs.

Class Not Found Exception when running JUnit test

In my case, changing the order of Maven Dependencies from Build Path configuration did not work for me. I changed its order from Run configuration.
Follow these steps:
• Go to Run -> Run Configurations...
• Click on the unit test's run configuration and click on the Classpath tab.
• check Use temporary JAR to specify classpath (to avoid classpath length limitations).
May be it is enough and your test works. You should try, so press Run button. If it did not work. Follow all previous steps again and without pressing Run button, go to the next step.
• In sub branches of User Entries move Maven Dependencies above your project or test class.
• Click Run button.

Is it possible to set a custom font for entire of application?

As of Android O this is now possible to define directly from the XML and my bug is now closed!

See here for details

TL;DR:

First you must add your fonts to the project

Second you add a font family, like so:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>

Finally, you can use the font in a layout or style:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/lobster"/>

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/lobster</item>
</style>

Enjoy!

JavaScript .replace only replaces first Match

textTitle.replace(/ /g, '%20');

Delete all lines beginning with a # from a file

This answer builds upon the earlier answer by Keith.

egrep -v "^[[:blank:]]*#" should filter out comment lines.

egrep -v "^[[:blank:]]*(#|$)" should filter out both comments and empty lines, as is frequently useful.

For information about [:blank:] and other character classes, refer to https://en.wikipedia.org/wiki/Regular_expression#Character_classes.

How can I start PostgreSQL on Windows?

If you have installed postgres via the Windows installer you can start it in Services like so:

enter image description here

Emulate/Simulate iOS in Linux

Maybe, this approach is better, https://saucelabs.com/mobile, mobile testing in the cloud with selenium

How can I apply styles to multiple classes at once?

Don’t Repeat Your CSS

 a.abc, a.xyz{
    margin-left:20px;
 }

OR

 a{
    margin-left:20px;
 }

Google Chrome redirecting localhost to https

I never figured out the root of the problem however I was able to fix this problem. I deleted the Google Chrome app cache folder which solved the problem.

C:\Users[users]\AppData\Local\Google\Chrome

Iterate through a HashMap

Smarter:

for (String key : hashMap.keySet()) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));
}

Aligning label and textbox on same line (left and right)

You can do it with a table, like this:

<table width="100%">
  <tr>
    <td style="width: 50%">Left Text</td>
    <td style="width: 50%; text-align: right;">Right Text</td>
  </tr>
</table>

Or, you can do it with CSS like this:

<div style="float: left;">
    Left text
</div>
<div style="float: right;">
    Right text
</div>

How can I update npm on Windows?

1. Installing latest npm version

npm install –g npm@latest 

(You can type "npm –version" to check that)


2. Installing Node

a. Install node new version via following URL: https://nodejs.org/en/download/current/ Follow the default choices
b. Remove C:\Users\\AppData\Roaming\NPM
c. Remove C:\Users\\AppData\Roaming\npm-cache


Optionally:

d. (Delete node_modules folder in your current project folder)
e. npm cache verify
f. npm install

Calculate a Running Total in SQL Server

Using join Another variation is to use join. Now the query could look like:

    SELECT a.id, a.value, SUM(b.Value)FROM   RunTotalTestData a,
    RunTotalTestData b
    WHERE b.id <= a.id
    GROUP BY a.id, a.value 
    ORDER BY a.id;

for more you can visite this link http://askme.indianyouth.info/details/calculating-simple-running-totals-in-sql-server-12

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Remote debugging Tomcat with Eclipse

Modify catalina.bat to add

set JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n" 

and

CATALINA_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

Optional: Add below line to run the debug mode by default when you run startup.bat

call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%

Eclipse or STS select debug configuration right click -> new

connection type -> Standard socket Attach
Port -> 8000 (as given in the CATALINA_OPTS)
Host -> localhost or IP address

Update date + one year in mysql

For multiple interval types use a nested construction as in:

 UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)

For updating a given date in the column date to 1 year + 1 day

What does the 'export' command do?

I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.

In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.

In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile or /etc/.bashrc but otherwise, they're not permanent. They're stored in RAM.

There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.

You can view shell variables with the set command (though note that unlike windows, variables are not set in linux with the set command).

set -o posix; set (doing that set -o posix once first, helps not display too much unnecessary stuff). So set displays shell variables.

You can view environment variables with the env command

shell variables are set with e.g. just a = 5

environment variables are set with export, export also sets the shell variable

Here you see shell variable zzz set with zzz = 5, and see it shows when running set but doesn't show as an environment variable.

Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables

$ zzz=5

$ set | grep zzz
zzz=5

$ env | grep zzz

$ export yyy=5

$ set | grep yyy
yyy=5

$ env | grep yyy
yyy=5

$

other useful threads

https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables

https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference

Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf then it sets $1 to asdf, and if you do echo $1 you see asdf. If you do set a=5 it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose to turn verbose off. Windows has no such usage for its set command.

ng-change not working on a text input

When you want to edit something in Angular you need to insert an ngModel in your html

try this in your sample:

    <input type="text" name="abc" class="color" ng-model="myStyle.color">

You don't need to watch the change at all!

What are the advantages of Sublime Text over Notepad++ and vice-versa?

Main advantage for me is that Sublime Text 2 is almost the same, and has the same features on Windows, Linux and OS X. Can you claim that about Notepad++? It makes me move from one OS to another seamlessly.

Then there is speed. Sublime Text 2, which people claim is buggy and unstable ( 3 is more stable ), is still amazingly fast. If you use it, you will realize how fast it is.

Sublime Text 2 has some neat features like multi cursor input, multiple selections etc that will make you immensely productive.

Good number of plugins and themes, and also support for those of Textmate means you can do anything with Sublime Text 2. I have moved from Notepad++ to Sublime Text 2 on Windows and haven't looked back. The real question for me has been - Sublime Text 2 or vim?

What's good on Notepad++ side - it loads much faster on Windows for me. Maybe it will be good enough for you for quick editing. But, again, Sublime Text 3 is supposed to be faster on this front too. Sublime text 2 is not really good when it comes to handling huge files, and I had found that Notepad++ was pretty good till certain size of files. And, of course, Notepad++ is free. Sublime Text 2 has unlimited trial.

IOError: [Errno 32] Broken pipe: Python

To bring Alex L.'s helpful answer, akhan's helpful answer, and Blckknght's helpful answer together with some additional information:

  • Standard Unix signal SIGPIPE is sent to a process writing to a pipe when there's no process reading from the pipe (anymore).

    • This is not necessarily an error condition; some Unix utilities such as head by design stop reading prematurely from a pipe, once they've received enough data.
  • By default - i.e., if the writing process does not explicitly trap SIGPIPE - the writing process is simply terminated, and its exit code is set to 141, which is calculated as 128 (to signal termination by signal in general) + 13 (SIGPIPE's specific signal number).

  • By design, however, Python itself traps SIGPIPE and translates it into a Python IOError instance with errno value errno.EPIPE, so that a Python script can catch it, if it so chooses - see Alex L.'s answer for how to do that.

  • If a Python script does not catch it, Python outputs error message IOError: [Errno 32] Broken pipe and terminates the script with exit code 1 - this is the symptom the OP saw.

  • In many cases this is more disruptive than helpful, so reverting to the default behavior is desirable:

    • Using the signal module allows just that, as stated in akhan's answer; signal.signal() takes a signal to handle as the 1st argument and a handler as the 2nd; special handler value SIG_DFL represents the system's default behavior:

      from signal import signal, SIGPIPE, SIG_DFL
      signal(SIGPIPE, SIG_DFL) 
      

What is referencedColumnName used for in JPA?

Quoting API on referencedColumnName:

The name of the column referenced by this foreign key column.

Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.

Q/A

Where this would be used?

When there is a composite PK in referenced table, then you need to specify column name you are referencing.

calculating execution time in c++

This looks like Dijstra's algorithm. In any case, the time taken to run will depend on N. If it takes more than 3 seconds there isn't any way I can see of speeding it up, as all the calculations that it is doing need to be done.

Depending on what problem you're trying to solve, there might be a faster algorithm.

Import pandas dataframe column as string not int

Since pandas 1.0 it became much more straightforward. This will read column 'ID' as dtype 'string':

pd.read_csv('sample.csv',dtype={'ID':'string'})

As we can see in this Getting started guide, 'string' dtype has been introduced (before strings were treated as dtype 'object').

How can I disable HREF if onclick is executed?

You can use this simple code:

<a href="" onclick="return false;">add new action</a><br>

Making Maven run all tests, even when some fail

Can you test with surefire 2.6 and either configure Surefire with <testFailureIgnore>true</testFailureIgnore>.

Or on the command line:

mvn install -Dmaven.test.failure.ignore=true

Serializing enums with Jackson

Finally I found solution myself.

I had to annotate enum with @JsonSerialize(using = OrderTypeSerializer.class) and implement custom serializer:

public class OrderTypeSerializer extends JsonSerializer<OrderType> {

  @Override
  public void serialize(OrderType value, JsonGenerator generator,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {

    generator.writeStartObject();
    generator.writeFieldName("id");
    generator.writeNumber(value.getId());
    generator.writeFieldName("name");
    generator.writeString(value.getName());
    generator.writeEndObject();
  }
}

Chaining multiple filter() in Django, is this a bug?

From Django docs :

To handle both of these situations, Django has a consistent way of processing filter() calls. Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects, but for multi-valued relations, they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.

  • It is clearly said that multiple conditions in a single filter() are applied simultaneously. That means that doing :
objs = Mymodel.objects.filter(a=True, b=False)

will return a queryset with raws from model Mymodel where a=True AND b=False.

  • Successive filter(), in some case, will provide the same result. Doing :
objs = Mymodel.objects.filter(a=True).filter(b=False)

will return a queryset with raws from model Mymodel where a=True AND b=False too. Since you obtain "first" a queryset with records which have a=True and then it's restricted to those who have b=False at the same time.

  • The difference in chaining filter() comes when there are multi-valued relations, which means you are going through other models (such as the example given in the docs, between Blog and Entry models). It is said that in that case (...) they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.

Which means that it applies the successives filter() on the target model directly, not on previous filter()

If I take the example from the docs :

Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)

remember that it's the model Blog that is filtered, not the Entry. So it will treat the 2 filter() independently.

It will, for instance, return a queryset with Blogs, that have entries that contain 'Lennon' (even if they are not from 2008) and entries that are from 2008 (even if their headline does not contain 'Lennon')

THIS ANSWER goes even further in the explanation. And the original question is similar.

How to cancel an $http request in AngularJS?

This enhances the accepted answer by decorating the $http service with an abort method as follows ...

'use strict';
angular.module('admin')
  .config(["$provide", function ($provide) {

$provide.decorator('$http', ["$delegate", "$q", function ($delegate, $q) {
  var getFn = $delegate.get;
  var cancelerMap = {};

  function getCancelerKey(method, url) {
    var formattedMethod = method.toLowerCase();
    var formattedUrl = encodeURI(url).toLowerCase().split("?")[0];
    return formattedMethod + "~" + formattedUrl;
  }

  $delegate.get = function () {
    var cancelerKey, canceler, method;
    var args = [].slice.call(arguments);
    var url = args[0];
    var config = args[1] || {};
    if (config.timeout == null) {
      method = "GET";
      cancelerKey = getCancelerKey(method, url);
      canceler = $q.defer();
      cancelerMap[cancelerKey] = canceler;
      config.timeout = canceler.promise;
      args[1] = config;
    }
    return getFn.apply(null, args);
  };

  $delegate.abort = function (request) {
    console.log("aborting");
    var cancelerKey, canceler;
    cancelerKey = getCancelerKey(request.method, request.url);
    canceler = cancelerMap[cancelerKey];

    if (canceler != null) {
      console.log("aborting", cancelerKey);

      if (request.timeout != null && typeof request.timeout !== "number") {

        canceler.resolve();
        delete cancelerMap[cancelerKey];
      }
    }
  };

  return $delegate;
}]);
  }]);

WHAT IS THIS CODE DOING?

To cancel a request a "promise" timeout must be set. If no timeout is set on the HTTP request then the code adds a "promise" timeout. (If a timeout is set already then nothing is changed).

However, to resolve the promise we need a handle on the "deferred". We thus use a map so we can retrieve the "deferred" later. When we call the abort method, the "deferred" is retrieved from the map and then we call the resolve method to cancel the http request.

Hope this helps someone.

LIMITATIONS

Currently this only works for $http.get but you can add code for $http.post and so on

HOW TO USE ...

You can then use it, for example, on state change, as follows ...

rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
  angular.forEach($http.pendingRequests, function (request) {
        $http.abort(request);
    });
  });

How to Retrieve value from JTextField in Java Swing?

How do we retrieve a value from a text field?

mytestField.getText();

ActionListner example:

mytextField.addActionListener(this);

public void actionPerformed(ActionEvent evt) {
    String text = textField.getText();
    textArea.append(text + newline);
    textField.selectAll();
}

How to display items side-by-side without using tables?

Yes, divs and CSS are usually a better and easier way to place your HTML. There are many different ways to do this and it all depends on the context.

For instance, if you want to place an image to the right of your text, you could do it like so:

<p style="width: 500px;">
<img src="image.png" style="float: right;" />
This is some text
</p> 

And if you want to display multiple items side by side, float is also usually preferred.For example:

<div>
  <img src="image1.png" style="float: left;" />
  <img src="image2.png" style="float: left;" />
  <img src="image3.png" style="float: left;" />
</div>

Floating these images to the same side will have then laying next to each other for as long as you hava horizontal space.

Moment Js UTC to Local Time

I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!

Full Example on Codesandbox (DEMO):

https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js

Convert MySQL to SQlite

From list of converter tools I found Kexi. It is a UI tool to import from various DB servers (including MySQL) into SQLite. When importing some database (say from MySQL) it stores it in Kexi format. The Kexi format is the 'native' SQLite format. So simply copy the kexi file and have your data in sqlite format

assembly to compare two numbers

input password program
.modle small
.stack 100h
.data
s pasword db 34
input pasword db "enter pasword","$"
valid db ?
invalid db?
.code
mov ax, @ data 
mov db, ax
mov ah,09h
mov dx, offest s pasword
int 21h
mov ah, 01h
cmp al, s pasword
je v
jmp nv
v:
mov ah, 09h
mov dx, offset valid 
int 21h
nv:
mov ah, 09h
mov dx, offset invalid 
int 21h
mov ah, 04ch 
int 21
end 

jQuery DatePicker with today as maxDate

$(".datepicker").datepicker({maxDate: '0'});

This will set the maxDate to +0 days from the current date (i.e. today). See:

http://api.jqueryui.com/datepicker/#option-maxDate

Return list using select new in LINQ

What is being returned is an anonymous type so create a new class with 2 fields

class BasicProjectInfo {
   string name;
   string id;
}

and return new BasicProjectInfo(pro.ProjectName, pro.ProjectId);. You method in this case will return a List<BasicProjectInfo>

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

I needed the following bindings to get mine to work:

        <binding name="SI_PurchaseRequisition_ISBindingSSL">
          <security mode="Transport">
            <transport clientCredentialType="Basic" proxyCredentialType="None" realm="" />
          </security>
        </binding>

How to start MySQL server on windows xp

  1. Run the command prompt as admin and cd to bin directory of MySQL

    Generally it is (C:\Program Files\MySQL\mysql-5.6.36-winx64\bin)
    
  2. Run command : mysqld --install. (This command will install MySQL services and if services already installed it will prompt.)

  3. Run below commands to start and stop server

    To start : net start mysql

    To stop : net stop mysql

  4. Run mysql command.

  5. Enjoy !!

Why does git revert complain about a missing -m option?

By default git revert refuses to revert a merge commit as what that actually means is ambiguous. I presume that your HEAD is in fact a merge commit.

If you want to revert the merge commit, you have to specify which parent of the merge you want to consider to be the main trunk, i.e. what you want to revert to.

Often this will be parent number one, for example if you were on master and did git merge unwanted and then decided to revert the merge of unwanted. The first parent would be your pre-merge master branch and the second parent would be the tip of unwanted.

In this case you could do:

git revert -m 1 HEAD

Maven artifact and groupId naming

Weirdness is highly subjective, I just suggest to follow the official recommendation:

Guide to naming conventions on groupId, artifactId and version

  • groupId will identify your project uniquely across all projects, so we need to enforce a naming schema. It has to follow the package name rules, what means that has to be at least as a domain name you control, and you can create as many subgroups as you want. Look at More information about package names.

    eg. org.apache.maven, org.apache.commons

    A good way to determine the granularity of the groupId is to use the project structure. That is, if the current project is a multiple module project, it should append a new identifier to the parent's groupId.

    eg. org.apache.maven, org.apache.maven.plugins, org.apache.maven.reporting

  • artifactId is the name of the jar without version. If you created it then you can choose whatever name you want with lowercase letters and no strange symbols. If it's a third party jar you have to take the name of the jar as it's distributed.

    eg. maven, commons-math

  • version if you distribute it then you can choose any typical version with numbers and dots (1.0, 1.1, 1.0.1, ...). Don't use dates as they are usually associated with SNAPSHOT (nightly) builds. If it's a third party artifact, you have to use their version number whatever it is, and as strange as it can look.

    eg. 2.0, 2.0.1, 1.3.1

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

In Chrome, request with 'Content-Type:application/json' shows as Request PayedLoad and sends data as json object.

But request with 'Content-Type:application/x-www-form-urlencoded' shows Form Data and sends data as Key:Value Pair, so if you have array of object in one key it flats that key's value:

{ Id: 1, 
name:'john', 
phones:[{title:'home',number:111111,...},
        {title:'office',number:22222,...}]
}

sends

{ Id: 1, 
name:'john', 
phones:[object object]
phones:[object object]
}

Convert StreamReader to byte[]

You can use this code: You shouldn't use this code:

byte[] bytes = streamReader.CurrentEncoding.GetBytes(streamReader.ReadToEnd());

Please see the comment to this answer as to why. I will leave the answer, so people know about the problems with this approach, because I didn't up till now.

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

https://groups.google.com/forum/#!topic/google-appengine-stackoverflow/QZGJg2tlfA4

From what I've found online, this is a bug introduced in JDK 1.7.0_45. I've read it will be fixed in the next release of Java, but it's not out yet. Supposedly, it was fixed in 1.7.0_60b01, but I can't find where to download it and 1.7.0_60b02 re-introduces the bug.

I managed to get around the problem by reverting back to JDK 1.7.0_25. Probably not the solution you wanted, but it's the only way I've been able to get it working. Don't forget add JDK 1.7.0_25 in Eclipse after installing the JDK.

Please DO NOT REPLY directly to this email but go to StackOverflow: Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

"Items collection must be empty before using ItemsSource."

I had the same error. The problem was this extra symbol ">" added by mistake between the tags </ComboBox.SelectedValue> and </ComboBox>:

<ComboBox 
   ItemsSource="{Binding StatusTypes}"
   DisplayMemberPath="StatusName"
   SelectedValuePath="StatusID">
   <ComboBox.SelectedValue>
      <Binding Path="StatusID"/>
   </ComboBox.SelectedValue>
   >
</ComboBox>

and here is the correct code:

<ComboBox 
   ItemsSource="{Binding StatusTypes}"
   DisplayMemberPath="StatusName"
   SelectedValuePath="StatusID">
   <ComboBox.SelectedValue>
      <Binding Path="StatusID"/>
   </ComboBox.SelectedValue>
</ComboBox>

Reverse engineering from an APK file to a project

Yes, you can get your project back. Just rename the yourproject.apk file to yourproject.zip, and you will get all the files inside that ZIP file. We are changing the file extension from .apk to .zip. From that ZIP file, extract the classes.dex file and decompile it by following way.

First, you need a tool to extract all the (compiled) classes on the DEX to a JAR. There's one called dex2jar, which is made by a Chinese student.

Then, you can use JD-GUI to decompile the classes in the JAR to source code. The resulting source code should be quite readable, as dex2jar applies some optimizations.

$rootScope.$broadcast vs. $scope.$emit

They are not doing the same job: $emit dispatches an event upwards through the scope hierarchy, while $broadcast dispatches an event downwards to all child scopes.

Detect Safari using jQuery

I use to detect Apple browser engine, this simple JavaScript condition:

 navigator.vendor.startsWith('Apple')

Wrap text in <td> tag

Actually wrapping of text happens automatically in tables. The blunder people commit while testing is to hypothetically assume a long string like "ggggggggggggggggggggggggggggggggggggggggggggggg" and complain that it doesn't wrap. Practically there is no word in English that is this long and even if there is, there is a faint chance that it will be used within that <td>.

Try testing with sentences like "Counterposition is superstitious in predetermining circumstances".

NodeJS - What does "socket hang up" actually mean?

This error also can happen when working with http.request, probably your request is not finished yet.

Example:

const req = https.request(options, res => {})

And you always need to add this line: req.end() With this function we will order to finish sending request.

As in documentation is said:

With http.request() one must always call req.end() to signify the end of the request - even if there is no data being written to the request body.

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Is there a decorator to simply cache function return values?

It sounds like you're not asking for a general-purpose memoization decorator (i.e., you're not interested in the general case where you want to cache return values for different argument values). That is, you'd like to have this:

x = obj.name  # expensive
y = obj.name  # cheap

while a general-purpose memoization decorator would give you this:

x = obj.name()  # expensive
y = obj.name()  # cheap

I submit that the method-call syntax is better style, because it suggests the possibility of expensive computation while the property syntax suggests a quick lookup.

[Update: The class-based memoization decorator I had linked to and quoted here previously doesn't work for methods. I've replaced it with a decorator function.] If you're willing to use a general-purpose memoization decorator, here's a simple one:

def memoize(function):
  memo = {}
  def wrapper(*args):
    if args in memo:
      return memo[args]
    else:
      rv = function(*args)
      memo[args] = rv
      return rv
  return wrapper

Example usage:

@memoize
def fibonacci(n):
  if n < 2: return n
  return fibonacci(n - 1) + fibonacci(n - 2)

Another memoization decorator with a limit on the cache size can be found here.

Specifying number of decimal places in Python

To calculate tax, you could use round (after all, that's what the restaurant does):

def calc_tax(mealPrice):  
    tax = round(mealPrice*.06,2)
    return tax

To display the data, you could use a multi-line string, and the string format method:

def display_data(mealPrice, tax):
    total=round(mealPrice+tax,2)
    print('''\
Your Meal Price is {m:=5.2f}
Tax                {x:=5.2f}
Total              {t:=5.2f}
'''.format(m=mealPrice,x=tax,t=total))

Note the format method was introduced in Python 2.6, for earlier versions you'll need to use old-style string interpolation %:

    print('''\
Your Meal Price is %5.2f
Tax                %5.2f
Total              %5.2f
'''%(mealPrice,tax,total))

Then

mealPrice=input_meal()
tax=calc_tax(mealPrice)
display_data(mealPrice,tax)

yields:

# Enter the meal subtotal: $43.45
# Your Meal Price is 43.45
# Tax                 2.61
# Total              46.06

Chart.js canvas resize

I tried to Resize Canvas using jQuery but it din't work well. I think CSS3 is the best option you can try on, if you want on hover zooming at certain level.

Following hover option from other codepan link:

.style_prevu_kit:hover{
    z-index: 2;
    -webkit-transition: all 200ms ease-in;
    -webkit-transform: scale(1.5);
    -ms-transition: all 200ms ease-in;
    -ms-transform: scale(1.5);   
    -moz-transition: all 200ms ease-in;
    -moz-transform: scale(1.5);
    transition: all 200ms ease-in;
    transform: scale(1.5);
}

Follow my codepan link:

https://codepen.io/hitman0775/pen/XZZzqN

Windows Forms ProgressBar: Easiest way to start/stop marquee?

Use a progress bar with the style set to Marquee. This represents an indeterminate progress bar.

myProgressBar.Style = ProgressBarStyle.Marquee;

You can also use the MarqueeAnimationSpeed property to set how long it will take the little block of color to animate across your progress bar.

Difference between char* and const char*?

Actually, char* name is not a pointer to a constant, but a pointer to a variable. You might be talking about this other question.

What is the difference between char * const and const char *?

in_array multiple values

As a developer, you should probably start learning set operations (difference, union, intersection). You can imagine your array as one "set", and the keys you are searching for the other.

Check if ALL needles exist

function in_array_all($needles, $haystack) {
   return empty(array_diff($needles, $haystack));
}

echo in_array_all( [3,2,5], [5,8,3,1,2] ); // true, all 3, 2, 5 present
echo in_array_all( [3,2,5,9], [5,8,3,1,2] ); // false, since 9 is not present

Check if ANY of the needles exist

function in_array_any($needles, $haystack) {
   return !empty(array_intersect($needles, $haystack));
}

echo in_array_any( [3,9], [5,8,3,1,2] ); // true, since 3 is present
echo in_array_any( [4,9], [5,8,3,1,2] ); // false, neither 4 nor 9 is present

JavaScript Loading Screen while page loads

To build further upon the ajax part which you may or may not use (from the comments)

a simple way to load another page and replace it with your current one is:

<script>
    $(document).ready( function() {
        $.ajax({
            type: 'get',
            url: 'http://pageToLoad.from',
            success: function(response) {
                // response = data which has been received and passed on to the 'success' function.
                $('body').html(response);
            }
        });
    });
<script>

Is there a need for range(len(a))?

Short answer: mathematically speaking, no, in practical terms, yes, for example for Intentional Programming.

Technically, the answer would be "no, it's not needed" because it's expressible using other constructs. But in practice, I use for i in range(len(a) (or for _ in range(len(a)) if I don't need the index) to make it explicit that I want to iterate as many times as there are items in a sequence without needing to use the items in the sequence for anything.

So: "Is there a need?"? — yes, I need it to express the meaning/intent of the code for readability purposes.

See also: https://en.wikipedia.org/wiki/Intentional_programming

And obviously, if there is no collection that is associated with the iteration at all, for ... in range(len(N)) is the only option, so as to not resort to i = 0; while i < N; i += 1 ...

List of <p:ajax> events

As the list of possible events is not tied to p:ajax itself but to the component it is used with, you'll have to ask the component for which ajax events it supports.

There are multiple ways to determine the ajax events for a given component:

1) Ask the component in xhtml:

You can output the list directly in xhtml by binding that component to a request scoped variable and printing the eventNames property:

<p:autoComplete binding="#{ac}"></p:autoComplete>
<h:outputText value="#{ac.eventNames}" />

This outputs

[blur, change, valueChange, click, dblclick, focus, keydown, keypress, keyup,
 mousedown, mousemove, mouseout, mouseover, mouseup, select, itemSelect,
 itemUnselect, query, moreText, clear]

2) Ask the component in java code:

Figure out the component implementation class and invoke its' implementation of javax.faces.component.UIComponentBase.getEventNames() method:

import javax.faces.component.UIComponentBase;

public class SomeTest {

    public static void main(String[] args) {
        dumpEvents(new org.primefaces.component.inputtext.InputText());
        dumpEvents(new org.primefaces.component.autocomplete.AutoComplete());
        dumpEvents(new org.primefaces.component.datatable.DataTable());
    }

    private static void dumpEvents(UIComponentBase comp) {
        System.out.println(
                comp + ":\n\tdefaultEvent: " + comp.getDefaultEventName() + ";\n\tEvents: " + comp.getEventNames());
    }

}

This outputs:

org.primefaces.component.inputtext.InputText@239963d8:
    defaultEvent: valueChange;
    Events: [blur, change, valueChange, click, dblclick, focus, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup, select]
org.primefaces.component.autocomplete.AutoComplete@72d818d1:
    defaultEvent: valueChange;
    Events: [blur, change, valueChange, click, dblclick, focus, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup, select, itemSelect, itemUnselect, query, moreText, clear]
org.primefaces.component.datatable.DataTable@614ddd49:
    defaultEvent: null;
    Events: [rowUnselect, colReorder, tap, rowEditInit, toggleSelect, cellEditInit, sort, rowToggle, cellEdit, rowSelectRadio, filter, cellEditCancel, rowSelect, contextMenu, taphold, rowReorder, colResize, rowUnselectCheckbox, rowDblselect, rowEdit, page, rowEditCancel, virtualScroll, rowSelectCheckbox]

3) 'rtfm' ;-)

Best option is to look into the documentation of the particular component in use as hopefully provided by the component developers, not limited to PrimeFaces btw. (p:ajax can be attached to any component providing ajax behaviors).

The advantage over previous suggestions is that the documentation not only provides the event names, but also enhanced description of the event potentially enriched with an event type class that can be caught by a listener.

For example the org.primefaces.event.SelectEvent in case of

<p:ajax event="itemSelect" listener="#{anyBean.onItemSelect}"/>

and listener method signature public void onItemSelect(SelectEvent) provides additional event contextual data.

Where there is no explicit list of ajax events on a compoment in the PrimeFaces documentation, the list of on* javascript callbacks can be used as events by removing the 'on' and using the remainder as an event name. The other answers in this question provides help on these plain dom events too.

How do you use variables in a simple PostgreSQL script?

Building on @nad2000's answer and @Pavel's answer here, this is where I ended up for my Flyway migration scripts. Handling for scenarios where the database schema was manually modified.

DO $$
BEGIN
    IF NOT EXISTS(
        SELECT TRUE FROM pg_attribute 
        WHERE attrelid = (
            SELECT c.oid
            FROM pg_class c
            JOIN pg_namespace n ON n.oid = c.relnamespace
            WHERE 
                n.nspname = CURRENT_SCHEMA() 
                AND c.relname = 'device_ip_lookups'
            )
        AND attname = 'active_date'
        AND NOT attisdropped
        AND attnum > 0
        )
    THEN
        RAISE NOTICE 'ADDING COLUMN';        
        ALTER TABLE device_ip_lookups
            ADD COLUMN active_date TIMESTAMP;
    ELSE
        RAISE NOTICE 'SKIPPING, COLUMN ALREADY EXISTS';
    END IF;
END $$;

LocalDate to java.util.Date and vice versa simplest conversion?

Date to LocalDate

Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

LocalDate to Date

LocalDate localDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

Tips for using Vim as a Java IDE?

  • How do I invoke a maven task without leaving vi?

    Maven is no different than any other shell command:

    :!mvn

    You can :set makeprg=mvn if you already have a favourite key mapping for :make.

  • Can I get code completion?

    Yes, eclim is great, a bridge between vim's editing efficiency and Eclipse's Java language-specific awareness.

    <C-n> and <C-p> are not-so-great, but amazingly helpful.

  • How's the syntax highlighting?

    More than good enough for a regex-based highligher.

You may want to consider tools for other vim+java purposes, like code templates (snippetEmu—default snippets suck, but customizability shines), searching for usages and going to declarations (eclim, grep, ctags), generating getters and setters (java_getset, or eclim), automatic imports (eclim). You might also need a java shell for quick experiments (the BeanShell, a.k.a. bsh).

C# Checking if button was clicked

i am very new to this website. I am an undergraduate student, doing my Bachelor Of Computer Application. I am doing a simple program in Visual Studio using C# and I came across the same problem, how to check whether a button is clicked? I wanted to do this,

if(-button1 is clicked-) then
{
this should happen;
}
if(-button2 is clicked-) then
{
this should happen;
}

I didn't know what to do, so I tried searching for the solution in the internet. I got many solutions which didn't help me. So, I tried something on my own and did this,

int i;
private void button1_Click(object sender, EventArgs e)
        {
            i = 1;
            label3.Text = "Principle";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Simple Interest";
        }


private void button2_Click(object sender, EventArgs e)
        {
            i = 2;
            label3.Text = "SI";
            label4.Text = "Rate";
            label5.Text = "Time";
            label6.Text = "Principle";
        }
private void button5_Click(object sender, EventArgs e)
        {

            try
            {
                if (i == 1)
                {
                    si = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text)) / 100;
                    textBox4.Text = Convert.ToString(si);
                }
                if (i == 2)
                {
                    p = (Convert.ToInt32(textBox1.Text) * 100) / (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text));
                    textBox4.Text = Convert.ToString(p);
                }

I declared a variable "i" and assigned it with different values in different buttons and checked the value of i in the if function. It worked. Give your suggestions if any. Thank you.

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

I resolved the same issue by running Workbench as administrator.

...I guess it's because of restrictions on company computers, in my case...

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

I had the same issue until i close teamviewer running on my pc. Then it worked fine!

Select distinct using linq

myList.GroupBy(test => test.id)
      .Select(grp => grp.First());

Edit: as getting this IEnumerable<> into a List<> seems to be a mystery to many people, you can simply write:

var result = myList.GroupBy(test => test.id)
                   .Select(grp => grp.First())
                   .ToList();

But one is often better off working with the IEnumerable rather than IList as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)

The flipside to this advice is that each time you enumerate such an IEnumerable the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable or to realize it into a List, Set, Dictionary or whatnot.

curl : (1) Protocol https not supported or disabled in libcurl

Looks like there are so many Answers already but the issue I faced was with double quotes. There is a difference in between:

and

"

Changing the 1 st double quote to the second worked for me, below is the sample curl:

curl -X PUT -u xxx:xxx -T test.txt "https://test.com/test/test.txt"

How to ignore the first line of data when processing CSV data?

Python 3.X

Handles UTF8 BOM + HEADER

It was quite frustrating that the csv module could not easily get the header, there is also a bug with the UTF-8 BOM (first char in file). This works for me using only the csv module:

import csv

def read_csv(self, csv_path, delimiter):
    with open(csv_path, newline='', encoding='utf-8') as f:
        # https://bugs.python.org/issue7185
        # Remove UTF8 BOM.
        txt = f.read()[1:]

    # Remove header line.
    header = txt.splitlines()[:1]
    lines = txt.splitlines()[1:]

    # Convert to list.
    csv_rows = list(csv.reader(lines, delimiter=delimiter))

    for row in csv_rows:
        value = row[INDEX_HERE]

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

I know this is an old question, but rather than adding the snapin which is apparently unsupported, I just looked at the EMS shortcut properties and copied those commands.

The full shortcut target is:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"

So I put the following at the start of my script and it seemed to function as expected:

. 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto

Notes:

  • Has to be run in 64bit PS
  • This was tested on a server with just the Management Tools installed. It automatically connected to our existing Exchange infrastructure.
  • No extensive testing has been done, so I do not know if this method is viable. I will edit this post if I run into any issues.

Git push rejected after feature branch rebase

My way of avoiding the force push is to create a new branch and continuing work on that new branch and after some stability, remove the old branch that was rebased:

  • Rebasing the checked out branch locally
  • Branching from the rebased branch to a new branch
  • Pushing that branch as a new branch to remote. and deleting the old branch on remote

Get decimal portion of a number with JavaScript

I am using:

var n = -556.123444444;
var str = n.toString();
var decimalOnly = 0;

if( str.indexOf('.') != -1 ){ //check if has decimal
    var decimalOnly = parseFloat(Math.abs(n).toString().split('.')[1]);
}

Input: -556.123444444

Result: 123444444

jQuery Ajax POST example with PHP

Handling Ajax errors and loader before submit and after submitting success shows an alert boot box with an example:

var formData = formData;

$.ajax({
    type: "POST",
    url: url,
    async: false,
    data: formData, // Only input
    processData: false,
    contentType: false,
    xhr: function ()
    {
        $("#load_consulting").show();
        var xhr = new window.XMLHttpRequest();

        // Upload progress
        xhr.upload.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = (evt.loaded / evt.total) * 100;
                $('#addLoad .progress-bar').css('width', percentComplete + '%');
            }
        }, false);

        // Download progress
        xhr.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
            }
        }, false);
        return xhr;
    },
    beforeSend: function (xhr) {
        qyuraLoader.startLoader();
    },
    success: function (response, textStatus, jqXHR) {
        qyuraLoader.stopLoader();
        try {
            $("#load_consulting").hide();

            var data = $.parseJSON(response);
            if (data.status == 0)
            {
                if (data.isAlive)
                {
                    $('#addLoad .progress-bar').css('width', '00%');
                    console.log(data.errors);
                    $.each(data.errors, function (index, value) {
                        if (typeof data.custom == 'undefined') {
                            $('#err_' + index).html(value);
                        }
                        else
                        {
                            $('#err_' + index).addClass('error');

                            if (index == 'TopError')
                            {
                                $('#er_' + index).html(value);
                            }
                            else {
                                $('#er_TopError').append('<p>' + value + '</p>');
                            }
                        }
                    });
                    if (data.errors.TopError) {
                        $('#er_TopError').show();
                        $('#er_TopError').html(data.errors.TopError);
                        setTimeout(function () {
                            $('#er_TopError').hide(5000);
                            $('#er_TopError').html('');
                        }, 5000);
                    }
                }
                else
                {
                    $('#headLogin').html(data.loginMod);
                }
            } else {
                //document.getElementById("setData").reset();
                $('#myModal').modal('hide');
                $('#successTop').show();
                $('#successTop').html(data.msg);
                if (data.msg != '' && data.msg != "undefined") {

                    bootbox.alert({closeButton: false, message: data.msg, callback: function () {
                            if (data.url) {
                                window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                            } else {
                                location.reload(true);
                            }
                        }});
                } else {
                    bootbox.alert({closeButton: false, message: "Success", callback: function () {
                        if (data.url) {
                            window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                        } else {
                            location.reload(true);
                        }
                    }});
                }

            }
        }
        catch (e) {
            if (e) {
                $('#er_TopError').show();
                $('#er_TopError').html(e);
                setTimeout(function () {
                    $('#er_TopError').hide(5000);
                    $('#er_TopError').html('');
                }, 5000);
            }
        }
    }
});

Form Submission without page refresh

<!-- index.php -->
    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    </head>
    <body>
    <form id="myForm">
        <input type="text" name="fname" id="fname"/>
        <input type="submit" name="click" value="button" />
    </form>
    <script>
    $(document).ready(function(){

         $(function(){
            $("#myForm").submit(function(event){
                event.preventDefault();
                $.ajax({
                    method: 'POST',
                    url: 'submit.php',
                    dataType: "json",
                    contentType: "application/json",
                    data : $('#myForm').serialize(),
                    success: function(data){
                        alert(data);
                    },
                    error: function(xhr, desc, err){
                        console.log(err);
                    }
                });
            });
        });
    });
    </script>
    </body>
    </html>
<!-- submit.php -->
<?php
$value ="call";
header('Content-Type: application/json');
echo json_encode($value);
?>

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I found this arrow(start, end) function on MATLAB Central which is perfect for this purpose of drawing vectors with true magnitude and direction.

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

In my humble experience with postgres 9.6, cascade delete doesn't work in practice for tables that grow above a trivial size.

  • Even worse, while the delete cascade is going on, the tables involved are locked so those tables (and potentially your whole database) is unusable.
  • Still worse, it's hard to get postgres to tell you what it's doing during the delete cascade. If it's taking a long time, which table or tables is making it slow? Perhaps it's somewhere in the pg_stats information? It's hard to tell.

Multiple types were found that match the controller named 'Home'

In MVC4 & MVC5 It is little bit different, use following

/App_Start/RouteConfig.cs

namespace MyNamespace
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                namespaces:  new[] {"MyNamespace.Controllers"}
            );
        }
    }
}

and in Areas

context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional },
                new[] { "MyNamespace.Areas.Admin.Controllers" }
            );

insert multiple rows into DB2 database

None of the above worked for me, the only one working was

insert into tableName  
select 11, 'BALOO' from sysibm.sysdummy1 union all
select 22, nullif('','') AS nullColumn from sysibm.sysdummy1

The nullif is used since it is not possible to pass null in the select statement otherwise.

Bin size in Matplotlib (Histogram)

I like things to happen automatically and for bins to fall on "nice" values. The following seems to work quite well.

import numpy as np
import numpy.random as random
import matplotlib.pyplot as plt
def compute_histogram_bins(data, desired_bin_size):
    min_val = np.min(data)
    max_val = np.max(data)
    min_boundary = -1.0 * (min_val % desired_bin_size - min_val)
    max_boundary = max_val - max_val % desired_bin_size + desired_bin_size
    n_bins = int((max_boundary - min_boundary) / desired_bin_size) + 1
    bins = np.linspace(min_boundary, max_boundary, n_bins)
    return bins

if __name__ == '__main__':
    data = np.random.random_sample(100) * 123.34 - 67.23
    bins = compute_histogram_bins(data, 10.0)
    print(bins)
    plt.hist(data, bins=bins)
    plt.xlabel('Value')
    plt.ylabel('Counts')
    plt.title('Compute Bins Example')
    plt.grid(True)
    plt.show()

The result has bins on nice intervals of bin size.

[-70. -60. -50. -40. -30. -20. -10.   0.  10.  20.  30.  40.  50.  60.]

computed bins histogram

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

If all the other answers do not work for you check the config.inc.php for the following:

$cfg['Servers'][$i]['host'] = '127.0.0.1';

…and add the port of MySQL set in your XAMPP as shown below:

$cfg['Servers'][$i]['host'] = '127.0.0.1:3307';

Stop MySQL from XAMPP and restart MySQL.

Open a fresh page for http://localhost:8012/phpmyadmin/ and check.

Cannot catch toolbar home button click event

In my case I had to put the icon using:

toolbar.setNavigationIcon(R.drawable.ic_my_home);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

And then listen to click events with default onOptionsItemSelected and android.R.id.home id

How to disable sort in DataGridView?

I was looking for a way to disable my already existing DataGridView and came across several answers. Oddly enough, the first few results on google were some very old topics. This being the earliest one of them, I decide to put my answer here.

private void dgvDetails_ColumnStateChanged(object sender, DataGridViewColumnStateChangedEventArgs e)
{
    e.Column.SortMode = DataGridViewColumnSortMode.NotSortable;
}

The description when you click on ColumStateChanged in the properties window is:

"Occurs when a column changes state, such as gaining or loosing focus"

Granted there are many ways to do this but I thought I'd add this one here. Can't say I found it anywhere else but then again I only read the first 5 topics I found.

Import JavaScript file and call functions using webpack, ES6, ReactJS

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

Or if you prefer, place the entire module's contents under a common namespace:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

export default function log(message) {
  console.log(message);
}

This can now be used like this:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

You don't have to call it log when you import it, you could actually call it whatever you want:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';

How I can check whether a page is loaded completely or not in web driver?

Simple ready2use snippet, working perfectly for me

static void waitForPageLoad(WebDriver wdriver) {
    WebDriverWait wait = new WebDriverWait(wdriver, 60);

    Predicate<WebDriver> pageLoaded = new Predicate<WebDriver>() {

        @Override
        public boolean apply(WebDriver input) {
            return ((JavascriptExecutor) input).executeScript("return document.readyState").equals("complete");
        }

    };
    wait.until(pageLoaded);
}

Best way to retrieve variable values from a text file?

How reliable is your format? If the seperator is always exactly ': ', the following works. If not, a comparatively simple regex should do the job.

As long as you're working with fairly simple variable types, Python's eval function makes persisting variables to files surprisingly easy.

(The below gives you a dictionary, btw, which you mentioned was one of your prefered solutions).

def read_config(filename):
    f = open(filename)
    config_dict = {}
    for lines in f:
        items = lines.split(': ', 1)
        config_dict[items[0]] = eval(items[1])
    return config_dict

Cross-Domain Cookies

There's no such thing as cross domain cookies. You could share a cookie between foo.example.com and bar.example.com but never between example.com and example2.com and that's for security reasons.

How to install latest version of git on CentOS 7.x/6.x

You can use WANDisco's CentOS repository to install Git 2.x: for CentOS 6, for CentOS 7

  1. Install WANDisco repo package:

    yum install http://opensource.wandisco.com/centos/6/git/x86_64/wandisco-git-release-6-1.noarch.rpm
    - or -
    yum install http://opensource.wandisco.com/centos/7/git/x86_64/wandisco-git-release-7-1.noarch.rpm
    - or -
    yum install http://opensource.wandisco.com/centos/7/git/x86_64/wandisco-git-release-7-2.noarch.rpm
    
  2. Install the latest version of Git 2.x:

    yum install git
    
  3. Verify the version of Git that was installed:

    git --version
    

As of 02 Mar. 2020, the latest available version from WANDisco is 2.22.0.

How to write asynchronous functions for Node.js

I've dealing too many hours for such task in for node.js. I'm mainly front-end guy.

I find this quite important, because all node methods asyncronous deal with callback, and transform it into Promise is better to handle it.

I Just want to show a possible outcome, more lean and readable. Using ECMA-6 with async you can write it like this.

 async function getNameFiles (dirname) {
  return new Promise((resolve, reject) => {
    fs.readdir(dirname, (err, filenames) => {
      err !== (undefined || null) ? reject(err) : resolve(filenames)
    })
  })
}

the (undefined || null) is for repl (read event print loop) scenarios, using undefined also work.

Wait until an HTML5 video loads

You don't really need jQuery for this as there is a Media API that provides you with all you need.

var video = document.getElementById('myVideo');
video.src = 'my_video_' + value + '.ogg';
video.load();

The Media API also contains a load() method which: "Causes the element to reset and start selecting and loading a new media resource from scratch."

(Ogg isn't the best format to use, as it's only supported by a limited number of browsers. I'd suggest using WebM and MP4 to cover all major browsers - you can use the canPlayType() function to decide on which one to play).

You can then wait for either the loadedmetadata or loadeddata (depending on what you want) events to fire:

video.addEventListener('loadeddata', function() {
   // Video is loaded and can be played
}, false);

What key shortcuts are to comment and uncomment code?

Keyboard accelerators are configurable. You can find out which keyboard accelerators are bound to a command in Tools -> Options on the Environment -> Keyboard page.

These commands are named Edit.CommentSelection and Edit.UncommentSelection.

(With my settings, these are bound to Ctrl+K, Ctrl+C and Ctrl+K, Ctrl+U. I would guess that these are the defaults, at least in the C++ defaults, but I don't know for sure. The best way to find out is to check your settings.)

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

How to run a python script from IDLE interactive shell?

you can do it by two ways

  • import file_name

  • exec(open('file_name').read())

but make sure that file should be stored where your program is running

How do I delete NuGet packages that are not referenced by any project in my solution?

One NuGet package can reference another NuGet package. So, please be very careful about inter-package dependencies. I just uninstalled a Google map package and it subsequently uninstalled underlying packages like Newtonsoft, Entity Framework, etc.

So, manually deleting particular package from packages folder would be safer.

Curly braces in string in PHP

I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.

$periods=array('hour', 'day', 'month');
foreach ($periods as $period)
{
    $this->{'value_'.$period}=1;
}

This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.

You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.

class timevalues
{
                             // Database table values:
    public $value_hour;      // maps to values.value_hour
    public $value_day;       // maps to values.value_day
    public $value_month;     // maps to values.value_month
    public $values=array();

    public function __construct()
    {
        $this->value_hour=0;
        $this->value_day=0;
        $this->value_month=0;
        $this->values=array(
            'hour'=>$this->value_hour,
            'day'=>$this->value_day,
            'month'=>$this->value_month,
        );
    }
}

How to reference image resources in XAML?

If you've got an image in the Icons folder of your project and its build action is "Resource", you can refer to it like this:

<Image Source="/Icons/play_small.png" />

That's the simplest way to do it. This is the only way I could figure doing it purely from the resource standpoint and no project files:

var resourceManager = new ResourceManager(typeof (Resources));
var bitmap = resourceManager.GetObject("Search") as System.Drawing.Bitmap;

var memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Position = 0;

var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();

this.image1.Source = bitmapImage;

How should I tackle --secure-file-priv in MySQL?

The thing that worked for me:

  1. Put your file inside of the folder specified in secure-file-priv.

    To find that type:

    mysql> show variables like "secure_file_priv";  
    
  2. Check if you have local_infile = 1.

    Do that typing:

    mysql> show variables like "local_infile";
    

    If you get:

    +---------------+-------+
    | Variable_name | Value |
    +---------------+-------+
    | local_infile  | OFF   |
    +---------------+-------+
    

    Then set it to one typing:

    mysql> set global local_infile = 1;
    
  3. Specify the full path for your file. In my case:

    mysql> load data infile "C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/file.txt" into table test;
    

Html- how to disable <a href>?

I created a button...

This is where you've gone wrong. You haven't created a button, you've created an anchor element. If you had used a button element instead, you wouldn't have this problem:

<button type="button" data-toggle="modal" data-target="#myModal" data-role="disabled">
    Connect
</button>

If you are going to continue using an a element instead, at the very least you should give it a role attribute set to "button" and drop the href attribute altogether:

<a role="button" ...>

Once you've done that you can introduce a piece of JavaScript which calls event.preventDefault() - here with event being your click event.

React.createElement: type is invalid -- expected a string

// @flow

import React from 'react';
import { styleLocal } from './styles';
import {
  View,
  Text,
  TextInput,
  Image,
} from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';

export default React.forwardRef((props, ref) => {
const { onSeachClick, onChangeTextSearch , ...otherProps } = props;

  return (
        <View style={styleLocal.sectionStyle}>
        <TouchableOpacity onPress={onSeachClick}>
            <Image                              
                    source={require('../../assets/imgs/search.png')}
                    style={styleLocal.imageStyle} />
                </TouchableOpacity>
            <TextInput
                style={{ flex: 1, fontSize: 18 }}
                placeholder="Search Here"
                underlineColorAndroid="transparent"
                onChangeText={(text) => { onChangeTextSearch(text) }}
            />
        </View>
  );
});
 import IGPSSearch from '../../components/IGPSSearch';
<Search onSeachClick={onSeachClick} onChangeTextSearch= {onChangeTextSearch}> </Search>

How to run a single test with Mocha?

For those who are looking to run a single file but they cannot make it work, what worked for me was that I needed to wrap my test cases in a describe suite as below and then use the describe title e.g. 'My Test Description' as pattern.

describe('My Test Description', () => {
  it('test case 1', () => {
    // My test code
  })
  it('test case 2', () => {
  // My test code
  })
})

then run

yarn test -g "My Test Description"

or

npm run test -g "My Test Description"

How do I configure the proxy settings so that Eclipse can download new plugins?

Just to add to the thread as a POSSIBLE solution, I faced a similar issue when developing on a Linux system that was behind a company firewall. However, using a Windows XP machine, Eclipse was able to access different update sites just fine as both the manual and native network connection providers worked just fine using the company proxy.

After stumbling around for some time, I came across a discussion about using NTLMv2 and an implementation to be found at http://cntlm.sourceforge.net/. To whomever posted this, I give much credit to as it helped me get past the issue running on Linux. As a side note, I was using Eclipse 3.6.2 / Helios on both the Linux and Windows distros.

Best of luck on finding a solution!

Just what is an IntPtr exactly?

Well this is the MSDN page that deals with IntPtr.

The first line reads:

A platform-specific type that is used to represent a pointer or a handle.

As to what a pointer or handle is the page goes on to state:

The IntPtr type can be used by languages that support pointers, and as a common means of referring to data between languages that do and do not support pointers.

IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.

A pointer is a reference to an area of memory that holds some data you are interested in.

A handle can be an identifier for an object and is passed between methods/classes when both sides need to access that object.

SQLDataReader Row Count

 DataTable dt = new DataTable();
 dt.Load(reader);
 int numRows= dt.Rows.Count;

Android Viewpager as Image Slide Gallery

Image Viewer with ViewPager Implementation, check this project https://github.com/chiuki/android-swipe-image-viewer

Refer this discussion also Swiping images (not layouts) with viewpager

Node.js: How to send headers with form data using request module?

This should work.

var url = 'http://<your_url_here>';
var headers = { 
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
    'Content-Type' : 'application/x-www-form-urlencoded' 
};
var form = { username: 'user', password: '', opaque: 'someValue', logintype: '1'};

request.post({ url: url, form: form, headers: headers }, function (e, r, body) {
    // your callback body
});

Invoke a second script with arguments from a script

Here's an answer covering the more general question of calling another PS script from a PS script, as you may do if you were composing your scripts of many little, narrow-purpose scripts.

I found it was simply a case of using dot-sourcing. That is, you just do:

# This is Script-A.ps1

. ./Script-B.ps1 -SomeObject $variableFromScriptA -SomeOtherParam 1234;

I found all the Q/A very confusing and complicated and eventually landed upon the simple method above, which is really just like calling another script as if it was a function in the original script, which I seem to find more intuitive.

Dot-sourcing can "import" the other script in its entirety, using:

. ./Script-B.ps1

It's now as if the two files are merged.

Ultimately, what I was really missing is the notion that I should be building a module of reusable functions.

Git: add vs push vs commit

git add selects changes

git commit records changes LOCALLY

git push shares changes

How to get your Netbeans project into Eclipse

  1. Make sure you have sbt and run sbt eclipse from the project root directory.
  2. In eclipse, use File --> Import --> General --> Existing Projects into Workspace, selecting that same location, so that eclipse builds its project structure for the file structure having just been prepared by sbt.

Yarn: How to upgrade yarn version using terminal?

Since you already have yarn installed and only want to upgrade/update. you can simply use

yarn self-update

Find ref here https://yarnpkg.com/en/docs/cli/self-update

Getting reference to the top-most view/window in iOS application

UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
if (![NSStringFromClass([keyWindow class]) isEqualToString:@"UIWindow"]) {

    NSArray *windows = [UIApplication sharedApplication].windows;
    for (UIWindow *window in windows) {
        if ([NSStringFromClass([window class]) isEqualToString:@"UIWindow"]) {
            keyWindow = window;
            break;
        }
    }
}

Override browser form-filling and input highlighting with HTML/CSS

Add this CSS rule, and yellow background color will disapear. :)

input:-webkit-autofill {
    -webkit-box-shadow: 0 0 0px 1000px white inset;
}

How to add additional fields to form before submit?

Yes.You can try with some hidden params.

  $("#form").submit( function(eventObj) {
      $("<input />").attr("type", "hidden")
          .attr("name", "something")
          .attr("value", "something")
          .appendTo("#form");
      return true;
  });

Showing Difference between two datetime values in hours

var startTime = new TimeSpan(6, 0, 0); // 6:00 AM
var endTime = new TimeSpan(5, 30, 0); // 5:30 AM 
var hours24 = new TimeSpan(24, 0, 0);
var difference = endTime.Subtract(startTime); // (-00:30:00)
difference = (difference.Duration() != difference) ? hours24.Subtract(difference.Duration()) : difference; // (23:30:00)

can also add difference between the dates if we compare two different dates

new TimeSpan(24 * days, 0, 0)

Removing element from array in component state

Here is a way to remove the element from the array in the state using ES6 spread syntax.

onRemovePerson: (index) => {
  const data = this.state.data;
  this.setState({ 
    data: [...data.slice(0,index), ...data.slice(index+1)]
  });
}

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

Got stuck as I was trying to a go get ... I think it was related to git. Here is how was able to fix it ...

  1. I entered the following in terminal:

    sudo xcodebuild -license
    
  2. This will open the agreement. Go all the way to end and type "agree".

That takes care of go get issues.

It was quite interesting how unrelated things were.

Stack, Static, and Heap in C++

An advantage of GC in some situations is an annoyance in others; reliance on GC encourages not thinking much about it. In theory, waits until 'idle' period or until it absolutely must, when it will steal bandwidth and cause response latency in your app.

But you don't have to 'not think about it.' Just as with everything else in multithreaded apps, when you can yield, you can yield. So for example, in .Net, it is possible to request a GC; by doing this, instead of less frequent longer running GC, you can have more frequent shorter running GC, and spread out the latency associated with this overhead.

But this defeats the primary attraction of GC which appears to be "encouraged to not have to think much about it because it is auto-mat-ic."

If you were first exposed to programming before GC became prevalent and were comfortable with malloc/free and new/delete, then it might even be the case that you find GC a little annoying and/or are distrustful(as one might be distrustful of 'optimization,' which has had a checkered history.) Many apps tolerate random latency. But for apps that don't, where random latency is less acceptable, a common reaction is to eschew GC environments and move in the direction of purely unmanaged code (or god forbid, a long dying art, assembly language.)

I had a summer student here a while back, an intern, smart kid, who was weaned on GC; he was so adament about the superiorty of GC that even when programming in unmanaged C/C++ he refused to follow the malloc/free new/delete model because, quote, "you shouldn't have to do this in a modern programming language." And you know? For tiny, short running apps, you can indeed get away with that, but not for long running performant apps.

how to console.log result of this ajax call?

Ajax call error handler will be triggered if the call itself fails.

You are probably trying to get the error from server in case login credentials do not go through. In that case, you need to inspect the server response json object and display appropriate message.

e.preventDefault();
$.ajax(
{
    type: 'POST',
    url: requestURI,
    data: $(formLogin).serialize(),
    dataType: 'json',
    success: function(result){
        if(result.hasError == true)
        {
            if(result.error_code == 'AUTH_FAILURE')
            {
                //wrong password
                console.log('Recieved authentication error');
                $('#login_errors_auth').fadeIn();
            }
            else
            {
                //generic error here
                $('#login_errors_unknown').fadeIn();
            }
        }
    }
});

Here, "result" is the json object returned form the server which could have a structure like:

$return = array(
        'hasError' => !$validPassword,
        'error_code' => 'AUTH_FAILURE'
);
die(jsonEncode($return));

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

How do I hide the status bar in a Swift iOS app?

Go to your Info.plist and add two Keys:

Go to your Info.plist and add two Keys:

Resizing Images in VB.NET

This will re-size any image using the best quality with support for 32bpp with alpha. The new image will have the original image centered inside the new one at the original aspect ratio.

#Region " ResizeImage "
    Public Overloads Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
        Dim bmSource = New Drawing.Bitmap(SourceImage)

        Return ResizeImage(bmSource, TargetWidth, TargetHeight)
    End Function

    Public Overloads Shared Function ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
        Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)

        Dim nSourceAspectRatio = bmSource.Width / bmSource.Height
        Dim nDestAspectRatio = bmDest.Width / bmDest.Height

        Dim NewX = 0
        Dim NewY = 0
        Dim NewWidth = bmDest.Width
        Dim NewHeight = bmDest.Height

        If nDestAspectRatio = nSourceAspectRatio Then
            'same ratio
        ElseIf nDestAspectRatio > nSourceAspectRatio Then
            'Source is taller
            NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
            NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth) / 2))
        Else
            'Source is wider
            NewHeight = Convert.ToInt32(Math.Floor((1 / nSourceAspectRatio) * NewWidth))
            NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight) / 2))
        End If

        Using grDest = Drawing.Graphics.FromImage(bmDest)
            With grDest
                .CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
                .InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
                .PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
                .SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
                .CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver

                .DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
            End With
        End Using

        Return bmDest
    End Function
#End Region

How can I output a UTF-8 CSV in PHP that Excel will read properly?

As I investigated and I found that UTF-8 is not working well on MAC and Windows so I tried with Windows-1252 , it supports well on both of them but you must select type of encoding on ubuntu. Here is my code$valueToWrite = mb_convert_encoding($value, 'Windows-1252');

$response->headers->set('Content-Type', $mime . '; charset=Windows-1252');
    $response->headers->set('Pragma', 'public');
    $response->headers->set('Content-Endcoding','Windows-1252');
    $response->headers->set('Cache-Control', 'maxage=1');
    $response->headers->set('Content-Disposition', $dispositionHeader);
    echo "\xEF\xBB\xBF"; // UTF-8 BOM

Running Selenium WebDriver python bindings in chrome

There are 2 ways to run Selenium python tests in Google Chrome. I'm considering Windows (Windows 10 in my case):

Prerequisite: Download the latest Chrome Driver from: https://sites.google.com/a/chromium.org/chromedriver/downloads

Way 1:

i) Extract the downloaded zip file in a directory/location of your choice
ii) Set the executable path in your code as below:

self.driver = webdriver.Chrome(executable_path='D:\Selenium_RiponAlWasim\Drivers\chromedriver_win32\chromedriver.exe')

Way 2:

i) Simply paste the chromedriver.exe under /Python/Scripts/ (In my case the folder was: C:\Python36\Scripts)
ii) Now write the simple code as below:

self.driver = webdriver.Chrome()

What are abstract classes and abstract methods?

An abstract class is a class that can't be instantiated. It's only purpose is for other classes to extend.

Abstract methods are methods in the abstract class (have to be declared abstract) which means the extending concrete class must override them as they have no body.

The main purpose of an abstract class is if you have common code to use in sub classes but the abstract class should not have instances of its own.

You can read more about it here: Abstract Methods and Classes

Regex to match any character including new lines

If you don't want add the /s regex modifier (perhaps you still want . to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:

[\S\s]

a character which is not a space or is a space. In other words, any character.

You can also change modifiers locally in a small part of the regex, like so:

(?s:.)

How can I move HEAD back to a previous location? (Detached head) & Undo commits

Before answering, let's add some background, explaining what this HEAD is.

First of all what is HEAD?

HEAD is simply a reference to the current commit (latest) on the current branch.
There can only be a single HEAD at any given time (excluding git worktree).

The content of HEAD is stored inside .git/HEAD and it contains the 40 bytes SHA-1 of the current commit.


detached HEAD

If you are not on the latest commit - meaning that HEAD is pointing to a prior commit in history it's called detached HEAD.

Enter image description here

On the command line, it will look like this - SHA-1 instead of the branch name since the HEAD is not pointing to the tip of the current branch:

Enter image description here

Enter image description here


A few options on how to recover from a detached HEAD:


git checkout

git checkout <commit_id>
git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits to go back

This will checkout new branch pointing to the desired commit.
This command will checkout to a given commit.
At this point, you can create a branch and start to work from this point on.

# Checkout a given commit.
# Doing so will result in a `detached HEAD` which mean that the `HEAD`
# is not pointing to the latest so you will need to checkout branch
# in order to be able to update the code.
git checkout <commit-id>

# Create a new branch forked to the given commit
git checkout -b <branch name>

git reflog

You can always use the reflog as well.
git reflog will display any change which updated the HEAD and checking out the desired reflog entry will set the HEAD back to this commit.

Every time the HEAD is modified there will be a new entry in the reflog

git reflog
git checkout HEAD@{...}

This will get you back to your desired commit

Enter image description here


git reset --hard <commit_id>

"Move" your HEAD back to the desired commit.

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts if you've modified things which were
# changed since the commit you reset to.
  • Note: (Since Git 2.7) you can also use the git rebase --no-autostash as well.

git revert <sha-1>

"Undo" the given commit or commit range.
The reset command will "undo" any changes made in the given commit.
A new commit with the undo patch will be committed while the original commit will remain in the history as well.

# Add a new commit with the undo of the original one.
# The <sha-1> can be any commit(s) or commit range
git revert <sha-1>

This schema illustrates which command does what.
As you can see there, reset && checkout modify the HEAD.

Enter image description here

Adding custom radio buttons in android

In order to hide the default radio button, I'd suggest to remove the button instead of making it transparent as all visual feedback is handled by the drawable background :

android:button="@null"

Also it would be better to use styles as there are several radio buttons :

<RadioButton style="@style/RadioButtonStyle" ... />

<style name="RadioButtonStyle" parent="@android:style/Widget.CompoundButton">
    <item name="android:background">@drawable/customButtonBackground</item>
    <item name="android:button">@null</item>
</style>

You'll need the Seslyn customButtonBackground drawable too.

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

String Fpath = getPath(this, uri) ;
File file = new File(Fpath);
String filename = file.getName();

Shift column in pandas dataframe up by one?

In [44]: df['gdp'] = df['gdp'].shift(-1)

In [45]: df
Out[45]: 
   y  gdp  cap
0  1    3    5
1  2    7    9
2  8    4    2
3  3    7    7
4  6  NaN    7

In [46]: df[:-1]                                                                                                                                                                                                                                                                                                               
Out[46]: 
   y  gdp  cap
0  1    3    5
1  2    7    9
2  8    4    2
3  3    7    7

phpmailer error "Could not instantiate mail function"

My config: IIS + php7.4

I had the same issue as @Salman-A, where small attachments were emailed but large were causing the page to error out. I have increased file and attachments limits in php.ini, but this has made no difference.

Then I found a configuration in IIS(6.0), and increased file limits in there. iis config image

Also here is my mail.php:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require '../_PHPMailer-master/src/Exception.php';
require '../_PHPMailer-master/src/PHPMailer.php';

try{
    $email = new PHPMailer(true);
    $email->SetFrom('[email protected]', 'optional name');
    $email->isHTML(true);
    $email->Subject   = 'my subject';
    $email->Body      = $emailContent;
    $email->AddAddress( $eml_to );  
    $email->AddAttachment( $file_to_attach );
    $email->Send();
  }catch(phpmailerException $e){echo $e->errorMessage();}

I hope this helps someone in the future.

Regular cast vs. static_cast vs. dynamic_cast

dynamic_cast only supports pointer and reference types. It returns NULL if the cast is impossible if the type is a pointer or throws an exception if the type is a reference type. Hence, dynamic_cast can be used to check if an object is of a given type, static_cast cannot (you will simply end up with an invalid value).

C-style (and other) casts have been covered in the other answers.

reading external sql script in python

Your code already contains a beautiful way to execute all statements from a specified sql file

# Open and read the file as a single buffer
fd = open('ZooDatabase.sql', 'r')
sqlFile = fd.read()
fd.close()

# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')

# Execute every command from the input file
for command in sqlCommands:
    # This will skip and report errors
    # For example, if the tables do not yet exist, this will skip over
    # the DROP TABLE commands
    try:
        c.execute(command)
    except OperationalError, msg:
        print "Command skipped: ", msg

Wrap this in a function and you can reuse it.

def executeScriptsFromFile(filename):
    # Open and read the file as a single buffer
    fd = open(filename, 'r')
    sqlFile = fd.read()
    fd.close()

    # all SQL commands (split on ';')
    sqlCommands = sqlFile.split(';')

    # Execute every command from the input file
    for command in sqlCommands:
        # This will skip and report errors
        # For example, if the tables do not yet exist, this will skip over
        # the DROP TABLE commands
        try:
            c.execute(command)
        except OperationalError, msg:
            print "Command skipped: ", msg

To use it

executeScriptsFromFile('zookeeper.sql')

You said you were confused by

result = c.execute("SELECT * FROM %s;" % table);

In Python, you can add stuff to a string by using something called string formatting.

You have a string "Some string with %s" with %s, that's a placeholder for something else. To replace the placeholder, you add % ("what you want to replace it with") after your string

ex:

a = "Hi, my name is %s and I have a %s hat" % ("Azeirah", "cool")
print(a)
>>> Hi, my name is Azeirah and I have a Cool hat

Bit of a childish example, but it should be clear.

Now, what

result = c.execute("SELECT * FROM %s;" % table);

means, is it replaces %s with the value of the table variable.

(created in)

for table in ['ZooKeeper', 'Animal', 'Handles']:


# for loop example

for fruit in ["apple", "pear", "orange"]:
    print fruit
>>> apple
>>> pear
>>> orange

If you have any additional questions, poke me.

How to format current time using a yyyyMMddHHmmss format?

This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:

t := time.Now()

t.Year()

t.Month()

t.Day()

t.Hour()

t.Minute()

t.Second()

For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:

t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
        t.Year(), t.Month(), t.Day(),
        t.Hour(), t.Minute(), t.Second())

As always, remember that docs are the best source of learning: https://golang.org/pkg/time/

Render HTML to an image

There is a lot of options and they all have their pro and cons.

Option 1: Use an API

Pros

  • Execute Javascript
  • Near perfect rendering
  • Fast when caching options are correctly used
  • Scale is handled by the APIs
  • Precise timing, viewport, ...
  • Most of the time they offer a free plan

Cons

  • Not free if you plan to use them a lot

Option 2: Use one of the many available libraries

Pros

  • Conversion is quite fast most of the time

Cons

  • Bad rendering
  • Does not execute javascript
  • No support for recent web features (FlexBox, Advanced Selectors, Webfonts, Box Sizing, Media Queries, ...)
  • Sometimes not so easy to install
  • Complicated to scale

Option 3: Use PhantomJs and maybe a wrapper library

Pros

  • Execute Javascript
  • Quite fast

Cons

  • Bad rendering
  • No support for recent web features (FlexBox, Advanced Selectors, Webfonts, Box Sizing, Media Queries, ...)
  • Complicated to scale
  • Not so easy to make it work if there is images to be loaded ...

Option 4: Use Chrome Headless and maybe a wrapper library

Pros

  • Execute Javascript
  • Near perfect rendering

Cons

  • Not so easy to have exactly the wanted result regarding:
    • page load timing
    • viewport dimensions
  • Complicated to scale
  • Quite slow and even slower if the html contains external links

Disclosure: I'm the founder of ApiFlash. I did my best to provide an honest and useful answer.

How to hide reference counts in VS2013?

In VSCode for Mac (0.10.6) I opened "Preferences -> User Settings" and placed the following code in the settings.json file

enter image description here

"editor.referenceInfos": false

enter image description here

User and Workspace Settings

Error "can't use subversion command line client : svn" when opening android project checked out from svn

Saw your problems.

Solutions:

First Download Subversion 1.8.13 ( 1.8 ) client Download link (https://subversion.apache.org/packages.html) at the time of this post the android studio version is less than 1.4 in my case 1.3.2 so you must avoid the issues here subversion command line client version is too old so just download the 1.8 preferably.

enter image description here

Then unzipped in a folder. There will have one folder "bin".

Then

Go to settings - > Version control -> Subversion

Copy the url of your downloaded svn.exe that is in bin folder that you have downloaded.

follow the picture:

enter image description here

Don't forget to give the end name like svn.exe last as per image.

Apply -> Ok

Restart your android studio now.

Happy Coding!

What's the best way to break from nested loops in JavaScript?

Already mentioned previously by swilliams, but with an example below (Javascript):

// Function wrapping inner for loop
function CriteriaMatch(record, criteria) {
  for (var k in criteria) {
    if (!(k in record))
      return false;

    if (record[k] != criteria[k])
      return false;
  }

  return true;
}

// Outer for loop implementing continue if inner for loop returns false
var result = [];

for (var i = 0; i < _table.length; i++) {
  var r = _table[i];

  if (!CriteriaMatch(r[i], criteria))
    continue;

  result.add(r);
}

I got error "The DELETE statement conflicted with the REFERENCE constraint"

Have you considered applying ON DELETE CASCADE where relevant?

What does "both" mean in <div style="clear:both">

Clear:both gives you that space between them.

For example your code:

  <div style="float:left">Hello</div>
  <div style="float:right">Howdy dere pardner</div>

Will currently display as :

Hello  ...................   Howdy dere pardner

If you add the following to above snippet,

  <div style="clear:both"></div>

In between them it will display as:

Hello ................ 
                       Howdy dere pardner

giving you that space between hello and Howdy dere pardner.

Js fiiddle http://jsfiddle.net/Qk5vR/1/

How to pass variable as a parameter in Execute SQL Task SSIS?

In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:

enter image description here

Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:

enter image description here

Now when this task runs it will pass the SSIS variables to the stored proc.

Return empty cell from formula in Excel

Google brought me here with a very similar problem, I finally figured out a solution that fits my needs, it might help someone else too...

I used this formula:

=IFERROR(MID(Q2, FIND("{",Q2), FIND("}",Q2) - FIND("{",Q2) + 1), "")

How to handle errors with boto3?

  • Only one import needed.
  • No if statement needed.
  • Use the client built-in exception as intended.

Ex:

from boto3 import client

cli = client('iam')
try:
    cli.create_user(
        UserName = 'Brian'
    )
except cli.exceptions.EntityAlreadyExistsException:
    pass

a CloudWatch example:

cli = client('logs')
try:
    cli.create_log_group(
        logGroupName = 'MyLogGroup'
    )
except cli.exceptions.ResourceAlreadyExistsException:
    pass

Unable to start MySQL server

Try manually start the service from Windows services, Start -> cmd.exe -> services.msc. Also try to configure the MySQL server to run on another port and try starting it again. Change the my.ini file to change the port number.

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

Working fiddle:

http://jsfiddle.net/repjt/

$.ajax({
    url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
    dataType: 'JSONP',
    jsonpCallback: 'callback',
    type: 'GET',
    success: function (data) {
        console.log(data);
    }
});

I had to manually set the callback to callback, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.

How to remove close button on the jQuery UI dialog?

This is for jQuery UI 1.12. I added the following configuration setting for 'classes' option

        classes: {
            'ui-dialog-titlebar-close': 'hidden',
        },

the whole dialog initialization looks like this:

ConfirmarSiNo(titulo, texto, idPadre, fnCerrar) {
    const DATA_RETORNO = 'retval';
    $('confirmar-si-no').dialog({
        title: titulo,
        modal: true,
        classes: {
            'ui-dialog-titlebar-close': 'hidden',
        },
        appendTo: `#${idPadre}`,
        open: function fnOpen() { $(this).text(texto); },
        close: function fnClose() {
            let eligioSi = $(this).data(DATA_RETORNO) == true;
            setTimeout(function () { fnCerrar(eligioSi); }, 30);
        },
        buttons: {
            'Si, por favor': function si() { $(this).data(DATA_RETORNO, true); $(this).dialog("close"); },
            'No, gracias': function no() { $(this).data(DATA_RETORNO, false); $(this).dialog("close"); }
        }
    });
}

I use following script call to show it:

ConfirmarSiNo('Titulo',
              '¿Desea actualizar?',
              idModalPadre,
              (eligioSi) => {
                            if (eligioSi) {
                                this.$tarifa.val(tarifa.tarifa);
                                this.__ActualizarTarifa(tarifa);
                            }
                        });

whithin Html body I have the following div that contains the dialog:

<div class="modal" id="confirmar-si-no" title="" aria-labelledby="confirmacion-label">
    mensaje
</div>

final result is:

enter image description here

function 'ConfirmarSiNo' is based on 'Whome' answer on post How to implement “confirmation” dialog in Jquery UI dialog?

ViewPager PagerAdapter not updating the View

Always returning POSITION_NONE is simple but a little inefficient way because that evoke instantiation of all page that have already instantiated.

I've created a library ArrayPagerAdapter to change items in PagerAdapters dynamically.

Internally, this library's adapters return POSITION_NONE on getItemPosiition() only when necessary.

You can change items dynamically like following by using this library.

@Override
protected void onCreate(Bundle savedInstanceState) {
        /** ... **/
    adapter = new MyStatePagerAdapter(getSupportFragmentManager()
                            , new String[]{"1", "2", "3"});
    ((ViewPager)findViewById(R.id.view_pager)).setAdapter(adapter);
     adapter.add("4");
     adapter.remove(0);
}

class MyPagerAdapter extends ArrayViewPagerAdapter<String> {

    public MyPagerAdapter(String[] data) {
        super(data);
    }

    @Override
    public View getView(LayoutInflater inflater, ViewGroup container, String item, int position) {
        View v = inflater.inflate(R.layout.item_page, container, false);
        ((TextView) v.findViewById(R.id.item_txt)).setText(item);
        return v;
    }
}

Thils library also support pages created by Fragments.

Npm install cannot find module 'semver'

Having just encountered this on Arch Linux 4.13.3, I solved the issue by simply reinstalling semver:

pacman -S semver

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

You can traverse each string in the list and even you can search in the whole generic using a single statement this makes searching easier.

public static void main(string[] args)
{
List names = new List();

names.Add(“Saurabh”);
names.Add("Garima");
names.Add(“Vivek”);
names.Add(“Sandeep”);

string stringResult = names.Find( name => name.Equals(“Garima”));
}

Python vs. Java performance (runtime speed)

Different languages do different things with different levels of efficiency.

The Benchmarks Game has a whole load of different programming problems implemented in a lot of different languages.

How can I remove all my changes in my SVN working directory?

svn revert will undo any local changes you've made

How do I create a crontab through a script

Here is how to modify cron a entry without directly editing the cron file (which is frowned upon).

crontab -l -u <user> | sed 's/find/replace/g' | crontab -u <user> -

If you want to remove a cron entry, use this:

crontab -l -u <user> | sed '/find/d' | crontab -u <user> -

I realize this is not what gaurav was asking for, but why not have all the solutions in one place?

Specifying java version in maven - differences between properties and compiler plugin

None of the solutions above worked for me straight away. So I followed these steps:

  1. Add in pom.xml:
<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
</properties>
  1. Go to Project Properties > Java Build Path, then remove the JRE System Library pointing to JRE1.5.

  2. Force updated the project.

finding multiples of a number in Python

def multiples(n,m,starting_from=1,increment_by=1):
    """
    # Where n is the number 10 and m is the number 2 from your example. 
    # In case you want to print the multiples starting from some other number other than 1 then you could use the starting_from parameter
    # In case you want to print every 2nd multiple or every 3rd multiple you could change the increment_by 
    """
    print [ n*x for x in range(starting_from,m+1,increment_by) ] 

Setting the height of a SELECT in IE

Finally found in http://viralpatel.net/blogs/2009/09/setting-height-selectbox-combobox-ie.html a simple solution (at least for IE8):

font-size:      1.0em;

BTW, for Google Chrome, found this workaround at How to standardize the height of a select box between Chrome and Firefox? */

-webkit-appearance: menulist-button;

iOS Simulator to test website on Mac

iPhoney is designed specifically for Mac users

you can read about it and download it here

GCC fatal error: stdio.h: No such file or directory

I know my case is rare, but I'll still add it here for someone who troubleshoots it later. I had a Linux Kernel module target in my Makefile and I tried to compile my user space program together with the kernel module that doesn't have stdio. Making it a separate target solved the problem.

How to do a batch insert in MySQL

mysql allows you to insert multiple rows at once INSERT manual

How can I extract audio from video with ffmpeg?

Here's what I just used:

ffmpeg -i my.mkv -map 0:3 -vn -b:a 320k my.mp3

Options explanation:

  • my.mkv is a source video file, you can use other formats as well
  • -map 0:3 means I want 3rd stream from video file. Put your N there - video files often has multiple audio streams; you can omit it or use -map 0:a to take the default audio stream. Run ffprobe my.mkv to see what streams does the video file have.
  • my.mp3 is a target audio filename, and ffmpeg figures out I want an MP3 from its extension. In my case the source audio stream is ac3 DTS and just copying wasn't what I wanted
  • 320k is a desired target bitrate
  • -vn means I don't want video in target file

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

For a true comparison, you can use:

dateTime1.Date.CompareTo(dateTime2.Date);

Effects of the extern keyword on C functions

IOW, extern is redundant, and does nothing.

That is why, 10 years later:

See commit ad6dad0, commit b199d71, commit 5545442 (29 Apr 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 4aeeef3, 13 May 2019)

*.[ch]: remove extern from function declarations using spatch

There has been a push to remove extern from function declarations.

Remove some instances of "extern" for function declarations which are caught by Coccinelle.
Note that Coccinelle has some difficulty with processing functions with __attribute__ or varargs so some extern declarations are left behind to be dealt with in a future patch.

This was the Coccinelle patch used:

  @@
    type T;
    identifier f;
    @@
    - extern
    T f(...);

and it was run with:

  $ git ls-files \*.{c,h} |
    grep -v ^compat/ |
    xargs spatch --sp-file contrib/coccinelle/noextern.cocci --in-place

This is not always straightforward though:

See commit 7027f50 (04 Sep 2019) by Denton Liu (Denton-L).
(Merged by Denton Liu -- Denton-L -- in commit 7027f50, 05 Sep 2019)

compat/*.[ch]: remove extern from function declarations using spatch

In 5545442 (*.[ch]: remove extern from function declarations using spatch, 2019-04-29, Git v2.22.0-rc0), we removed externs from function declarations using spatch but we intentionally excluded files under compat/ since some are directly copied from an upstream and we should avoid churning them so that manually merging future updates will be simpler.

In the last commit, we determined the files which taken from an upstream so we can exclude them and run spatch on the remainder.

This was the Coccinelle patch used:

@@
type T;
identifier f;
@@
- extern
  T f(...);

and it was run with:

$ git ls-files compat/\*\*.{c,h} |
    xargs spatch --sp-file contrib/coccinelle/noextern.cocci --in-place
$ git checkout -- \
    compat/regex/ \
    compat/inet_ntop.c \
    compat/inet_pton.c \
    compat/nedmalloc/ \
    compat/obstack.{c,h} \
    compat/poll/

Coccinelle has some trouble dealing with __attribute__ and varargs so we ran the following to ensure that no remaining changes were left behind:

$ git ls-files compat/\*\*.{c,h} |
    xargs sed -i'' -e 's/^\(\s*\)extern \([^(]*([^*]\)/\1\2/'
$ git checkout -- \
    compat/regex/ \
    compat/inet_ntop.c \
    compat/inet_pton.c \
    compat/nedmalloc/ \
    compat/obstack.{c,h} \
    compat/poll/

Note that with Git 2.24 (Q4 2019), any spurious extern is dropped.

See commit 65904b8 (30 Sep 2019) by Emily Shaffer (nasamuffin).
Helped-by: Jeff King (peff).
See commit 8464f94 (21 Sep 2019) by Denton Liu (Denton-L).
Helped-by: Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 59b19bc, 07 Oct 2019)

promisor-remote.h: drop extern from function declaration

During the creation of this file, each time a new function declaration was introduced, it included an extern.
However, starting from 5545442 (*.[ch]: remove extern from function declarations using spatch, 2019-04-29, Git v2.22.0-rc0), we've been actively trying to prevent externs from being used in function declarations because they're unnecessary.

Remove these spurious externs.

What is the C++ function to raise a number to a power?

#include <iostream>
#include <conio.h>

using namespace std;

double raiseToPow(double ,int) //raiseToPow variable of type double which takes arguments (double, int)

void main()
{
    double x; //initializing the variable x and i 
    int i;
    cout<<"please enter the number"; 
    cin>>x;
    cout<<"plese enter the integer power that you want this number raised to";
    cin>>i;
    cout<<x<<"raise to power"<<i<<"is equal to"<<raiseToPow(x,i);
}

//definition of the function raiseToPower

double raiseToPow(double x, int power)
{
    double result;
    int i;
    result =1.0;
    for (i=1, i<=power;i++)
    {
        result = result*x;
    }
    return(result);
}

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

There are 2 scenario's where Bash performance is at least equal I believe:

  • Scripting of command line utilities
  • Scripts which take only a short time to execute; where starting the Python interpreter takes more time than the operation itself

That said, I usually don't really concern myself with performance of the scripting language itself. If performance is a real issue you don't script but program (possibly in Python).

How to convert a string with comma-delimited items to a list in Python?

The following Python code will turn your string into a list of strings:

import ast
teststr = "['aaa','bbb','ccc']"
testarray = ast.literal_eval(teststr)

How to differentiate single click event and double click event?

The behavior of the dblclick event is explained at Quirksmode.

The order of events for a dblclick is:

  1. mousedown
  2. mouseup
  3. click
  4. mousedown
  5. mouseup
  6. click
  7. dblclick

The one exception to this rule is (of course) Internet Explorer with their custom order of:

  1. mousedown
  2. mouseup
  3. click
  4. mouseup
  5. dblclick

As you can see, listening to both events together on the same element will result in extra calls to your click handler.

What is the best way to extract the first word from a string in Java?

String anotherPalindrome = "Niagara. O roar again!"; 
String roar = anotherPalindrome.substring(11, 15); 

You can also do like these

Angular2 - Input Field To Accept Only Numbers

If you don't want a directive

https://stackblitz.com/edit/numeric-only

in component.html

<input (keypress)="numberOnly($event)" type="text">

in component.ts

export class AppComponent {

  numberOnly(event): boolean {
    const charCode = (event.which) ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false;
    }
    return true;

  }
}

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

It looks like you did not add a MySQL database to your application, OR you added it after you installed laravel. In that case, you need to stop & start (not restart) your application so that it will pick up your environment variables. (rhc app stop , rhc app start ). If you did not add a database yet, you will need to add one of the mysql cartridges, and then stop & start your application using the previously shown commands.

Force browser to download image files on click

You can directly download this file using anchor tag without much code.
Copy the snippet and paste in your text-editor and try it...!

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
   <div>_x000D_
     <img src="https://upload.wikimedia.org/wikipedia/commons/1/1f/SMirC-thumbsup.svg" width="200" height="200">_x000D_
      <a href="#" download="https://upload.wikimedia.org/wikipedia/commons/1/1f/SMirC-thumbsup.svg"> Download Image </a>_x000D_
   </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to sort an array of associative arrays by value of a given key in PHP?

For PHP 7 and later versions.

/**
 * A method for sorting associative arrays by a key and a direction.
 * Direction can be ASC or DESC.
 *
 * @param $array
 * @param $key
 * @param $direction
 * @return mixed $array
 */
function sortAssociativeArrayByKey($array, $key, $direction){

    switch ($direction){
        case "ASC":
            usort($array, function ($first, $second) use ($key) {
                return $first[$key] <=> $second[$key];
            });
            break;
        case "DESC":
            usort($array, function ($first, $second) use ($key) {
                return $second[$key] <=> $first[$key];
            });
            break;
        default:
            break;
    }

    return $array;
}

Usage:

$inventory = sortAssociativeArrayByKey($inventory, "price", "ASC");

Best data type for storing currency values in a MySQL database

It depends on the nature of data. You need to contemplate it beforehand.

My case

  • decimal(13,4) unsigned for recording money transactions
    • storage efficient (4 bytes for each side of decimal point anyway) 1
    • GAAP compliant
  • decimal(19,4) unsigned for aggregates
    • we need more space for totals of multiple multi-billion transactions
    • semi-compliance with MS Currency data type won't hurt 2
    • it will take more space per record (11 bytes - 7 left & 4 right), but this is fine as there are fewer records for aggregates 1
  • decimal(10,5) for exchange rates
    • they are normally quoted with 5 digits altogether so you could find values like 1.2345 & 12.345 but not 12345.67890
    • it is widespread convention, but not a codified standard (at least to my quick search knowledge)
    • you could make it decimal (18,9) with the same storage, but the datatype restrictions are valuable built-in validation mechanism

Why (M,4)?

  • there are currencies that split into a thousand pennies
  • there are money equivalents like "Unidad de Fermento", "CLF" expressed with 4 significant decimal places 3,4
  • it is GAAP compliant

Tradeoff

  • lower precision:
    • less storage cost
    • quicker calculations
    • lower calculation error risk
    • quicker backup & restore
  • higher precision:
    • future compatibility (numbers tend to grow)
    • development time savings (you won't have to rebuild half a system when the limits are met)
    • lower risk of production failure due to insufficient storage precision

Compatible Extreme

Although MySQL lets you use decimal(65,30), 31 for scale and 30 for precision seem to be our limits if we want to leave transfer option open.

Maximum scale and precision in most common RDBMS:

            Precision   Scale
Oracle      31          31
T-SQL       38          38
MySQL       65          30
PostgreSQL  131072      16383

6, 7, 8, 9

Reasonable Extreme

  1. Why (27,4)?
    • you never know when the system needs to store Zimbabwean dollars

September 2015 Zimbabwean government stated it would exchange Zimbabwean dollars for US dollars at a rate of 1 USD to 35 quadrillion Zimbabwean dollars 5

We tend to say "yeah, sure... I won't need that crazy figures". Well, Zimbabweans used to say that too. Not to long ago.

Let's imagine you need to record a transaction of 1 mln USD in Zimbabwean dollars (maybe unlikely today, but who knows how this will look like in 10 years from now?).

  1. (1 mln USD) * (35 Quadrylion ZWL) = ( 10^6 ) * (35 * 10^15) = 35 * 10^21
  2. we need:
    • 2 digits to store "35"
    • 21 digits to store the zeros
    • 4 digits to the right of decimal point
  3. this makes decimal(27,4) which costs us 15 bytes for each entry
  4. we may add one more digit on the left at no expense - we have decimal(28,4) for 15 bytes
  5. Now we can store 10 mln USD transaction expressed in Zimbabwean dollars, or secure from another strike of hiperinflation, which hopefully won't happen

MySql : Grant read only options?

A step by step guide I found here.

To create a read-only database user account for MySQL

At a UNIX prompt, run the MySQL command-line program, and log in as an administrator by typing the following command:

mysql -u root -p

Type the password for the root account. At the mysql prompt, do one of the following steps:

To give the user access to the database from any host, type the following command:

grant select on database_name.* to 'read-only_user_name'@'%' identified by 'password';

If the collector will be installed on the same host as the database, type the following command:

grant select on database_name.* to 'read-only_user_name' identified by 'password';

This command gives the user read-only access to the database from the local host only. If you know the host name or IP address of the host that the collector is will be installed on, type the following command:

grant select on database_name.* to 'read-only_user_name'@'host_name or IP_address' identified by 'password';

The host name must be resolvable by DNS or by the local hosts file. At the mysql prompt, type the following command:

flush privileges;

Type quit.

The following is a list of example commands and confirmation messages:

mysql> grant select on dbname.* to 'readonlyuser'@'%' identified 
by 'pogo$23';
Query OK, 0 rows affected (0.11 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> quit

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

In case you're having this problem in flex/adobe air and find yourself here first, i've found a solution, and have posted it on a related question: ADD COLUMN to sqlite db IF NOT EXISTS - flex/air sqlite?

My comment here: https://stackoverflow.com/a/24928437/2678219

Write a formula in an Excel Cell using VBA

The correct character (comma or colon) depends on the purpose.

Comma (,) will sum only the two cells in question.

Colon (:) will sum all the cells within the range with corners defined by those two cells.

Python list / sublist selection -1 weirdness

It seems pretty consistent to me; positive indices are also non-inclusive. I think you're doing it wrong. Remembering that range() is also non-inclusive, and that Python arrays are 0-indexed, here's a sample python session to illustrate:

>>> d = range(10)
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d[9]
9
>>> d[-1]
9
>>> d[0:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> d[0:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> len(d)
10

How to stop a PowerShell script on the first error?

I came here looking for the same thing. $ErrorActionPreference="Stop" kills my shell immediately when I'd rather see the error message (pause) before it terminates. Falling back on my batch sensibilities:

IF %ERRORLEVEL% NEQ 0 pause & GOTO EOF

I found that this works pretty much the same for my particular ps1 script:

Import-PSSession $Session
If ($? -ne "True") {Pause; Exit}

Tomcat base URL redirection

Tested and Working procedure:

Goto the file path ..\apache-tomcat-7.0.x\webapps\ROOT\index.jsp

remove the whole content or declare the below lines of code at the top of the index.jsp

<% response.sendRedirect("http://yourRedirectionURL"); %>

Please note that in jsp file you need to start the above line with <% and end with %>

Insert Update trigger how to determine if insert or update

A potential problem with the two solutions offered is that, depending on how they are written, an update query may update zero records and an insert query may insert zero records. In these cases, the Inserted and Deleted recordsets will be empty. In many cases, if both the Inserted and Deleted recordsets are empty you might just want to exit the trigger without doing anything.

github: server certificate verification failed

Another possible cause is that the clock of your machine is not synced (e.g. on Raspberry Pi). Check the current date/time using:

$ date

If the date and/or time is incorrect, try to update using:

$ sudo ntpdate -u time.nist.gov

How to convert string to integer in UNIX

Use this:

#include <stdlib.h>
#include <string.h>

int main()
{
    const char *d1 = "11";
    int d1int = atoi(d1);
    printf("d1 = %d\n", d1);
    return 0;
}

etc.

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

Open application after clicking on Notification

Here's example using NotificationCompact.Builder class which is the recent version to build notification.

private void startNotification() {
    Log.i("NextActivity", "startNotification");

 // Sets an ID for the notification
      int mNotificationId = 001;

    // Build Notification , setOngoing keeps the notification always in status bar
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ldb)
                    .setContentTitle("Stop LDB")
                    .setContentText("Click to stop LDB")
                    .setOngoing(true);

    // Create pending intent, mention the Activity which needs to be 
    //triggered when user clicks on notification(StopScript.class in this case)

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, StopScript.class), PendingIntent.FLAG_UPDATE_CURRENT);


    mBuilder.setContentIntent(contentIntent);


    // Gets an instance of the NotificationManager service
   NotificationManager mNotificationManager =
            (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);


    // Builds the notification and issues it.
    mNotificationManager.notify(mNotificationId, mBuilder.build());


}

Finding common rows (intersection) in two Pandas dataframes

In SQL, this problem could be solved by several methods:

select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)

or join and then unpivot (possible in SQL server)

select
    df1.user_id,
    c.rating
from df1
    inner join df2 on df2.user_i = df1.user_id
    outer apply (
        select df1.rating union all
        select df2.rating
    ) as c

Second one could be written in pandas with something like:

>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
   user_id  rating
0        3      20
0        3      30

Spring: How to get parameters from POST body?

You can try using @RequestBodyParam

@RequestMapping(value = "/saveData", headers="Content-Type=application/json", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(@RequestBodyParam String source,@RequestBodyParam JsonDto json) throws MyException {
    ...
}

https://github.com/LambdaExpression/RequestBodyParam

/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

I ran into this issue on my Ubuntu-64 system when attempting to import fst within python as such:

    Python 3.4.3 |Continuum Analytics, Inc.| (default, Jun  4 2015, 15:29:08)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fst
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ogi/miniconda3/lib/python3.4/site-packages/pyfst-0.2.3.dev0-py3.4-linux-x86_64.egg/fst/__init__.py", line 1, in <module>
    from fst._fst import EPSILON, EPSILON_ID, SymbolTable,\
ImportError: /home/ogi/miniconda3/lib/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /usr/local/lib/libfst.so.1)

I then ran:

ogi@ubuntu:~/miniconda3/lib$ find ~/ -name "libstdc++.so.6"
/home/ogi/miniconda3/lib/libstdc++.so.6
/home/ogi/miniconda3/pkgs/libgcc-5-5.2.0-2/lib/libstdc++.so.6
/home/ogi/miniconda3/pkgs/libgcc-4.8.5-1/lib/libstdc++.so.6
find: `/home/ogi/.local/share/jupyter/runtime': Permission denied
ogi@ubuntu:~/miniconda3/lib$

mv /home/ogi/miniconda3/lib/libstdc++.so.6 /home/ogi/miniconda3/libstdc++.so.6.old
cp /home/ogi/miniconda3/libgcc-5-5.2.0-2/lib/libstdc++.so.6 /home/ogi/miniconda3/lib/

At which point I was then able to load the library

ogi@ubuntu:~/miniconda3/lib$ python
Python 3.4.3 |Continuum Analytics, Inc.| (default, Jun  4 2015, 15:29:08)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fst
>>> exit()

Where can I find a list of keyboard keycodes?

I know this was asked awhile back, but I found a comprehensive list of the virtual keyboard key codes right in MSDN, for use in C/C++. This also includes the mouse events. Note it is different than the javascript key codes (I noticed it around the VK_OEM section).

Here's the link:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

Amazon AWS Filezilla transfer permission denied

for me below worked:

chown -R ftpusername /var/app/current

Programmatically center TextView text

You can use the following to programmatically center TextView text in Kotlin:

textview.gravity = Gravity.CENTER

Java compiler level does not match the version of the installed Java project facet

In Eclipse, right click on your project, go to Maven> Update projetc. Wait and the error will disappear. This is already configured correctly the version of Java for this project.

enter image description here

Pandas dataframe fillna() only some columns in place

You can avoid making a copy of the object using Wen's solution and inplace=True:

df.fillna({'a':0, 'b':0}, inplace=True)
print(df)

Which yields:

     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

Curl Command to Repeat URL Request

for i in `seq 1 20`; do curl http://url; done

Or if you want to get timing information back, use ab:

ab -n 20 http://url/

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    e.preventDefault();
    $('#contactsForm').attr('action', "/test1").submit();
});

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

How to convert this var string to URL in Swift

In Swift3:
let fileUrl = Foundation.URL(string: filePath)

ImportError: No module named 'django.core.urlresolvers'

urlresolver has been removed in the higher version of Django - Please upgrade your django installation. I fixed it using the following command.

pip install django==2.0 --upgrade

Can Android Studio be used to run standard Java projects?

I installed IntelliJ IDEA community version from http://www.jetbrains.com/idea/download/

I tried opening my project that I started in Android studio but it failed when at gradle build. I instead opened both android studio and intellij at same time and placed one screen next to the other and simply drag and dropped my java files, xml layouts, drawables, and manifest into the project hiearchy of a new project started in IntelliJ. It worked around the gradle build issues and now I can start a new project in IntelliJ and design either an android app or a basic Java app. Thankfully this worked because I hated having so many IDEs on my pc.

How to edit CSS style of a div using C# in .NET

If all you want to do is conditionally show or hide a <div>, then you could declare it as an <asp:panel > (renders to html as a div tag) and set it's .Visible property.

@RequestParam vs @PathVariable

1) @RequestParam is used to extract query parameters

http://localhost:3000/api/group/test?id=4

@GetMapping("/group/test")
public ResponseEntity<?> test(@RequestParam Long id) {
    System.out.println("This is test");
    return ResponseEntity.ok().body(id);
}

while @PathVariable is used to extract data right from the URI:

http://localhost:3000/api/group/test/4

@GetMapping("/group/test/{id}")
public ResponseEntity<?> test(@PathVariable Long id) {
    System.out.println("This is test");
    return ResponseEntity.ok().body(id);
}

2) @RequestParam is more useful on a traditional web application where data is mostly passed in the query parameters while @PathVariable is more suitable for RESTful web services where URL contains values.

3) @RequestParam annotation can specify default values if a query parameter is not present or empty by using a defaultValue attribute, provided the required attribute is false:

@RestController
@RequestMapping("/home")
public class IndexController {

    @RequestMapping(value = "/name")
    String getName(@RequestParam(value = "person", defaultValue = "John") String personName) {
        return "Required element of request param";
    }

}

How to select first child with jQuery?

Try with: $('.onediv').eq(0)

demo jsBin

From the demo: Other examples of selectors and methods targeting the first LI unside an UL:

.eq() Method: $('li').eq(0)
:eq() selector: $('li:eq(0)')
.first() Method $('li').first()
:first selector: $('li:first')
:first-child selector: $('li:first-child')
:lt() selector:$('li:lt(1)')
:nth-child() selector:$('li:nth-child(1)')

jQ + JS:

Array.slice() Method: $('li').slice(0,1)

you can also use [i] to get the JS HTMLelement index out of the jQuery el. (array) collection like eg:

$('li')[0]

now that you have the JS element representation you have to use JS native methods eg:

$('li')[0].className = 'active'; // Adds class "active" to the first LI in the DOM

or you can (don't - it's bad design) wrap it back into a jQuery object

$( $('li')[0] ).addClass('active'); // Don't. Use .eq() instead

How to read all of Inputstream in Server Socket JAVA

int c;
    String raw = "";
    do {
        c = inputstream.read();
        raw+=(char)c;
    } while(inputstream.available()>0);

InputStream.available() shows the available bytes only after one byte is read, hence do .. while