Programs & Examples On #Mathematical notation

What does this square bracket and parenthesis bracket notation mean [first1,last1)?

It can be a mathematical convention in the definition of an interval where square brackets mean "extremal inclusive" and round brackets "extremal exclusive".

Rollback transaction after @Test

I know, I am tooooo late to post an answer, but hoping that it might help someone. Plus, I just solved this issue I had with my tests. This is what I had in my test:

My test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "path-to-context" })
@Transactional
public class MyIntegrationTest 

Context xml

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName" value="${jdbc.driverClassName}" />
   <property name="url" value="${jdbc.url}" />
   <property name="username" value="${jdbc.username}" />
   <property name="password" value="${jdbc.password}" />
</bean>

I still had the problem that, the database was not being cleaned up automatically.

Issue was resolved when I added following property to BasicDataSource

<property name="defaultAutoCommit" value="false" />

Hope it helps.

Width of input type=text element

I think you are forgetting about the border. Having a one-pixel-wide border on the Div will take away two pixels of total length. Therefore it will appear as though the div is two pixels shorter than it actually is.

Typescript ReferenceError: exports is not defined

Had the same issue and fixed it by changing the JS packages loading order.

Check the order in which the packages you need are being called and load them in an appropriate order.

In my specific case (not using module bundler) I needed to load Redux, then Redux Thunk, then React Redux. Loading React Redux before Redux Thunk would give me exports is not defined.

How to tar certain file types in all subdirectories?

If you're using bash version > 4.0, you can exploit shopt -s globstar to make short work of this:

shopt -s globstar; tar -czvf deploy.tar.gz **/Alice*.yml **/Bob*.json

this will add all .yml files that starts with Alice from any sub-directory and add all .json files that starts with Bob from any sub-directory.

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

As it is a multi-class problem, you have to use the categorical_crossentropy, the binary cross entropy will produce bogus results, most likely will only evaluate the first two classes only.

50% for a multi-class problem can be quite good, depending on the number of classes. If you have n classes, then 100/n is the minimum performance you can get by outputting a random class.

Determine installed PowerShell version

This is the top search result for "Batch file get powershell version", so I'd like to provide a basic example of how to do conditional flow in a batch file depending on the powershell version

Generic example

powershell "exit $PSVersionTable.PSVersion.Major"
if %errorlevel% GEQ 5 (
    echo Do some fancy stuff that only powershell v5 or higher supports
) else (
    echo Functionality not support by current powershell version.
)

Real world example

powershell "exit $PSVersionTable.PSVersion.Major"
if %errorlevel% GEQ 5 (
    rem Unzip archive automatically
    powershell Expand-Archive Compressed.zip
) else (
    rem Make the user unzip, because lazy
    echo Please unzip Compressed.zip prior to continuing...
    pause
)

Verify object attribute value with mockito

New feature added to Mockito makes this even easier,

ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());

Take a look at Mockito documentation


In case when there are more than one parameters, and capturing of only single param is desired, use other ArgumentMatchers to wrap the rest of the arguments:

verify(mock).doSomething(eq(someValue), eq(someOtherValue), argument.capture());
assertEquals("John", argument.getValue().getName());

How to apply shell command to each line of a command output?

for s in `cmd`; do echo $s; done

If cmd has a large output:

cmd | xargs -L1 echo

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

os:Ubuntu18.04

mysql:5.7

  1. add the skip-grant-tables to the file end of mysqld.cnf

  2. cp the my.cnf

sudo cp /etc/mysql/mysql.conf.d/mysqld.cnf /etc/mysql/my.cnf
  1. reset the password
(base) ?  ~ sudo service mysql stop 
(base) ?  ~ sudo service mysql start
(base) ?  ~ mysql -uroot
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.25-0ubuntu0.18.04.2 (Ubuntu)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed, 3 warnings
mysql> update mysql.user set authentication_string=password('newpass') where user='root' and Host ='localhost';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> update user set plugin="mysql_native_password"; 
Query OK, 0 rows affected (0.00 sec)
Rows matched: 4  Changed: 0  Warnings: 0

mysql>  flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> quit
Bye
  1. remove theskip-grant-tables from my.cnf
(base) ?  ~ sudo emacs /etc/mysql/mysql.conf.d/mysqld.cnf 
(base) ?  ~ sudo emacs /etc/mysql/my.cnf                 
(base) ?  ~ sudo service mysql restart

  1. open the mysql
(base) ?  ~ mysql -uroot -ppassword 
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.25-0ubuntu0.18.04.2 (Ubuntu)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 
  1. check the password policy
mysql> select @@validate_password_policy;
+----------------------------+
| @@validate_password_policy |
+----------------------------+
| MEDIUM                     |
+----------------------------+
1 row in set (0.00 sec)


mysql> SHOW VARIABLES LIKE 'validate_password%';
+--------------------------------------+--------+
| Variable_name                        | Value  |
+--------------------------------------+--------+
| validate_password_dictionary_file    |        |
| validate_password_length             | 8      |
| validate_password_mixed_case_count   | 1      |
| validate_password_number_count       | 1      |
| validate_password_policy             | MEDIUM |
| validate_password_special_char_count | 1      |
+--------------------------------------+--------+
6 rows in set (0.08 sec)!
  1. change the config of the validate_password
mysql> set global validate_password_policy=0;
Query OK, 0 rows affected (0.05 sec)

mysql> set global validate_password_mixed_case_count=0;
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password_number_count=3;
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password_special_char_count=0;
Query OK, 0 rows affected (0.00 sec)

mysql> set global validate_password_length=3;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW VARIABLES LIKE 'validate_password%';
+--------------------------------------+-------+
| Variable_name                        | Value |
+--------------------------------------+-------+
| validate_password_dictionary_file    |       |
| validate_password_length             | 3     |
| validate_password_mixed_case_count   | 0     |
| validate_password_number_count       | 3     |
| validate_password_policy             | LOW   |
| validate_password_special_char_count | 0     |
+--------------------------------------+-------+
6 rows in set (0.00 sec)

note you should know that you error caused by what? validate_password_policy?

you should decided to reset the your password to fill the policy or change the policy.

Storing data into list with class

You need to create an instance of the class to add:

lstemail.Add(new EmailData
                 {
                     FirstName = "JOhn",
                     LastName = "Smith",
                     Location = "Los Angeles"
                 });

See How to: Initialize Objects by Using an Object Initializer (C# Programming Guide)


Alternatively you could declare a constructor for you EmailData object and use that to create the instance.

Read/Write 'Extended' file properties (C#)

Thank you guys for this thread! It helped me when I wanted to figure out an exe's file version. However, I needed to figure out the last bit myself of what is called Extended Properties.

If you open properties of an exe (or dll) file in Windows Explorer, you get a Version tab, and a view of Extended Properties of that file. I wanted to access one of those values.

The solution to this is the property indexer FolderItem.ExtendedProperty and if you drop all spaces in the property's name, you'll get the value. E.g. File Version goes FileVersion, and there you have it.

Hope this helps anyone else, just thought I'd add this info to this thread. Cheers!

How can I find the OWNER of an object in Oracle?

Interesting question - I don't think there's any Oracle function that does this (almost like a "which" command in Unix), but you can get the resolution order for the name by:

select * from 
(
 select  object_name objname, object_type, 'my object' details, 1 resolveOrder 
  from user_objects
  where object_type not like 'SYNONYM'
 union all
 select synonym_name obj , 'my synonym', table_owner||'.'||table_name, 2 resolveOrder
  from user_synonyms
 union all
 select  synonym_name obj , 'public synonym', table_owner||'.'||table_name, 3 resolveOrder
  from all_synonyms where owner = 'PUBLIC'
)
where objname like upper('&objOfInterest')

Remove whitespaces inside a string in javascript

You can use Strings replace method with a regular expression.

"Hello World ".replace(/ /g, "");

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp

RegExp

  • / / - Regular expression matching spaces

  • g - Global flag; find all matches rather than stopping after the first match

_x000D_
_x000D_
const str = "H    e            l l       o  World! ".replace(/ /g, "");_x000D_
document.getElementById("greeting").innerText = str;
_x000D_
<p id="greeting"><p>
_x000D_
_x000D_
_x000D_

git add only modified changes and ignore untracked files

This worked for me:

#!/bin/bash

git add `git status | grep modified | sed 's/\(.*modified:\s*\)//'`

Or even better:

$ git ls-files --modified | xargs git add

Form content type for a json HTTP POST?

It looks like people answered the first part of your question (use application/json).

For the second part: It is perfectly legal to send query parameters in a HTTP POST Request.

Example:

POST /members?id=1234 HTTP/1.1
Host: www.example.com
Content-Type: application/json

{"email":"[email protected]"}

Query parameters are commonly used in a POST request to refer to an existing resource. The above example would update the email address of an existing member with the id of 1234.

Twitter Bootstrap 3: how to use media queries?

you can see in my example font sizes and background colors are changing according to the screen size

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<style>_x000D_
body {_x000D_
    background-color: lightgreen;_x000D_
}_x000D_
/* Custom, iPhone Retina */ _x000D_
@media(max-width:320px){_x000D_
    body {_x000D_
        background-color: lime;_x000D_
        font-size:14px;_x000D_
     }_x000D_
}_x000D_
@media only screen and (min-width : 320px) {_x000D_
     body {_x000D_
        background-color: red;_x000D_
        font-size:18px;_x000D_
    }_x000D_
}_x000D_
/* Extra Small Devices, Phones */ _x000D_
@media only screen and (min-width : 480px) {_x000D_
     body {_x000D_
        background-color: aqua;_x000D_
        font-size:24px;_x000D_
    }_x000D_
}_x000D_
/* Small Devices, Tablets */_x000D_
@media only screen and (min-width : 768px) {_x000D_
     body {_x000D_
        background-color: green;_x000D_
        font-size:30px;_x000D_
    }_x000D_
}_x000D_
/* Medium Devices, Desktops */_x000D_
@media only screen and (min-width : 992px) {_x000D_
     body {_x000D_
        background-color: grey;_x000D_
        font-size:34px;_x000D_
    }_x000D_
}_x000D_
/* Large Devices, Wide Screens */_x000D_
@media only screen and (min-width : 1200px) {_x000D_
     body {_x000D_
        background-color: black;_x000D_
        font-size:42px;_x000D_
    }_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<p>Resize the browser window. When the width of this document is larger than the height, the background-color is "lightblue", otherwise it is "lightgreen".</p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to deal with certificates using Selenium?

I was able to do this on .net c# with PhantomJSDriver with selenium web driver 3.1

 [TestMethod]
    public void headless()
    {


        var driverService = PhantomJSDriverService.CreateDefaultService(@"C:\Driver\phantomjs\");
        driverService.SuppressInitialDiagnosticInformation = true;
        driverService.AddArgument("--web-security=no");
        driverService.AddArgument("--ignore-ssl-errors=yes");
        driver = new PhantomJSDriver(driverService);

        driver.Navigate().GoToUrl("XXXXXX.aspx");

        Thread.Sleep(6000);
    }

How to run Pip commands from CMD

Go to the folder where Python is installed .. and go to Scripts folder .

Do all this in CMD and then type :

pip

to check whether its there or not .

As soon as it shows some list it means that it is there .

Then type

pip install <package name you want to install>

How to disable SSL certificate checking with Spring RestTemplate?

Iknow It is too old to answer, but I couldn't find solution like this.

The code that worked for me with the jersey client:

import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;

import javax.net.ssl.*;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

public class Testi {

static {
    disableSslVerification();
}
private static void disableSslVerification() {
    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

public Testi() {
    MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<>();
    //... initialize headers

    Form form = new Form();
    Entity<Form> entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
    // initialize entity ...

    WebTarget target = getWebTarget();
    Object responseResult = target.path("api/test/path...").request()
            .headers(headers).post(entity, Object.class);

}

public static void main(String args[]) {
    new Testi();
}

private WebTarget getWebTarget() {
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 30000);
    clientConfig.property(ClientProperties.READ_TIMEOUT, 30000);

    SSLContext sc = getSSLContext();
    Client client = ClientBuilder.newBuilder().sslContext(sc).withConfig(clientConfig).build();
    WebTarget target = client.target("...url...");
    return target;
}

private SSLContext getSSLContext() {
    try {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }
        };

        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        return sc;
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}
}

How to select multiple files with <input type="file">?

You can do it now with HTML5

In essence you use the multiple attribute on the file input.

<input type='file' multiple>

Access to the requested object is only available from the local network phpmyadmin

after putting "Allow from all", you need to restart your xampp to apply the setting. thanks

How to remove unique key from mysql table

All keys are named, you should use something like this -

ALTER TABLE tbl_quiz_attempt_master
  DROP INDEX index_name;

To drop primary key use this one -

ALTER TABLE tbl_quiz_attempt_master
  DROP INDEX `PRIMARY`;

ALTER TABLE Syntax.

Is there a way that I can check if a data attribute exists?

And what about:

if ($('#dataTable[data-timer]').length > 0) {
    // logic here
}

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

I got a similar prompt. It was because I had specified the x-axis in terms of some percentage (for example: 10%A, 20%B,....). So an alternate approach could be that you multiply these values and write them in the simplest form.

How to access environment variable values?

Environment variables are accessed through os.environ

import os
print(os.environ['HOME'])

Or you can see a list of all the environment variables using:

os.environ

As sometimes you might need to see a complete list!

# using get will return `None` if a key is not present rather than raise a `KeyError`
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))

# os.getenv is equivalent, and can also give a default value instead of `None`
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))

Python default installation on Windows is C:\Python. If you want to find out while running python you can do:

import sys
print(sys.prefix)

Dropdownlist width in IE

Creating your own drop down list is more of a pain than it's worth. You can use some JavaScript to make the IE drop down work.

It uses a bit of the YUI library and a special extension for fixing IE select boxes.

You will need to include the following and wrap your <select> elements in a <span class="select-box">

Put these before the body tag of your page:

<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/yahoo_2.0.0-b3.js" type="text/javascript">
</script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/event_2.0.0-b3.js" type="text/javascript">
</script>
<script src="http://us.js2.yimg.com/us.js.yimg.com/lib/common/utils/2/dom_2.0.2-b3.js" type="text/javascript">
</script>
<script src="ie-select-width-fix.js" type="text/javascript">
</script>
<script>
// for each select box you want to affect, apply this:
var s1 = new YAHOO.Hack.FixIESelectWidth( 's1' ); // s1 is the ID of the select box you want to affect
</script>

Post acceptance edit:

You can also do this without the YUI library and Hack control. All you really need to do is put an onmouseover="this.style.width='auto'" onmouseout="this.style.width='100px'" (or whatever you want) on the select element. The YUI control gives it that nice animation but it's not necessary. This task can also be accomplished with jquery and other libraries (although, I haven't found explicit documentation for this)

-- amendment to the edit:
IE has a problem with the onmouseout for select controls (it doesn't consider mouseover on options being a mouseover on the select). This makes using a mouseout very tricky. The first solution is the best I've found so far.

How does Java import work?

Import in Java does not work at all, as it is evaluated at compile time only. (Treat it as shortcuts so you do not have to write fully qualified class names). At runtime there is no import at all, just FQCNs.

At runtime it is necessary that all classes you have referenced can be found by classloaders. (classloader infrastructure is sometimes dark magic and highly dependent on environment.) In case of an applet you will have to rig up your HTML tag properly and also provide necessary JAR archives on your server.

PS: Matching at runtime is done via qualified class names - class found under this name is not necessarily the same or compatible with class you have compiled against.

how to get the host url using javascript from the current page

This should work:

window.location.hostname

Getting text from td cells with jQuery

$(".field-group_name").each(function() {
        console.log($(this).text());
    });

How to send a HTTP OPTIONS request from the command line?

The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)

OPTIONS /path

You can send an OPTIONS request with curl like this:

curl -i -X OPTIONS http://example.org/path

You may also use -v instead of -i to see more output.

OPTIONS *

To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:

curl -i --request-target "*" -X OPTIONS http://example.org

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

No. Mostly because it's of a rather niche need, and there are too many possible variations. (Is it "KB", "Kb" or "Ko"? Is a megabyte 1024 * 1024 bytes, or 1024 * 1000 bytes? -- yes, some places use that!)

Convenient C++ struct initialisation

What about this syntax?

typedef struct
{
    int a;
    short b;
}
ABCD;

ABCD abc = { abc.a = 5, abc.b = 7 };

Just tested on a Microsoft Visual C++ 2015 and on g++ 6.0.2. Working OK.
You can make a specific macro also if you want to avoid duplicating variable name.

Python3 project remove __pycache__ folders and .pyc files

Since this is a Python 3 project, you only need to delete __pycache__ directories -- all .pyc/.pyo files are inside them.

find . -type d -name __pycache__ -exec rm -r {} \+

or its simpler form,

find . -type d -name __pycache__ -delete

which didn't work for me for some reason (files were deleted but directories weren't), so I'm including both for the sake of completeness.


Alternatively, if you're doing this in a directory that's under revision control, you can tell the RCS to ignore __pycache__ folders recursively. Then, at the required moment, just clean up all the ignored files. This will likely be more convenient because there'll probably be more to clean up than just __pycache__.

How to prevent rm from reporting that a file was not found?

I had same issue for cshell. The only solution I had was to create a dummy file that matched pattern before "rm" in my script.

'str' object does not support item assignment in Python

Another approach if you wanted to swap out a specific character for another character:

def swap(input_string):
   if len(input_string) == 0:
     return input_string
   if input_string[0] == "x":
     return "y" + swap(input_string[1:])
   else:
     return input_string[0] + swap(input_string[1:])

Get the time of a datetime using T-SQL?

CAST(CONVERT(CHAR(8),GETUTCDATE(),114) AS DATETIME)

IN SQL Server 2008+

CAST(GETUTCDATE() AS TIME)

What is the correct way to write HTML using Javascript?

I'm not particularly great at JavaScript or its best practices, but document.write() along with innerHtml() basically allows you to write out strings that may or may not be valid HTML; it's just characters. By using the DOM, you ensure proper, standards-compliant HTML that will keep your page from breaking via plainly bad HTML.

And, as Tom mentioned, JavaScript is done after the page is loaded; it'd probably be a better practice to have the initial setup for your page to be done via standard HTML (via .html files or whatever your server does [i.e. php]).

How to get the 'height' of the screen using jquery

use with responsive website (view in mobile or ipad)

jQuery(window).height();   // return height of browser viewport
jQuery(window).width();    // return width of browser viewport

rarely use

jQuery(document).height(); // return height of HTML document
jQuery(document).width();  // return width of HTML document

What is the best way to add options to a select from a JavaScript object with jQuery?

var output = [];

$.each(selectValues, function(key, value)
{
  output.push('<option value="'+ key +'">'+ value +'</option>');
});

$('#mySelect').html(output.join(''));

In this way you "touch the DOM" only one time.

I'm not sure if the latest line can be converted into $('#mySelect').html(output.join('')) because I don't know jQuery internals (maybe it does some parsing in the html() method)

VBA: Convert Text to Number

''Convert text to Number with ZERO Digits and Number convert ZERO Digits  

Sub ZERO_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0"
 Set rSelection = Nothing
End Sub

''Convert text to Number with TWO Digits and Number convert TWO Digits  

Sub TWO_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0.00"
 Set rSelection = Nothing
End Sub

''Convert text to Number with SIX Digits and Number convert SIX Digits  


Sub SIX_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0.000000"
 Set rSelection = Nothing
End Sub



Simple check for SELECT query empty result

Use @@ROWCOUNT:

SELECT * FROM service s WHERE s.service_id = ?;

IF @@ROWCOUNT > 0 
   -- do stuff here.....

According to SQL Server Books Online:

Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG.

Decrementing for loops

Check out the range documentation, you have to define a negative step:

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

Make a link use POST instead of GET

As mentioned in many posts, this is not directly possible, but an easy and successful way is as follows: First, we put a form in the body of our html page, which does not have any buttons for the submit, and also its inputs are hidden. Then we use a javascript function to get the data and ,send the form. One of the advantages of this method is to redirect to other pages, which depends on the server-side code. The code is as follows: and now in anywhere you need an to be in "POST" method:

<script type="text/javascript" language="javascript">
function post_link(data){

    $('#post_form').find('#form_input').val(data);
    $('#post_form').submit();
};
</script>

   <form id="post_form" action="anywhere/you/want/" method="POST">
 {% csrf_token %}
    <input id="form_input" type="hidden" value="" name="form_input">
</form>

<a href="javascript:{}" onclick="javascript:post_link('data');">post link is ready</a>

How can I make a checkbox readonly? not disabled?

Through CSS:

<label for="">
  <input type="checkbox" style="pointer-events: none; tabindex: -1;" checked> Label
</label>

pointer-events not supported in IE<10

https://jsfiddle.net/fl4sh/3r0v8pug/2/

getElementById returns null?

Also be careful how you execute the js on the page. For example if you do something like this:

(function(window, document, undefined){

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

  console.log(foo);

})(window, document, undefined); 

This will return null because you'd be calling the document before it was loaded.

Better option..

(function(window, document, undefined){

// code that should be taken care of right away

window.onload = init;

  function init(){
    // the code to be called when the dom has loaded
    // #document has its nodes
  }

})(window, document, undefined);

How to add element in Python to the end of list using list.insert?

list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append

Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]

Time complexity, append O(1), insert O(n)

Clear back stack using fragments

    private void clearBackStack(){
        SupportFragmentManaer fm = getSupportFragmentManager();
        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

Call to this method would be very neat.

  1. No Loop required.
  2. If you are using animation in fragments, it will not show too many animations. But using loop will.

Get everything after the dash in a string in JavaScript

For those trying to get everything after the first occurance:

Something like "Nic K Cage" to "K Cage".

You can use slice to get everything from a certain character. In this case from the first space:

const delim = " "
const name = "Nic K Cage"

const end = name.split(delim).slice(1).join(delim) // prints: "K Cage"

Or if OP's string had two hyphens:

const text = "sometext-20202-03"
// Option 1
const op1 = text.slice(text.indexOf('-')).slice(1) // prints: 20202-03
// Option 2
const op2 = text.split('-').slice(1).join("-")     // prints: 20202-03

"date(): It is not safe to rely on the system's timezone settings..."

A quick solution whilst your rectify the incompatibilities, is to disable error reporting in your index.php file:

Insert the line below into your index.php below define( ‘_JEXEC’, 1 );

error_reporting( E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR |
E_COMPILE_WARNING );

Calculating moving average

Though a bit slow but you can also use zoo::rollapply to perform calculations on matrices.

reqd_ma <- rollapply(x, FUN = mean, width = n)

where x is the data set, FUN = mean is the function; you can also change it to min, max, sd etc and width is the rolling window.

What is the best data type to use for money in C#?

decimal has a smaller range, but greater precision - so you don't lose all those pennies over time!

Full details here:

http://msdn.microsoft.com/en-us/library/364x0z75.aspx

ASP.NET MVC Razor render without encoding

You can also use the WriteLiteral method

AJAX POST and Plus Sign ( + ) -- How to Encode?

If you have to do a curl in php, you should use urlencode() from PHP but individually!

strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+")

If you do urlencode(strPOST), you will bring you another problem, you will have one Item1 and & will be change %xx value and be as one value, see down here the return!

Example 1

$strPOST = "Item1=" . $Value1 . "&Item2=" . urlencode("+") will give Item1=Value1&Item2=%2B

Example 2

$strPOST = urlencode("Item1=" . $Value1 . "&Item2=+") will give Item1%3DValue1%26Item2%3D%2B

Example 1 is the good way to prepare string for POST in curl

Example 2 show that the receptor will not see the equal and the ampersand to distinguish both value!

How can I select an element with multiple classes in jQuery?

You can do this using the filter() function:

$(".a").filter(".b")

Does C have a string type?

There is no string type in C. You have to use char arrays.

By the way your code will not work ,because the size of the array should allow for the whole array to fit in plus one additional zero terminating character.

Compare two objects in Java with possible null values

Since version 3.5 Apache Commons StringUtils has the following methods:

static int  compare(String str1, String str2)
static int  compare(String str1, String str2, boolean nullIsLess)
static int  compareIgnoreCase(String str1, String str2)
static int  compareIgnoreCase(String str1, String str2, boolean nullIsLess)

These provide null safe String comparison.

Which characters need to be escaped in HTML?

If you're inserting text content in your document in a location where text content is expected1, you typically only need to escape the same characters as you would in XML. Inside of an element, this just includes the entity escape ampersand & and the element delimiter less-than and greater-than signs < >:

& becomes &amp;
< becomes &lt;
> becomes &gt;

Inside of attribute values you must also escape the quote character you're using:

" becomes &quot;
' becomes &#39;

In some cases it may be safe to skip escaping some of these characters, but I encourage you to escape all five in all cases to reduce the chance of making a mistake.

If your document encoding does not support all of the characters that you're using, such as if you're trying to use emoji in an ASCII-encoded document, you also need to escape those. Most documents these days are encoded using the fully Unicode-supporting UTF-8 encoding where this won't be necessary.

In general, you should not escape spaces as &nbsp;. &nbsp; is not a normal space, it's a non-breaking space. You can use these instead of normal spaces to prevent a line break from being inserted between two words, or to insert          extra        space       without it being automatically collapsed, but this is usually a rare case. Don't do this unless you have a design constraint that requires it.


1 By "a location where text content is expected", I mean inside of an element or quoted attribute value where normal parsing rules apply. For example: <p>HERE</p> or <p title="HERE">...</p>. What I wrote above does not apply to content that has special parsing rules or meaning, such as inside of a script or style tag, or as an element or attribute name. For example: <NOT-HERE>...</NOT-HERE>, <script>NOT-HERE</script>, <style>NOT-HERE</style>, or <p NOT-HERE="...">...</p>.

In these contexts, the rules are more complicated and it's much easier to introduce a security vulnerability. I strongly discourage you from ever inserting dynamic content in any of these locations. I have seen teams of competent security-aware developers introduce vulnerabilities by assuming that they had encoded these values correctly, but missing an edge case. There's usually a safer alternative, such as putting the dynamic value in an attribute and then handling it with JavaScript.

If you must, please read the Open Web Application Security Project's XSS Prevention Rules to help understand some of the concerns you will need to keep in mind.

ValueError : I/O operation on closed file

file = open("filename.txt", newline='')
for row in self.data:
    print(row)

Save data to a variable(file), so you need a with.

How can I check if an InputStream is empty without reading from it?

If the InputStream you're using supports mark/reset support, you could also attempt to read the first byte of the stream and then reset it to its original position:

input.mark(1);
final int bytesRead = input.read(new byte[1]);
input.reset();
if (bytesRead != -1) {
    //stream not empty
} else {
    //stream empty
} 

If you don't control what kind of InputStream you're using, you can use the markSupported() method to check whether mark/reset will work on the stream, and fall back to the available() method or the java.io.PushbackInputStream method otherwise.

How do I get LaTeX to hyphenate a word that contains a dash?

I answered something similar here: LaTeX breaking up too many words

I said:

you should set a hyphenation penalty somewhere in your preamble:

\hyphenpenalty=750

The value of 750 suited my needs for a two column layout on letter paper (8.5x11 in) with a 12 pt font. Adjust the value to suit your needs. The higher the number, the less hyphenation will occur. You may also want to have a look at the hyphenatpackage, it provides a bit more than just hyphenation penalty

How to declare an array inside MS SQL Server Stored Procedure?

Great question and great idea, but in SQL you'll need to do this:

For data type datetime, something like this-

declare @BeginDate    datetime = '1/1/2016',
        @EndDate      datetime = '12/1/2016'
create table #months (dates datetime)
declare @var datetime = @BeginDate
   while @var < dateadd(MONTH, +1, @EndDate)
   Begin
          insert into #months Values(@var)
          set @var = Dateadd(MONTH, +1, @var)
   end

If all you really want is numbers, do this-

create table #numbas (digit int)
declare @var int = 1        --your starting digit
    while @var <= 12        --your ending digit
    begin
        insert into #numbas Values(@var)
        set @var = @var +1
    end

Visual Studio : short cut Key : Duplicate Line

for Visual Studio 2012, 2013, 2015, 2017 follow the link and download the extension

https://marketplace.visualstudio.com/items?itemName=ctlajoie.DuplicateSelection

Now go into Tools > Options > Keyboard, and type "Duplicate" in the search box (the full command string is "Edit.DuplicateSelection"). Here you can bind it to any shortcut in the same way you would for any other command.

How to catch SQLServer timeout exceptions

I am not sure but when we have execute time out or command time out The client sends an "ABORT" to SQL Server then simply abandons the query processing. No transaction is rolled back, no locks are released. to solve this problem I Remove transaction in Stored-procedure and use SQL Transaction in my .Net Code To manage sqlException

When and Why to use abstract classes/methods?

read the following article http://mycodelines.wordpress.com/2009/09/01/in-which-scenario-we-use-abstract-classes-and-interfaces/

Abstract Classes

–> When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.

For e.g. again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods / properties as abstract so they could be overridden by child classes.

–> The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.

For example a class library may define an abstract class that is used as a parameter to many of its functions and require programmers using that library to provide their own implementation of the class by creating a derived class.

Use an abstract class

When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library. ( COM was designed around interfaces.) Use an abstract class to define a common base class for a family of types. Use an abstract class to provide default behavior. Subclass only a base class in a hierarchy to which the class logically belongs.

What is the difference between a database and a data warehouse?

Data Warehouse vs Database: A data warehouse is specially designed for data analytics, which involves reading large amounts of data to understand relationships and trends across the data. A database is used to capture and store data, such as recording details of a transaction.

Data Warehouse: Suitable workloads - Analytics, reporting, big data. Data source - Data collected and normalized from many sources. Data capture - Bulk write operations typically on a predetermined batch schedule. Data normalization - Denormalized schemas, such as the Star schema or Snowflake schema. Data storage - Optimized for simplicity of access and high-speed query. performance using columnar storage. Data access - Optimized to minimize I/O and maximize data throughput.

Transactional Database: Suitable workloads - Transaction processing. Data source - Data captured as-is from a single source, such as a transactional system. Data capture - Optimized for continuous write operations as new data is available to maximize transaction throughput. Data normalization - Highly normalized, static schemas. Data storage - Optimized for high throughout write operations to a single row-oriented physical block. Data access - High volumes of small read operations.

How do I get the day of week given a date?

Say you have timeStamp: String variable, YYYY-MM-DD HH:MM:SS

step 1: convert it to dateTime function with blow code...

df['timeStamp'] = pd.to_datetime(df['timeStamp'])

Step 2 : Now you can extract all the required feature as below which will create new Column for each of the fild- hour,month,day of week,year, date

df['Hour'] = df['timeStamp'].apply(lambda time: time.hour)
df['Month'] = df['timeStamp'].apply(lambda time: time.month)
df['Day of Week'] = df['timeStamp'].apply(lambda time: time.dayofweek)
df['Year'] = df['timeStamp'].apply(lambda t: t.year)
df['Date'] = df['timeStamp'].apply(lambda t: t.day)

Calling a Function defined inside another function in Javascript

You can also try this.Here you are returning the function "inside" and invoking with the second set of parenthesis.

function outer() {
  return (function inside(){
    console.log("Inside inside function");
  });
}
outer()();

Or

function outer2() {
    let inside = function inside(){
      console.log("Inside inside");
    };
    return inside;
  }
outer2()();

How do you stash an untracked file?

You can simply do it with below command

git stash save --include-untracked

or

git stash save -u

For more about git stash Visit this post (Click Here)

Change Title of Javascript Alert

As others have said, you can't do that either using alert()or confirm().

You can, however, create an external HTML document containing your error message and an OK button, set its <title> element to whatever you want, then display it in a modal dialog box using showModalDialog().

Get the last inserted row ID (with SQL statement)

You can use:

SELECT IDENT_CURRENT('tablename')

to access the latest identity for a perticular table.

e.g. Considering following code:

INSERT INTO dbo.MyTable(columns....) VALUES(..........)

INSERT INTO dbo.YourTable(columns....) VALUES(..........)

SELECT IDENT_CURRENT('MyTable')

SELECT IDENT_CURRENT('YourTable')

This would yield to correct value for corresponding tables.

It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value.

IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

How do I find out what version of WordPress is running?

Because I can not comment to @Michelle 's answer, I post my trick here.

Instead of checking the version on meta tag that usually is removed by a customized theme.

Check the rss feed by append /feed to almost any link from that site, then search for some keywords (wordpress, generator), you will have a better chance.

<lastBuildDate>Fri, 29 May 2015 10:08:40 +0000</lastBuildDate>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<generator>http://wordpress.org/?v=4.2.2</generator>

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

How to SFTP with PHP?

PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp:// for protocol, e.g.

file_get_contents('ssh2.sftp://user:[email protected]:22/path/to/filename');

or - when also using the ssh2 extension

$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');

See http://php.net/manual/en/wrappers.ssh2.php

On a side note, there is also quite a bunch of questions about this topic already:

Visual studio code terminal, how to run a command with administrator rights?

Option 1 - Easier & Persistent

Running Visual Studio Code as Administrator should do the trick.

If you're on Windows you can:

  1. Right click the shortcut or app/exe
  2. Go to properties
  3. Compatibility tab
  4. Check "Run this program as an administrator"
There is a caveat to it though

Make sure you have all other instances of VS Code closed and then try to run as Administrator. The electron framework likes to stall processes when closing them so it's best to check your task manager and kill the remaining processes.

Related Changes in Codebase

Option 2 - More like Sudo

If for some weird reason this is not running your commands as an Administrator you can try the runas command. Microsoft: runas command

Examples
  • runas /user:Administrator myCommand
  • runas "/user:First Last" "my command"
Notes
  • Just don't forget to put double quotes around anything that has a space in it.
  • Also it's quite possible that you have never set the password on the Administrator account, as it will ask you for the password when trying to run the command. You can always use an account without the username of Administrator if it has administrator access rights/permissions.

How to open a web server port on EC2 instance

You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Correct Method is

.PopupPanel
{
    border: solid 1px black;
    position: fixed;
    left: 50%;
    top: 50%;
    background-color: white;
    z-index: 100;
    height: 400px;
    margin-top: -200px;

    width: 600px;
    margin-left: -300px;
}

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

If you just want the bitmap, This too works

InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();

sample uri : content://media/external/images/media/12345

No Application Encryption Key Has Been Specified

simply run

php artisan key:generate

its worked for me

Eclipse "Invalid Project Description" when creating new project from existing source

If you wish to open a new project from an existing source code in the following way:

File -> Import -> General -> Existing Project into Workspace

you still have the message "Invalid Project Description". I solve it just by going in

File -> Switch Workspace

and choosing one of the recent workspaces.

Programmatically set left drawable in a TextView

You can use setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)

set 0 where you don't want images

Example for Drawable on the left:

TextView textView = (TextView) findViewById(R.id.myTxtView);
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);

Alternatively, you can use setCompoundDrawablesRelativeWithIntrinsicBounds to respect RTL/LTR layouts.


Tip: Whenever you know any XML attribute but don't have clue about how to use it at runtime. just go to the description of that property in developer doc. There you will find Related Methods if it's supported at runtime . i.e. For DrawableLeft

How to join entries in a set into one string?

The join is called on the string:

print ", ".join(set_3)

How do I copy the contents of one stream to another?

For .NET 3.5 and before try :

MemoryStream1.WriteTo(MemoryStream2);

How can I comment a single line in XML?

As others have said, there is no way to do a single line comment legally in XML that comments out multiple lines, but, there are ways to make commenting out segments of XML easier.

Looking at the example below, if you add '>' to line one, the XmlTag will be uncommented. Remove the '>' and it's commented out again. This is the simplest way that I've seen to quickly comment/uncomment XML without breaking things.

<!-- --
<XmlTag variable="0" />
<!-- -->

The added benefit is that you only manipulate the top comment, and the bottom comment can just sit there forever. This breaks compatibility with SGML and some XML parsers will barf on it. So long as this isn't a permanent fixture in your XML, and your parsers accept it, it's not really a problem.

Stack Overflow's and Notepad++'s syntax highlighter treat it like a multi-line comment, C++'s Boost library treats it as a multi-line comment, and the only parser I've found so far that breaks is the one in .NET, specifically C#. So, be sure to first test that your tools, IDE, libraries, language, etc. accept it before using it.

If you care about SGML compatibility, simply use this instead:

<!-- -
<XmlTag variable="0" />
<!- -->

Add '->' to the top comment and a '-' to the bottom comment. The downside is having to edit the bottom comment each time, which would probably make it easier to just type in <!-- at the top and --> at the bottom each time.

I also want to mention that other commenters recommend using an XML editor that allows you to right-click and comment/uncomment blocks of XML, which is probably preferable over fancy find/replace tricks (it would also make for a good answer in itself, but I've never used such tools. I just want to make sure the information isn't lost over time). I've personally never had to deal with XML enough to justify having an editor fancier than Notepad++, so this is totally up to you.

Get paragraph text inside an element

Add an Id property into the P tag with value like text or something:

function gettext() {
    var amount = document.getElementById('text').value;
}

Logical operators for boolean indexing in Pandas

TLDR; Logical Operators in Pandas are &, | and ~, and parentheses (...) is important!

Python's and, or and not logical operators are designed to work with scalars. So Pandas had to do one better and override the bitwise operators to achieve vectorized (element-wise) version of this functionality.

So the following in python (exp1 and exp2 are expressions which evaluate to a boolean result)...

exp1 and exp2              # Logical AND
exp1 or exp2               # Logical OR
not exp1                   # Logical NOT

...will translate to...

exp1 & exp2                # Element-wise logical AND
exp1 | exp2                # Element-wise logical OR
~exp1                      # Element-wise logical NOT

for pandas.

If in the process of performing logical operation you get a ValueError, then you need to use parentheses for grouping:

(exp1) op (exp2)

For example,

(df['col1'] == x) & (df['col2'] == y) 

And so on.


Boolean Indexing: A common operation is to compute boolean masks through logical conditions to filter the data. Pandas provides three operators: & for logical AND, | for logical OR, and ~ for logical NOT.

Consider the following setup:

np.random.seed(0)
df = pd.DataFrame(np.random.choice(10, (5, 3)), columns=list('ABC'))
df

   A  B  C
0  5  0  3
1  3  7  9
2  3  5  2
3  4  7  6
4  8  8  1

Logical AND

For df above, say you'd like to return all rows where A < 5 and B > 5. This is done by computing masks for each condition separately, and ANDing them.

Overloaded Bitwise & Operator
Before continuing, please take note of this particular excerpt of the docs, which state

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses, since by default Python will evaluate an expression such as df.A > 2 & df.B < 3 as df.A > (2 & df.B) < 3, while the desired evaluation order is (df.A > 2) & (df.B < 3).

So, with this in mind, element wise logical AND can be implemented with the bitwise operator &:

df['A'] < 5

0    False
1     True
2     True
3     True
4    False
Name: A, dtype: bool

df['B'] > 5

0    False
1     True
2    False
3     True
4     True
Name: B, dtype: bool

(df['A'] < 5) & (df['B'] > 5)

0    False
1     True
2    False
3     True
4    False
dtype: bool

And the subsequent filtering step is simply,

df[(df['A'] < 5) & (df['B'] > 5)]

   A  B  C
1  3  7  9
3  4  7  6

The parentheses are used to override the default precedence order of bitwise operators, which have higher precedence over the conditional operators < and >. See the section of Operator Precedence in the python docs.

If you do not use parentheses, the expression is evaluated incorrectly. For example, if you accidentally attempt something such as

df['A'] < 5 & df['B'] > 5

It is parsed as

df['A'] < (5 & df['B']) > 5

Which becomes,

df['A'] < something_you_dont_want > 5

Which becomes (see the python docs on chained operator comparison),

(df['A'] < something_you_dont_want) and (something_you_dont_want > 5)

Which becomes,

# Both operands are Series...
something_else_you_dont_want1 and something_else_you_dont_want2

Which throws

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

So, don't make that mistake!1

Avoiding Parentheses Grouping
The fix is actually quite simple. Most operators have a corresponding bound method for DataFrames. If the individual masks are built up using functions instead of conditional operators, you will no longer need to group by parens to specify evaluation order:

df['A'].lt(5)

0     True
1     True
2     True
3     True
4    False
Name: A, dtype: bool

df['B'].gt(5)

0    False
1     True
2    False
3     True
4     True
Name: B, dtype: bool

df['A'].lt(5) & df['B'].gt(5)

0    False
1     True
2    False
3     True
4    False
dtype: bool

See the section on Flexible Comparisons.. To summarise, we have

+------------------------------+
¦    ¦ Operator   ¦ Function   ¦
¦----+------------+------------¦
¦  0 ¦ >          ¦ gt         ¦
+----+------------+------------¦
¦  1 ¦ >=         ¦ ge         ¦
+----+------------+------------¦
¦  2 ¦ <          ¦ lt         ¦
+----+------------+------------¦
¦  3 ¦ <=         ¦ le         ¦
+----+------------+------------¦
¦  4 ¦ ==         ¦ eq         ¦
+----+------------+------------¦
¦  5 ¦ !=         ¦ ne         ¦
+------------------------------+

Another option for avoiding parentheses is to use DataFrame.query (or eval):

df.query('A < 5 and B > 5')

   A  B  C
1  3  7  9
3  4  7  6

I have extensively documented query and eval in Dynamic Expression Evaluation in pandas using pd.eval().

operator.and_
Allows you to perform this operation in a functional manner. Internally calls Series.__and__ which corresponds to the bitwise operator.

import operator 

operator.and_(df['A'] < 5, df['B'] > 5)
# Same as,
# (df['A'] < 5).__and__(df['B'] > 5) 

0    False
1     True
2    False
3     True
4    False
dtype: bool

df[operator.and_(df['A'] < 5, df['B'] > 5)]

   A  B  C
1  3  7  9
3  4  7  6

You won't usually need this, but it is useful to know.

Generalizing: np.logical_and (and logical_and.reduce)
Another alternative is using np.logical_and, which also does not need parentheses grouping:

np.logical_and(df['A'] < 5, df['B'] > 5)

0    False
1     True
2    False
3     True
4    False
Name: A, dtype: bool

df[np.logical_and(df['A'] < 5, df['B'] > 5)]

   A  B  C
1  3  7  9
3  4  7  6

np.logical_and is a ufunc (Universal Functions), and most ufuncs have a reduce method. This means it is easier to generalise with logical_and if you have multiple masks to AND. For example, to AND masks m1 and m2 and m3 with &, you would have to do

m1 & m2 & m3

However, an easier option is

np.logical_and.reduce([m1, m2, m3])

This is powerful, because it lets you build on top of this with more complex logic (for example, dynamically generating masks in a list comprehension and adding all of them):

import operator

cols = ['A', 'B']
ops = [np.less, np.greater]
values = [5, 5]

m = np.logical_and.reduce([op(df[c], v) for op, c, v in zip(ops, cols, values)])
m 
# array([False,  True, False,  True, False])

df[m]
   A  B  C
1  3  7  9
3  4  7  6

1 - I know I'm harping on this point, but please bear with me. This is a very, very common beginner's mistake, and must be explained very thoroughly.


Logical OR

For the df above, say you'd like to return all rows where A == 3 or B == 7.

Overloaded Bitwise |

df['A'] == 3

0    False
1     True
2     True
3    False
4    False
Name: A, dtype: bool

df['B'] == 7

0    False
1     True
2    False
3     True
4    False
Name: B, dtype: bool

(df['A'] == 3) | (df['B'] == 7)

0    False
1     True
2     True
3     True
4    False
dtype: bool

df[(df['A'] == 3) | (df['B'] == 7)]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

If you haven't yet, please also read the section on Logical AND above, all caveats apply here.

Alternatively, this operation can be specified with

df[df['A'].eq(3) | df['B'].eq(7)]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

operator.or_
Calls Series.__or__ under the hood.

operator.or_(df['A'] == 3, df['B'] == 7)
# Same as,
# (df['A'] == 3).__or__(df['B'] == 7)

0    False
1     True
2     True
3     True
4    False
dtype: bool

df[operator.or_(df['A'] == 3, df['B'] == 7)]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

np.logical_or
For two conditions, use logical_or:

np.logical_or(df['A'] == 3, df['B'] == 7)

0    False
1     True
2     True
3     True
4    False
Name: A, dtype: bool

df[np.logical_or(df['A'] == 3, df['B'] == 7)]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

For multiple masks, use logical_or.reduce:

np.logical_or.reduce([df['A'] == 3, df['B'] == 7])
# array([False,  True,  True,  True, False])

df[np.logical_or.reduce([df['A'] == 3, df['B'] == 7])]

   A  B  C
1  3  7  9
2  3  5  2
3  4  7  6

Logical NOT

Given a mask, such as

mask = pd.Series([True, True, False])

If you need to invert every boolean value (so that the end result is [False, False, True]), then you can use any of the methods below.

Bitwise ~

~mask

0    False
1    False
2     True
dtype: bool

Again, expressions need to be parenthesised.

~(df['A'] == 3)

0     True
1    False
2    False
3     True
4     True
Name: A, dtype: bool

This internally calls

mask.__invert__()

0    False
1    False
2     True
dtype: bool

But don't use it directly.

operator.inv
Internally calls __invert__ on the Series.

operator.inv(mask)

0    False
1    False
2     True
dtype: bool

np.logical_not
This is the numpy variant.

np.logical_not(mask)

0    False
1    False
2     True
dtype: bool

Note, np.logical_and can be substituted for np.bitwise_and, logical_or with bitwise_or, and logical_not with invert.

Inserting the same value multiple times when formatting a string

>>> s1 ='arbit'
>>> s2 = 'hello world '.join( [s]*3 )
>>> print s2
arbit hello world arbit hello world arbit

Best data type to store money values in MySQL

Indeed this relies on the programmer's preferences. I personally use: numeric(15,4) to conform to the Generally Accepted Accounting Principles (GAAP).

Pythonic way of checking if a condition holds for any element of a list

any():

if any(t < 0 for t in x):
    # do something

Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:

if True in (t < 0 for t in x):

iOS: Modal ViewController with transparent background

I struggled a bit with the Interface Builder of XCode 7 to set the Presentation Style as @VenuGopalTewari suggested. In this version, there seems to be no Over Current Context or Over Full Screen presentation mode for the segue. Thus, to make it work, I set the mode to Default:

enter image description here with enter image description here

Additionally I set the presentation mode of the modally presented view controller to Over Full Screen:

enter image description here

How to parse Excel (XLS) file in Javascript/HTML5

If you want the simplest and tiniest way of reading an *.xlsx file in a browser then this library might do:

https://catamphetamine.github.io/read-excel-file/

<input type="file" id="input" />
import readXlsxFile from 'read-excel-file'

const input = document.getElementById('input')

input.addEventListener('change', () => {
  readXlsxFile(input.files[0]).then((data) => {
    // `data` is an array of rows
    // each row being an array of cells.
  })
})

In the example above data is raw string data. It can be parsed to JSON with a strict schema by passing schema argument. See API docs for an example of that.

API docs: http://npmjs.com/package/read-excel-file

How to restore the menu bar in Visual Studio Code

Another way to restore the menu bar is to trigger the View: Toggle Menu Bar command in the command palette (F1).

How to update-alternatives to Python 3 without breaking apt?

Somehow python 3 came back (after some updates?) and is causing big issues with apt updates, so I've decided to remove python 3 completely from the alternatives:

root:~# python -V
Python 3.5.2

root:~# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/python3.5   3         auto mode
  1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.5   3         manual mode


root:~# update-alternatives --remove python /usr/bin/python3.5

root:~# update-alternatives --config python
There is 1 choice for the alternative python (providing /usr/bin/python).

    Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python2.7   2         auto mode
* 1            /usr/bin/python2.7   2         manual mode

Press <enter> to keep the current choice[*], or type selection number: 0


root:~# python -V
Python 2.7.12

root:~# update-alternatives --config python
There is only one alternative in link group python (providing /usr/bin/python): /usr/bin/python2.7
Nothing to configure.

Get the position of a div/span tag

You can call the method getBoundingClientRect() on a reference to the element. Then you can examine the top, left, right and/or bottom properties...

var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;

If using jQuery, you can use the more succinct code...

var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

That heavily depends on the structure of the search tree and the number and location of solutions (aka searched-for items).

  • If you know a solution is not far from the root of the tree, a breadth first search (BFS) might be better.

  • If the tree is very deep and solutions are rare, depth first search (DFS) might take an extremely long time, but BFS could be faster.

  • If the tree is very wide, a BFS might need too much memory, so it might be completely impractical.

  • If solutions are frequent but located deep in the tree, BFS could be impractical.

  • If the search tree is very deep you will need to restrict the search depth for depth first search (DFS), anyway (for example with iterative deepening).

But these are just rules of thumb; you'll probably need to experiment.

Another issue is parallelism: if you want to parallelize BFS you would need a shared datastructure between threads, which is a bad thing. DFS might be easier to distribute even between connected machines if you don't insist on the exact order of visiting the nodes.

Android Studio : unmappable character for encoding UTF-8

In Android Studio resolved it by

  1. Navigate to File > Editor > File Encodings.
  2. In global encoding set the encoding to ISO-8859-1
  3. In Project encoding set the encoding to UTF-8 and the same case to Default encoding for properties files.
  4. Rebuild project.

How to wait in a batch script?

What about:

@echo off
set wait=%1
echo waiting %wait% s
echo wscript.sleep %wait%000 > wait.vbs
wscript.exe wait.vbs
del wait.vbs

How do I add a linker or compile flag in a CMake file?

Suppose you want to add those flags (better to declare them in a constant):

SET(GCC_COVERAGE_COMPILE_FLAGS "-fprofile-arcs -ftest-coverage")
SET(GCC_COVERAGE_LINK_FLAGS    "-lgcov")

There are several ways to add them:

  1. The easiest one (not clean, but easy and convenient, and works only for compile flags, C & C++ at once):

    add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})
    
  2. Appending to corresponding CMake variables:

    SET(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
    SET(CMAKE_EXE_LINKER_FLAGS  "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")
    
  3. Using target properties, cf. doc CMake compile flag target property and need to know the target name.

    get_target_property(TEMP ${THE_TARGET} COMPILE_FLAGS)
    if(TEMP STREQUAL "TEMP-NOTFOUND")
      SET(TEMP "") # Set to empty string
    else()
      SET(TEMP "${TEMP} ") # A space to cleanly separate from existing content
    endif()
    # Append our values
    SET(TEMP "${TEMP}${GCC_COVERAGE_COMPILE_FLAGS}" )
    set_target_properties(${THE_TARGET} PROPERTIES COMPILE_FLAGS ${TEMP} )
    

Right now I use method 2.

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

To solve the problem in my case it was just missing this line

<tx:annotation-driven transaction-manager="myTxManager" />

in the application-context file.

The @Transactional annotation over a method was not taken into account.

Hope the answer will help someone

How to split one text file into multiple *.txt files?

$ split -l 100 input_file output_file

where -l is the number of lines in each files. This will create:

  • output_fileaa
  • output_fileab
  • output_fileac
  • output_filead
  • ....

Zsh: Conda/Pip installs command not found

If you are on macOS Catalina, the new default shell is zsh. You will need to run source /bin/activate followed by conda init zsh. For example: I installed anaconda python 3.7 Version, type echo $USER to find username

source /Users/my_username/opt/anaconda3/bin/activate

Follow by

conda init zsh

or (for bash shell)

conda init

Check working:

conda list

The error will be fixed.

How to import a Python class that is in a directory above?

Here's a three-step, somewhat minimalist version of ThorSummoner's answer for the sake of clarity. It doesn't quite do what I want (I'll explain at the bottom), but it works okay.

Step 1: Make directory and setup.py

filepath_to/project_name/
    setup.py

In setup.py, write:

import setuptools

setuptools.setup(name='project_name')

Step 2: Install this directory as a package

Run this code in console:

python -m pip install --editable filepath_to/project_name

Instead of python, you may need to use python3 or something, depending on how your python is installed. Also, you can use -e instead of --editable.

Now, your directory will look more or less like this. I don't know what the egg stuff is.

filepath_to/project_name/
    setup.py
    test_3.egg-info/
        dependency_links.txt
        PKG-INFO
        SOURCES.txt
        top_level.txt

This folder is considered a python package and you can import from files in this parent directory even if you're writing a script anywhere else on your computer.

Step 3. Import from above

Let's say you make two files, one in your project's main directory and another in a sub directory. It'll look like this:

filepath_to/project_name/
    top_level_file.py
    subdirectory/
        subfile.py

    setup.py          |
    test_3.egg-info/  |----- Ignore these guys
        ...           |

Now, if top_level_file.py looks like this:

x = 1

Then I can import it from subfile.py, or really any other file anywhere else on your computer.

# subfile.py  OR  some_other_python_file_somewhere_else.py

import random # This is a standard package that can be imported anywhere.
import top_level_file # Now, top_level_file.py works similarly.

print(top_level_file.x)

This is different than what I was looking for: I hoped python had a one-line way to import from a file above. Instead, I have to treat the script like a module, do a bunch of boilerplate, and install it globally for the entire python installation to have access to it. It's overkill. If anyone has a simpler method than doesn't involve the above process or importlib shenanigans, please let me know.

Import python package from local directory into interpreter

I used pathlib to add my module directory to my system path as I wanted to avoid installing the module as a package and @maninthecomputer response didn't work for me

import sys
from pathlib import Path

cwd = str(Path(__file__).parent)
sys.path.insert(0, cwd)
from my_module import my_function

Rock, Paper, Scissors Game Java

I would recommend making Rock, Paper and Scissors objects. The objects would have the logic of both translating to/from Strings and also "knowing" what beats what. The Java enum is perfect for this.

public enum Type{

  ROCK, PAPER, SCISSOR;

  public static Type parseType(String value){
     //if /else logic here to return either ROCK, PAPER or SCISSOR

     //if value is not either, you can return null
  }
}

The parseType method can return null if the String is not a valid type. And you code can check if the value is null and if so, print "invalid try again" and loop back to re-read the Scanner.

Type person=null;

 while(person==null){
      System.out.println("Enter your play: "); 
      person= Type.parseType(scan.next());
      if(person ==null){
         System.out.println("invalid try again");
      }
 }

Furthermore, your type enum can determine what beats what by having each Type object know:

public enum Type{

    //...

    //each type will implement this method differently
    public abstract boolean beats(Type other);


}

each type will implement this method differently to see what beats what:

ROCK{

   @Override
   public boolean beats(Type other){            
        return other ==  SCISSOR;

   }
}

 ...

Then in your code

 Type person, computer;
   if (person.equals(computer)) 
   System.out.println("It's a tie!");
  }else if(person.beats(computer)){
     System.out.println(person+ " beats " + computer + "You win!!"); 
  }else{
     System.out.println(computer + " beats " + person+ "You lose!!");
  }

How do I remove/delete a virtualenv?

The following command works for me.

rm -rf /path/to/virtualenv

What is a practical use for a closure in JavaScript?

I like Mozilla's function factory example.

function makeAdder(x) {

    return function(y) {
        return x + y;
    };
}

var addFive = makeAdder(5);

console.assert(addFive(2) === 7);
console.assert(addFive(-5) === 0);

How to get disk capacity and free space of remote computer

In case you want to check multiple drive letters and/or filter between local and network drives, you can use PowerShell to take advantage of the Win32_LogicalDisk WMI class. Here's a quick example:

$localVolumes = Get-WMIObject win32_volume;

foreach ($vol in $localVolumes) {
  if ($vol.DriveLetter -ne $null ) {
    $d = $vol.DriveLetter[0];
    if ($vol.DriveType -eq 3) {
      Write-Host ("Drive " + $d + " is a Local Drive");
    }
    elseif ($vol.DriveType -eq 4) {
      Write-Host ("Drive" + $d + " is a Network Drive");
    }
    else {
      // ... and so on
    }

    $drive = Get-PSDrive $d;
    Write-Host ("Used space on drive " + $d + ": " + $drive.Used + " bytes. `r`n");
    Write-Host ("Free space on drive " + $d + ": " + $drive.Free + " bytes. `r`n");
  }
}

I used the above technique to create a Powershell script that checks all drives and send an e-mail alert whenever they go below a user-defined quota. You can get it from this post on my blog.

Does SVG support embedding of bitmap images?

You could use a Data URI to supply the image data, for example:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

<image width="20" height="20" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>

</svg>

The image will go through all normal svg transformations.

But this technique has disadvantages, for example the image will not be cached by the browser

What is the correct JSON content type?

As some research,

Most commonly MIME type is

application/json

Let's see a example to differentiate with json and javascript.

  • application/json

It is used when it is not known how this data will be used. When the information is to be just extracted from the server in JSON format, it may be through a link or from any file, in that case, it is used.

For example-

<?php 
  
header('Content-type:application/json');     
   
$directory =[ 

    ['Id'=> 1, 'Name' => 'this' ], 

    ['Id'=> 2, 'Name' => 'is'], 

    ['Id'=> 3, 'Name' => 'stackoverflow'], 

      ]; 

    
// Showing the json data 

echo json_encode($directory);     


   ?>

Output is,

[{"Id":1, "Name":"this"}, {"Id":2, "Name":"is"}, {"Id":3, "Name":"stackoverflow"}]

  • application/javascript

it is used when the use of the data is predefined. It is used by applications in which there are calls by the client-side ajax applications. It is used when the data is of type JSON-P or JSONP. 

For example

<?php 

header('Content-type:application/javascript'); 

$dir =[ 

    ['Id'=> 1, 'Name' => 'this' ], 

    ['Id'=> 2, 'Name' => 'is'], 

    ['Id'=> 3, 'Name' => 'stackoverflow'], 

      ]; 

echo "Function_call(".json_encode($dir).");"; 

  

?> 

Output is,

Function_call([{"Id":1, "Name":"this"}, {"Id":2, "Name":"is"}, {"Id":3, "Name":"stackoverflow"}])

And for other MIME Types see full detail here,

https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types

Javascript get the text value of a column from a particular row of an html table

document.getElementById("tblBlah").rows[i].columns[j].innerHTML;

Should be:

document.getElementById("tblBlah").rows[i].cells[j].innerHTML;

But I get the distinct impression that the row/cell you need is the one clicked by the user. If so, the simplest way to achieve this would be attaching an event to the cells in your table:

function alertInnerHTML(e)
{
    e = e || window.event;//IE
    alert(this.innerHTML);
}

var theTbl = document.getElementById('tblBlah');
for(var i=0;i<theTbl.length;i++)
{
    for(var j=0;j<theTbl.rows[i].cells.length;j++)
    {
        theTbl.rows[i].cells[j].onclick = alertInnerHTML;
    }
}

That makes all table cells clickable, and alert it's innerHTML. The event object will be passed to the alertInnerHTML function, in which the this object will be a reference to the cell that was clicked. The event object offers you tons of neat tricks on how you want the click event to behave if, say, there's a link in the cell that was clicked, but I suggest checking the MDN and MSDN (for the window.event object)

How to find out line-endings in a text file?

You can use vim -b filename to edit a file in binary mode, which will show ^M characters for carriage return and a new line is indicative of LF being present, indicating Windows CRLF line endings. By LF I mean \n and by CR I mean \r. Note that when you use the -b option the file will always be edited in UNIX mode by default as indicated by [unix] in the status line, meaning that if you add new lines they will end with LF, not CRLF. If you use normal vim without -b on a file with CRLF line endings, you should see [dos] shown in the status line and inserted lines will have CRLF as end of line. The vim documentation for fileformats setting explains the complexities.

Also, I don't have enough points to comment on the Notepad++ answer, but if you use Notepad++ on Windows, use the View / Show Symbol / Show End of Line menu to display CR and LF. In this case LF is shown whereas for vim the LF is indicated by a new line.

How to increase MySQL connections(max_connections)?

I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:

  1. in the navigator (on the left side), under the section "management", click on "Status and System variables",
  2. then choose "system variables" (tab at the top),
  3. then search for "connection" in the search field,
  4. and 5. you will see two fields that need to be adjusted to fit your needs (max_connections and mysqlx_max_connections).

Hope that helps!

The system does not allow me to upload pictures, instead please click on this link and you can see my screenshot...

Convert INT to DATETIME (SQL)

you need to convert to char first because converting to int adds those days to 1900-01-01

select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))

here are some examples

select CONVERT (datetime,5)

1900-01-06 00:00:00.000

select CONVERT (datetime,20100101)

blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit

convert to char first

declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))

Return None if Dictionary key is not available

You can use dict.get()

value = d.get(key)

which will return None if key is not in d. You can also provide a different default value that will be returned instead of None:

value = d.get(key, "empty")

How to make a phone call in android and come back to my activity when the call is done?

This is solution from my point of view:

ok.setOnClickListener(this);
@Override
public void onClick(View view) {
    if(view == ok){
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + num));
        activity.startActivity(intent);

    }

Of course in Activity (class) definition you have to implement View.OnClickListener .

Origin <origin> is not allowed by Access-Control-Allow-Origin

I was facing a problem while calling cross origin resource using ajax from chrome.

I have used node js and local http server to deploy my node js app.

I was getting error response, when I access cross origin resource

I found one solution on that ,

1) I have added below code to my app.js file

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");

2) In my html page called cross origin resource using $.getJSON();

$.getJSON("http://localhost:3000/users", function (data) {
    alert("*******Success*********");
    var response=JSON.stringify(data);
    alert("success="+response);
    document.getElementById("employeeDetails").value=response;
});

Batch file to copy files from one folder to another folder

To bypass the 'specify a file name or directory name on the target (F = file, D = directory)?' prompt with xcopy, you can do the following...

echo f | xcopy /f /y srcfile destfile

or for those of us just copying large substructures/folders:

use /i which specifies destination must be a directory if copying more than one file

How to do a less than or equal to filter in Django queryset?

Less than or equal:

User.objects.filter(userprofile__level__lte=0)

Greater than or equal:

User.objects.filter(userprofile__level__gte=0)

Likewise, lt for less than and gt for greater than. You can find them all in the documentation.

Difference between volatile and synchronized in Java

volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:

    int i1;
    int geti1() {return i1;}

    volatile int i2;
    int geti2() {return i2;}

    int i3;
    synchronized int geti3() {return i3;}

geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads.In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.

On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Generally volatile variables have a higher access and update overhead than "plain" variables. Generally threads are allowed to have their own copy of data is for better efficiency.

There are two differences between volitile and synchronized.

Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block. That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:

  1. The thread acquires the lock on the monitor for object this .
  2. The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory .
  3. The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
  4. (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
  5. The thread releases the lock on the monitor for object this.

So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

http://javaexp.blogspot.com/2007/12/difference-between-volatile-and.html

How do I handle the window close event in Tkinter?

You should use destroy() to close a tkinter window.

   from Tkinter import *
   root = Tk()
   Button(root, text="Quit", command=root.destroy).pack()
   root.mainloop()

Explanation:

root.quit() The above line just Bypasses the root.mainloop() i.e root.mainloop() will still be running in background if quit() command is executed.

root.destroy() While destroy() command vanish out root.mainloop() i.e root.mainloop() stops.

So as you just want to quit the program so you should use root.destroy() as it will it stop the mainloop()`.

But if you want to run some infinite loop and you don't want to destroy your Tk window and want to execute some code after root.mainloop() line then you should use root.quit(). Ex:

from Tkinter import *
def quit():
    global root
    root.quit()

root = Tk()
while True:
    Button(root, text="Quit", command=quit).pack()
    root.mainloop()
    #do something

ARG or ENV, which one to use in this case?

So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.

While ENV, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args at every build without changing our docker file.

For more details, you can refer this.

How can I add a space in between two outputs?

import java.util.Scanner;
public class class2 {

    public void Multipleclass(){
       String x,y;
       Scanner sc=new Scanner(System.in);

       System.out.println("Enter your First name");
       x=sc.next();
       System.out.println("Enter your Last name");
       y=sc.next();

       System.out.println(x+  " "  +y );
   }
}

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

Other than using the Navigator/Proj Explorer and choosing files and doing 'Compare With'->'Each other'... I prefer opening both files in Eclipse and using 'Compare With'->'Opened Editor'->(pick the opened tab)... You can get this feature via the AnyEdit eclipse plugin located here (you can use Install Software via Eclipse->Help->Install New Software screen): http://andrei.gmxhome.de/eclipse/

Is an HTTPS query string secure?

You can send password as MD5 hash param with some salt added. Compare it on the server side for auth.

SQL - Select first 10 rows only?

SELECT *  
  FROM (SELECT ROW_NUMBER () OVER (ORDER BY user_id) user_row_no, a.* FROM temp_emp a)  
 WHERE user_row_no > 1 and user_row_no <11  

This worked for me.If i may,i have few useful dbscripts that you can have look at

Useful Dbscripts

Parse XML using JavaScript

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;
if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Which I got from https://stackoverflow.com/a/8412989/1232175.

Calculate business days

<?php
// $today is the UNIX timestamp for today's date
$today = time();
echo "<strong>Today is (ORDER DATE): " . '<font color="red">' . date('l, F j, Y', $today) . "</font></strong><br/><br/>";

//The numerical representation for day of week (Ex. 01 for Monday .... 07 for Sunday
$today_numerical = date("N",$today);

//leadtime_days holds the numeric value for the number of business days 
$leadtime_days = $_POST["leadtime"];

//leadtime is the adjusted date for shipdate
$shipdate = time();

while ($leadtime_days > 0) 
{
 if ($today_numerical != 5 && $today_numerical != 6)
 {
  $shipdate = $shipdate + (60*60*24);
  $today_numerical = date("N",$shipdate);
  $leadtime_days --;
 }
 else
  $shipdate = $shipdate + (60*60*24);
  $today_numerical = date("N",$shipdate);
}

echo '<strong>Estimated Ship date: ' . '<font color="green">' . date('l, F j, Y', $shipdate) . "</font></strong>";
?>

What does "collect2: error: ld returned 1 exit status" mean?

Include: #include<stdlib.h>

and use System("cls") instead of clrscr()

Node.js ES6 classes with require

Yes, your example would work fine.

As for exposing your classes, you can export a class just like anything else:

class Animal {...}
module.exports = Animal;

Or the shorter:

module.exports = class Animal {

};

Once imported into another module, then you can treat it as if it were defined in that file:

var Animal = require('./Animal');

class Cat extends Animal {
    ...
}

How to move files from one git repo to another (not a clone), preserving history

This answer provide interesting commands based on git am and presented using examples, step by step.

Objective

  • You want to move some or all files from one repository to another.
  • You want to keep their history.
  • But you do not care about keeping tags and branches.
  • You accept limited history for renamed files (and files in renamed directories).

Procedure

  1. Extract history in email format using
    git log --pretty=email -p --reverse --full-index --binary
  2. Reorganize file tree and update filename change in history [optional]
  3. Apply new history using git am

1. Extract history in email format

Example: Extract history of file3, file4 and file5

my_repo
+-- dirA
¦   +-- file1
¦   +-- file2
+-- dirB            ^
¦   +-- subdir      | To be moved
¦   ¦   +-- file3   | with history
¦   ¦   +-- file4   | 
¦   +-- file5       v
+-- dirC
    +-- file6
    +-- file7

Clean the temporary directory destination

export historydir=/tmp/mail/dir  # Absolute path
rm -rf "$historydir"             # Caution when cleaning

Clean your the repo source

git commit ...           # Commit your working files
rm .gitignore            # Disable gitignore
git clean -n             # Simulate removal
git clean -f             # Remove untracked file
git checkout .gitignore  # Restore gitignore

Extract history of each file in email format

cd my_repo/dirB
find -name .git -prune -o -type d -o -exec bash -c 'mkdir -p "$historydir/${0%/*}" && git log --pretty=email -p --stat --reverse --full-index --binary -- "$0" > "$historydir/$0"' {} ';'

Unfortunately option --follow or --find-copies-harder cannot be combined with --reverse. This is why history is cut when file is renamed (or when a parent directory is renamed).

After: Temporary history in email format

/tmp/mail/dir
    +-- subdir
    ¦   +-- file3
    ¦   +-- file4
    +-- file5

2. Reorganize file tree and update filename change in history [optional]

Suppose you want to move these three files in this other repo (can be the same repo).

my_other_repo
+-- dirF
¦   +-- file55
¦   +-- file56
+-- dirB              # New tree
¦   +-- dirB1         # was subdir
¦   ¦   +-- file33    # was file3
¦   ¦   +-- file44    # was file4
¦   +-- dirB2         # new dir
¦        +-- file5    # = file5
+-- dirH
    +-- file77

Therefore reorganize your files:

cd /tmp/mail/dir
mkdir     dirB
mv subdir dirB/dirB1
mv dirB/dirB1/file3 dirB/dirB1/file33
mv dirB/dirB1/file4 dirB/dirB1/file44
mkdir    dirB/dirB2
mv file5 dirB/dirB2

Your temporary history is now:

/tmp/mail/dir
    +-- dirB
        +-- dirB1
        ¦   +-- file33
        ¦   +-- file44
        +-- dirB2
             +-- file5

Change also filenames within the history:

cd "$historydir"
find * -type f -exec bash -c 'sed "/^diff --git a\|^--- a\|^+++ b/s:\( [ab]\)/[^ ]*:\1/$0:g" -i "$0"' {} ';'

Note: This rewrites the history to reflect the change of path and filename.
      (i.e. the change of the new location/name within the new repo)


3. Apply new history

Your other repo is:

my_other_repo
+-- dirF
¦   +-- file55
¦   +-- file56
+-- dirH
    +-- file77

Apply commits from temporary history files:

cd my_other_repo
find "$historydir" -type f -exec cat {} + | git am 

Your other repo is now:

my_other_repo
+-- dirF
¦   +-- file55
¦   +-- file56
+-- dirB            ^
¦   +-- dirB1       | New files
¦   ¦   +-- file33  | with
¦   ¦   +-- file44  | history
¦   +-- dirB2       | kept
¦        +-- file5  v
+-- dirH
    +-- file77

Use git status to see amount of commits ready to be pushed :-)

Note: As the history has been rewritten to reflect the path and filename change:
      (i.e. compared to the location/name within the previous repo)

  • No need to git mv to change the location/filename.
  • No need to git log --follow to access full history.

Extra trick: Detect renamed/moved files within your repo

To list the files having been renamed:

find -name .git -prune -o -exec git log --pretty=tformat:'' --numstat --follow {} ';' | grep '=>'

More customizations: You can complete the command git log using options --find-copies-harder or --reverse. You can also remove the first two columns using cut -f3- and grepping complete pattern '{.* => .*}'.

find -name .git -prune -o -exec git log --pretty=tformat:'' --numstat --follow --find-copies-harder --reverse {} ';' | cut -f3- | grep '{.* => .*}'

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

You can use vim programmatically with the option -c {command} :

Dos to Unix:

vim file.txt -c "set ff=unix" -c ":wq"

Unix to dos:

vim file.txt -c "set ff=dos" -c ":wq"

"set ff=unix/dos" means change fileformat (ff) of the file to Unix/DOS end of line format

":wq" means write file to disk and quit the editor (allowing to use the command in a loop)

How to Merge Two Eloquent Collections?

The merge() method on the Collection does not modify the collection on which it was called. It returns a new collection with the new data merged in. You would need:

$related = $related->merge($tag->questions);

However, I think you're tackling the problem from the wrong angle.

Since you're looking for questions that meet a certain criteria, it would probably be easier to query in that manner. The has() and whereHas() methods are used to generate a query based on the existence of a related record.

If you were just looking for questions that have any tag, you would use the has() method. Since you're looking for questions with a specific tag, you would use the whereHas() to add the condition.

So, if you want all the questions that have at least one tag with either 'Travel', 'Trains', or 'Culture', your query would look like:

$questions = Question::whereHas('tags', function($q) {
    $q->whereIn('name', ['Travel', 'Trains', 'Culture']);
})->get();

If you wanted all questions that had all three of those tags, your query would look like:

$questions = Question::whereHas('tags', function($q) {
    $q->where('name', 'Travel');
})->whereHas('tags', function($q) {
    $q->where('name', 'Trains');
})->whereHas('tags', function($q) {
    $q->where('name', 'Culture');
})->get();

How to configure WAMP (localhost) to send email using Gmail?

use stunnel on your server, to send with gmail. google it.

Do not want scientific notation on plot axis

Normally setting axis limit @ max of your variable is enough

a <- c(0:1000000)
b <- c(0:1000000)

plot(a, b, ylim = c(0, max(b)))

Converting JSONarray to ArrayList

I have fast solution. Just create a file ArrayUtil.java

import java.util.ArrayList;
import java.util.Collection;
import org.json.JSONArray;
import org.json.JSONException;

public class ArrayUtil
{
    public static ArrayList<Object> convert(JSONArray jArr)
    {
        ArrayList<Object> list = new ArrayList<Object>();
        try {
            for (int i=0, l=jArr.length(); i<l; i++){
                 list.add(jArr.get(i));
            }
        } catch (JSONException e) {}

        return list;
    }

    public static JSONArray convert(Collection<Object> list)
    {
        return new JSONArray(list);
    }

}

Usage:

ArrayList<Object> list = ArrayUtil.convert(jArray);

or

JSONArray jArr = ArrayUtil.convert(list);

document.body.appendChild(i)

You can appendChild to document.body but not if the document hasn't been loaded. So you should put everything in:

window.onload=function(){
    //your code
}

This works or you can make appendChild to be dependent on something else like another event for eg.

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append

As a matter of fact you can try changing the innerHTML of the document.body it works...!

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

PHP 7.0 $_SERVER varibales have changed. var_dump it and see how it fits your reqs.

some of them giving remote details are, REMOTE_ADDR HTTP_X_FORWARDED_FOR HTTP_CF_CONNECTING_IP HTTP_CF_IPCOUNTRY

Creating a list/array in excel using VBA to get a list of unique names in a column

You can try my suggestion for a work around in Doug's approach.
But if you want to stick with your logic though, you can try this:

Option Explicit

Sub GetUnique()

Dim rng As Range
Dim myarray, myunique
Dim i As Integer

ReDim myunique(1)

With ThisWorkbook.Sheets("Sheet1")
    Set rng = .Range(.Range("A1"), .Range("A" & .Rows.Count).End(xlUp))
    myarray = Application.Transpose(rng)
    For i = LBound(myarray) To UBound(myarray)
        If IsError(Application.Match(myarray(i), myunique, 0)) Then
            myunique(UBound(myunique)) = myarray(i)
            ReDim Preserve myunique(UBound(myunique) + 1)
        End If
    Next
End With

For i = LBound(myunique) To UBound(myunique)
    Debug.Print myunique(i)
Next

End Sub

This uses array instead of range.
It also uses Match function instead of a nested For Loop.
I didn't have the time to check the time difference though.
So I leave the testing to you.

Resizing image in Java

We're doing this to create thumbnails of images:

  BufferedImage tThumbImage = new BufferedImage( tThumbWidth, tThumbHeight, BufferedImage.TYPE_INT_RGB );
  Graphics2D tGraphics2D = tThumbImage.createGraphics(); //create a graphics object to paint to
  tGraphics2D.setBackground( Color.WHITE );
  tGraphics2D.setPaint( Color.WHITE );
  tGraphics2D.fillRect( 0, 0, tThumbWidth, tThumbHeight );
  tGraphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR );
  tGraphics2D.drawImage( tOriginalImage, 0, 0, tThumbWidth, tThumbHeight, null ); //draw the image scaled

  ImageIO.write( tThumbImage, "JPG", tThumbnailTarget ); //write the image to a file

Best way to create a simple python web service

Raw CGI is kind of a pain, Django is kind of heavyweight. There are a number of simpler, lighter frameworks about, e.g. CherryPy. It's worth looking around a bit.

jquery .live('click') vs .click()

If you need simplify code then live is better in the most cases. If you need to get the best performance then delegate will always better than live. bind (click) vs delegate isn't so simple question (if you have a lot of similar items then delegate will be better).

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

Show or hide element in React

Here is my approach.

import React, { useState } from 'react';

function ToggleBox({ title, children }) {
  const [isOpened, setIsOpened] = useState(false);

  function toggle() {
    setIsOpened(wasOpened => !wasOpened);
  }

  return (
    <div className="box">
      <div className="boxTitle" onClick={toggle}>
        {title}
      </div>
      {isOpened && (
        <div className="boxContent">
          {children}
        </div>
      )}
    </div>
  );
}

In code above, to achieve this, I'm using code like:

{opened && <SomeElement />}

That will render SomeElement only if opened is true. It works because of the way how JavaScript resolve logical conditions:

true && true && 2; // will output 2
true && false && 2; // will output false
true && 'some string'; // will output 'some string'
opened && <SomeElement />; // will output SomeElement if `opened` is true, will output false otherwise (and false will be ignored by react during rendering)
// be careful with 'falsy' values eg
const someValue = 0;
someValue && <SomeElement /> // will output 0, which will be rednered by react
// it'll be better to:
!!someValue && <SomeElement /> // will render nothing as we cast the value to boolean

Reasons for using this approach instead of CSS 'display: none';

  • While it might be 'cheaper' to hide an element with CSS - in such case 'hidden' element is still 'alive' in react world (which might make it actually way more expensive)
    • it means that if props of the parent element (eg. <TabView>) will change - even if you see only one tab, all 5 tabs will get re-rendered
    • the hidden element might still have some lifecycle methods running - eg. it might fetch some data from the server after every update even tho it's not visible
    • the hidden element might crash the app if it'll receive incorrect data. It might happen as you can 'forget' about invisible nodes when updating the state
    • you might by mistake set wrong 'display' style when making element visible - eg. some div is 'display: flex' by default, but you'll set 'display: block' by mistake with display: invisible ? 'block' : 'none' which might break the layout
    • using someBoolean && <SomeNode /> is very simple to understand and reason about, especially if your logic related to displaying something or not gets complex
    • in many cases, you want to 'reset' element state when it re-appears. eg. you might have a slider that you want to set to initial position every time it's shown. (if that's desired behavior to keep previous element state, even if it's hidden, which IMO is rare - I'd indeed consider using CSS if remembering this state in a different way would be complicated)

How do I list the symbols in a .so file

For C++ .so files, the ultimate nm command is nm --demangle --dynamic --defined-only --extern-only <my.so>

# nm --demangle --dynamic --defined-only --extern-only /usr/lib64/libqpid-proton-cpp.so | grep work | grep add
0000000000049500 T proton::work_queue::add(proton::internal::v03::work)
0000000000049580 T proton::work_queue::add(proton::void_function0&)
000000000002e7b0 W proton::work_queue::impl::add_void(proton::internal::v03::work)
000000000002b1f0 T proton::container::impl::add_work_queue()
000000000002dc50 T proton::container::impl::container_work_queue::add(proton::internal::v03::work)
000000000002db60 T proton::container::impl::connection_work_queue::add(proton::internal::v03::work)

source: https://stackoverflow.com/a/43257338

How to iterate a loop with index and element in Swift

For those who want to use forEach.

Swift 4

extension Array {
  func forEachWithIndex(_ body: (Int, Element) throws -> Void) rethrows {
    try zip((startIndex ..< endIndex), self).forEach(body)
  }
}

Or

array.enumerated().forEach { ... }

Hide div if screen is smaller than a certain width

I have the almost the same situation as yours; that if the screen width is less than the my specified width it should hide the div. This is the jquery code I used that worked for me.

$(window).resize(function() {

  if ($(this).width() < 1024) {

    $('.divIWantedToHide').hide();

  } else {

    $('.divIWantedToHide').show();

    }

});

Are there any naming convention guidelines for REST APIs?

No. REST has nothing to do with URI naming conventions. If you include these conventions as part of your API, out-of-band, instead of only via hypertext, then your API is not RESTful.

For more information, see http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

Django - Reverse for '' not found. '' is not a valid view function or pattern name

When you use the url tag you should use quotes for string literals, for example:

{% url 'products' %}

At the moment product is treated like a variable and evaluates to '' in the error message.

How to trigger click on page load?

You can do the following :-

$(document).ready(function(){
    $("#id").trigger("click");
});

How to access the local Django webserver from outside world

If you are using Docker you need to make sure ports are exposed as well

Is it necessary to assign a string to a variable before comparing it to another?

You can also use the NSString class methods which will also create an autoreleased instance and have more options like string formatting:

NSString *myString = [NSString stringWithString:@"abc"];
NSString *myString = [NSString stringWithFormat:@"abc %d efg", 42];

Java collections maintaining insertion order

some Collection are not maintain the order because of, they calculate the hashCode of content and store it accordingly in the appropriate bucket.

How to sort two lists (which reference each other) in the exact same way

One classic approach to this problem is to use the "decorate, sort, undecorate" idiom, which is especially simple using python's built-in zip function:

>>> list1 = [3,2,4,1, 1]
>>> list2 = ['three', 'two', 'four', 'one', 'one2']
>>> list1, list2 = zip(*sorted(zip(list1, list2)))
>>> list1
(1, 1, 2, 3, 4)
>>> list2 
('one', 'one2', 'two', 'three', 'four')

These of course are no longer lists, but that's easily remedied, if it matters:

>>> list1, list2 = (list(t) for t in zip(*sorted(zip(list1, list2))))
>>> list1
[1, 1, 2, 3, 4]
>>> list2
['one', 'one2', 'two', 'three', 'four']

It's worth noting that the above may sacrifice speed for terseness; the in-place version, which takes up 3 lines, is a tad faster on my machine for small lists:

>>> %timeit zip(*sorted(zip(list1, list2)))
100000 loops, best of 3: 3.3 us per loop
>>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100000 loops, best of 3: 2.84 us per loop

On the other hand, for larger lists, the one-line version could be faster:

>>> %timeit zip(*sorted(zip(list1, list2)))
100 loops, best of 3: 8.09 ms per loop
>>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100 loops, best of 3: 8.51 ms per loop

As Quantum7 points out, JSF's suggestion is a bit faster still, but it will probably only ever be a little bit faster, because Python uses the very same DSU idiom internally for all key-based sorts. It's just happening a little closer to the bare metal. (This shows just how well optimized the zip routines are!)

I think the zip-based approach is more flexible and is a little more readable, so I prefer it.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

No you can't use bind variables that way. In your second example :into_bind in v_query_str is just a placeholder for value of variable v_num_of_employees. Your select into statement will turn into something like:

SELECT COUNT(*) INTO  FROM emp_...

because the value of v_num_of_employees is null at EXECUTE IMMEDIATE.

Your first example presents the correct way to bind the return value to a variable.

Edit

The original poster has edited the second code block that I'm referring in my answer to use OUT parameter mode for v_num_of_employees instead of the default IN mode. This modification makes the both examples functionally equivalent.

What's the difference between ViewData and ViewBag?

Can I recommend to you to not use either?

If you want to "send" data to your screen, send a strongly typed object (A.K.A. ViewModel) because it's easier to test.

If you bind to some sort of "Model" and have random "viewbag" or "viewdata" items then it makes automated testing very difficult.

If you are using these consider how you might be able to restructure and just use ViewModels.

PNG transparency issue in IE8

I know this thread has been dead some time, but here is another answer to the old ie8 png background issue.

You can do it in CSS by using IE's proprietary filtering system like this as well:

filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='scale',src='pathToYourPNG');

DEMO

you will need to use a blank.gif for the 'first' image in your background declaration. This is simply to confuse ie8 and prevent it from using both the filter and the background you have set, and only use the filter. Other browsers support multiple background images and will understand the background declaration and not understand the filter, hence using the background only.

You may also need to play with the sizingMethod in the filter to get it to work the way you want.

How to return multiple values in one column (T-SQL)?

group_concat() sounds like what you're looking for.

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

since you're on mssql, i just googled "group_concat mssql" and found a bunch of hits to recreate group_concat functionality. here's one of the hits i found:

http://www.stevenmapes.com/index.php?/archives/23-Recreating-MySQL-GROUP_CONCAT-In-MSSQL-Cross-Tab-Query.html

Authentication issues with WWW-Authenticate: Negotiate

The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.

This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):

  • either NTLM
  • or Kerberos.

See:

How to set a radio button in Android

Just to clarify this: if we have a RadioGroup with several RadioButtons and need to activate one by index, implies that:

radioGroup.check(R.id.radioButtonId)

and

radioGroup.getChildAt(index)`

We can to do:

radioGroup.check(radioGroup.getChildAt(index).getId());

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

It needs the system.web.http.webhost which is part of this package. I fixed this by installing the following package:

PM> Install-Package Microsoft.AspNet.WebApi.WebHost 

or search for it in nuget https://www.nuget.org/packages/Microsoft.AspNet.WebApi.WebHost/5.1.0

Why does Java have transient fields?

To allow you to define variables that you don't want to serialize.

In an object you may have information that you don't want to serialize/persist (perhaps a reference to a parent factory object), or perhaps it doesn't make sense to serialize. Marking these as 'transient' means the serialization mechanism will ignore these fields.

Python "extend" for a dictionary

As others have mentioned, a.update(b) for some dicts a and b will achieve the result you've asked for in your question. However, I want to point out that many times I have seen the extend method of mapping/set objects desire that in the syntax a.extend(b), a's values should NOT be overwritten by b's values. a.update(b) overwrites a's values, and so isn't a good choice for extend.

Note that some languages call this method defaults or inject, as it can be thought of as a way of injecting b's values (which might be a set of default values) in to a dictionary without overwriting values that might already exist.

Of course, you could simple note that a.extend(b) is nearly the same as b.update(a); a=b. To remove the assignment, you could do it thus:

def extend(a,b):
    """Create a new dictionary with a's properties extended by b,
    without overwriting.

    >>> extend({'a':1,'b':2},{'b':3,'c':4})
    {'a': 1, 'c': 4, 'b': 2}
    """
    return dict(b,**a)

Thanks to Tom Leys for that smart idea using a side-effect-less dict constructor for extend.

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I have worked alot with msaccess vba. I think you are looking for MID function

example

    dim myReturn as string
    myreturn = mid("bonjour tout le monde",9,4)

will give you back the value "tout"

Erase whole array Python

Note that list and array are different classes. You can do:

del mylist[:]

This will actually modify your existing list. David's answer creates a new list and assigns it to the same variable. Which you want depends on the situation (e.g. does any other variable have a reference to the same list?).

Try:

a = [1,2]
b = a
a = []

and

a = [1,2]
b = a
del a[:]

Print a and b each time to see the difference.

Difference between Method and Function?

From Object-Oriented Programming Concept:

If you have a function that is accessing/muttating the fields of your class, it becomes method. Otherwise, it is a function.

It will not be a crime if you keep calling all the functions in Java/C++ classes as methods. The reason is that you are directly/indirectly accessing/mutating class properties. So why not all the functions in Java/C++ classes are methods?

"CAUTION: provisional headers are shown" in Chrome debugger

HTTP/2 Pushed resources will produce Provisional headers are shown in the inspector for the same theory as @wvega posted in his answer above.

e.g: Since the server pushed the resource(s) to the client (before the client requested them), the browser has the resources cached and therefore the client never makes/needs a requests; So because...

...the real headers are updated when the server responds, but there is no response if the request was blocked.

How can I discard remote changes and mark a file as "resolved"?

git checkout has the --ours option to check out the version of the file that you had locally (as opposed to --theirs, which is the version that you pulled in). You can pass . to git checkout to tell it to check out everything in the tree. Then you need to mark the conflicts as resolved, which you can do with git add, and commit your work once done:

git checkout --ours .  # checkout our local version of all files
git add -u             # mark all conflicted files as merged
git commit             # commit the merge

Note the . in the git checkout command. That's very important, and easy to miss. git checkout has two modes; one in which it switches branches, and one in which it checks files out of the index into the working copy (sometimes pulling them into the index from another revision first). The way it distinguishes is by whether you've passed a filename in; if you haven't passed in a filename, it tries switching branches (though if you don't pass in a branch either, it will just try checking out the current branch again), but it refuses to do so if there are modified files that that would effect. So, if you want a behavior that will overwrite existing files, you need to pass in . or a filename in order to get the second behavior from git checkout.

It's also a good habit to have, when passing in a filename, to offset it with --, such as git checkout --ours -- <filename>. If you don't do this, and the filename happens to match the name of a branch or tag, Git will think that you want to check that revision out, instead of checking that filename out, and so use the first form of the checkout command.

I'll expand a bit on how conflicts and merging work in Git. When you merge in someone else's code (which also happens during a pull; a pull is essentially a fetch followed by a merge), there are few possible situations.

The simplest is that you're on the same revision. In this case, you're "already up to date", and nothing happens.

Another possibility is that their revision is simply a descendent of yours, in which case you will by default have a "fast-forward merge", in which your HEAD is just updated to their commit, with no merging happening (this can be disabled if you really want to record a merge, using --no-ff).

Then you get into the situations in which you actually need to merge two revisions. In this case, there are two possible outcomes. One is that the merge happens cleanly; all of the changes are in different files, or are in the same files but far enough apart that both sets of changes can be applied without problems. By default, when a clean merge happens, it is automatically committed, though you can disable this with --no-commit if you need to edit it beforehand (for instance, if you rename function foo to bar, and someone else adds new code that calls foo, it will merge cleanly, but produce a broken tree, so you may want to clean that up as part of the merge commit in order to avoid having any broken commits).

The final possibility is that there's a real merge, and there are conflicts. In this case, Git will do as much of the merge as it can, and produce files with conflict markers (<<<<<<<, =======, and >>>>>>>) in your working copy. In the index (also known as the "staging area"; the place where files are stored by git add before committing them), you will have 3 versions of each file with conflicts; there is the original version of the file from the ancestor of the two branches you are merging, the version from HEAD (your side of the merge), and the version from the remote branch.

In order to resolve the conflict, you can either edit the file that is in your working copy, removing the conflict markers and fixing the code up so that it works. Or, you can check out the version from one or the other sides of the merge, using git checkout --ours or git checkout --theirs. Once you have put the file into the state you want it, you indicate that you are done merging the file and it is ready to commit using git add, and then you can commit the merge with git commit.

Specifying and saving a figure with exact size in pixels

Comparison of different approaches

Here is a quick comparison of some of the approaches I've tried with images showing what the give.

Baseline example without trying to set the image dimensions

Just to have a comparison point:

base.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

fig, ax = plt.subplots()
print('fig.dpi = {}'.format(fig.dpi))
print('fig.get_size_inches() = ' + str(fig.get_size_inches())
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig('base.png', format='png')

run:

./base.py
identify base.png

outputs:

fig.dpi = 100.0
fig.get_size_inches() = [6.4 4.8]
base.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000

enter image description here

My best approach so far: plt.savefig(dpi=h/fig.get_size_inches()[1] height-only control

I think this is what I'll go with most of the time, as it is simple and scales:

get_size.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'get_size.png',
    format='png',
    dpi=height/fig.get_size_inches()[1]
)

run:

./get_size.py 431

outputs:

get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000

enter image description here

and

./get_size.py 1293

outputs:

main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000

enter image description here

I tend to set just the height because I'm usually most concerned about how much vertical space the image is going to take up in the middle of my text.

plt.savefig(bbox_inches='tight' changes image size

I always feel that there is too much white space around images, and tended to add bbox_inches='tight' from: Removing white space around a saved image in matplotlib

However, that works by cropping the image, and you won't get the desired sizes with it.

Instead, this other approach proposed in the same question seems to work well:

plt.tight_layout(pad=1)
plt.savefig(...

which gives the exact desired height for height equals 431:

enter image description here

Fixed height, set_aspect, automatically sized width and small margins

Ermmm, set_aspect messes things up again and prevents plt.tight_layout from actually removing the margins...

Asked at: How to obtain a fixed height in pixels, fixed data x/y aspect ratio and automatically remove remove horizontal whitespace margin in Matplotlib?

plt.savefig(dpi=h/fig.get_size_inches()[1] + width control

If you really need a specific width in addition to height, this seems to work OK:

width.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

h = int(sys.argv[1])
w = int(sys.argv[2])
fig, ax = plt.subplots()
wi, hi = fig.get_size_inches()
fig.set_size_inches(hi*(w/h), hi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'width.png',
    format='png',
    dpi=h/hi
)

run:

./width.py 431 869

output:

width.png PNG 869x431 869x431+0+0 8-bit sRGB 10965B 0.000u 0:00.000

enter image description here

and for a small width:

./width.py 431 869

output:

width.png PNG 211x431 211x431+0+0 8-bit sRGB 6949B 0.000u 0:00.000

enter image description here

So it does seem that fonts are scaling correctly, we just get some trouble for very small widths with labels getting cut off, e.g. the 100 on the top left.

I managed to work around those with Removing white space around a saved image in matplotlib

plt.tight_layout(pad=1)

which gives:

width.png PNG 211x431 211x431+0+0 8-bit sRGB 7134B 0.000u 0:00.000

enter image description here

From this, we also see that tight_layout removes a lot of the empty space at the top of the image, so I just generally always use it.

Fixed magic base height, dpi on fig.set_size_inches and plt.savefig(dpi= scaling

I believe that this is equivalent to the approach mentioned at: https://stackoverflow.com/a/13714720/895245

magic.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

magic_height = 300
w = int(sys.argv[1])
h = int(sys.argv[2])
dpi = 80
fig, ax = plt.subplots(dpi=dpi)
fig.set_size_inches(magic_height*w/(h*dpi), magic_height/dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'magic.png',
    format='png',
    dpi=h/magic_height*dpi,
)

run:

./magic.py 431 231

outputs:

magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000

enter image description here

And to see if it scales nicely:

./magic.py 1291 693

outputs:

magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000

enter image description here

So we see that this approach also does work well. The only problem I have with it is that you have to set that magic_height parameter or equivalent.

Fixed DPI + set_size_inches

This approach gave a slightly wrong pixel size, and it makes it is hard to scale everything seamlessly.

set_size_inches.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

w = int(sys.argv[1])
h = int(sys.argv[2])
fig, ax = plt.subplots()
fig.set_size_inches(w/fig.dpi, h/fig.dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(
    0,
    60.,
    'Hello',
    # Keep font size fixed independently of DPI.
    # https://stackoverflow.com/questions/39395616/matplotlib-change-figsize-but-keep-fontsize-constant
    fontdict=dict(size=10*h/fig.dpi),
)
plt.savefig(
    'set_size_inches.png',
    format='png',
)

run:

./set_size_inches.py 431 231

outputs:

set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000

so the height is slightly off, and the image:

enter image description here

The pixel sizes are also correct if I make it 3 times larger:

./set_size_inches.py 1291 693

outputs:

set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000

enter image description here

We understand from this however that for this approach to scale nicely, you need to make every DPI-dependant setting proportional to the size in inches.

In the previous example, we only made the "Hello" text proportional, and it did retain its height between 60 and 80 as we'd expect. But everything for which we didn't do that, looks tiny, including:

  • line width of axes
  • tick labels
  • point markers

SVG

I could not find how to set it for SVG images, my approaches only worked for PNG e.g.:

get_size_svg.py

#!/usr/bin/env python3

import sys

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
    'get_size_svg.svg',
    format='svg',
    dpi=height/fig.get_size_inches()[1]
)

run:

./get_size_svg.py 431

and the generated output contains:

<svg height="345.6pt" version="1.1" viewBox="0 0 460.8 345.6" width="460.8pt"

and identify says:

get_size_svg.svg SVG 614x461 614x461+0+0 8-bit sRGB 17094B 0.000u 0:00.000

and if I open it in Chromium 86 the browser debug tools mouse image hover confirm that height as 460.79.

But of course, since SVG is a vector format, everything should in theory scale, so you can just convert to any fixed sized format without loss of resolution, e.g.:

inkscape -h 431 get_size_svg.svg -b FFF -e get_size_svg.png

gives the exact height:

TODO regenerate image, messed up the upload somehow.

I use Inkscape instead of Imagemagick's convert here because you need to mess with -density as well to get sharp SVG resizes with ImageMagick:

And setting <img height="" on the HTML should also just work for the browser.

Tested on matplotlib==3.2.2.

Replace a value if null or undefined in JavaScript

Here’s the JavaScript equivalent:

var i = null;
var j = i || 10; //j is now 10

Note that the logical operator || does not return a boolean value but the first value that can be converted to true.

Additionally use an array of objects instead of one single object:

var options = {
    filters: [
        {
            name: 'firstName',
            value: 'abc'
        }
    ]
};
var filter  = options.filters[0] || '';  // is {name:'firstName', value:'abc'}
var filter2 = options.filters[1] || '';  // is ''

That can be accessed by index.

Twitter bootstrap float div right

bootstrap 3 has a class to align the text within a div

<div class="text-right">

will align the text on the right

<div class="pull-right">

will pull to the right all the content not only the text

how to use jQuery ajax calls with node.js

Thanks to yojimbo for his answer. To add to his sample, I wanted to use the jquery method $.getJSON which puts a random callback in the query string so I also wanted to parse that out in the Node.js. I also wanted to pass an object back and use the stringify function.

This is my Client Side code.

$.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?",
function(data){
  alert(data);
},
function(jqXHR, textStatus, errorThrown) {
    alert('error ' + textStatus + " " + errorThrown);
});

This is my Server side Node.js

var http = require('http');
var querystring = require('querystring');
var url = require('url');

http.createServer(function (req, res) {
    //grab the callback from the query string   
    var pquery = querystring.parse(url.parse(req.url).query);   
    var callback = (pquery.callback ? pquery.callback : '');

    //we probably want to send an object back in response to the request
    var returnObject = {message: "Hello World!"};
    var returnObjectString = JSON.stringify(returnObject);

    //push back the response including the callback shenanigans
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(callback + '(\'' + returnObjectString + '\')');
}).listen(8124);

How to install Python package from GitHub?

To install Python package from github, you need to clone that repository.

git clone https://github.com/jkbr/httpie.git

Then just run the setup.py file from that directory,

sudo python setup.py install

Difference between partition key, composite key and clustering key in Cassandra?

In cassandra , the difference between primary key,partition key,composite key, clustering key always makes some confusion.. So I am going to explain below and co relate to each others. We use CQL (Cassandra Query Language) for Cassandra database access. Note:- Answer is as per updated version of Cassandra. Primary Key :-

In cassandra there are 2 different way to use primary Key .

CREATE TABLE Cass (
    id int PRIMARY KEY,
    name text 
);

Create Table Cass (
   id int,
   name text,
   PRIMARY KEY(id) 
);

In CQL, the order in which columns are defined for the PRIMARY KEY matters. The first column of the key is called the partition key having property that all the rows sharing the same partition key (even across table in fact) are stored on the same physical node. Also, insertion/update/deletion on rows sharing the same partition key for a given table are performed atomically and in isolation. Note that it is possible to have a composite partition key, i.e. a partition key formed of multiple columns, using an extra set of parentheses to define which columns forms the partition key.

Partitioning and Clustering The PRIMARY KEY definition is made up of two parts: the Partition Key and the Clustering Columns. The first part maps to the storage engine row key, while the second is used to group columns in a row.

CREATE TABLE device_check (
  device_id   int,
  checked_at  timestamp,
  is_power    boolean,
  is_locked   boolean,
  PRIMARY KEY (device_id, checked_at)
);

Here device_id is partition key and checked_at is cluster_key.

We can have multiple cluster key as well as partition key too which depends on declaration.

Javascript onload not working

You can try use in javascript:

window.onload = function() {
 alert("let's go!");
}

Its a good practice separate javascript of html

React Error: Target Container is not a DOM Element

I had encountered the same error with React version 16. This error comes when the Javascript that tries to render the React component is included before the static parent dom element in the html. Fix is same as the accepted answer, i.e. the JavaScript should get included only after the static parent dom element has been defined in the html.

Child inside parent with min-height: 100% not inheriting height

Add height: 1px to parent container. Works in Chrome, FF, Safari.

Linux command (like cat) to read a specified quantity of characters

head -Line_number file_name | tail -1 |cut -c Num_of_chars

this script gives the exact number of characters from the specific line and location, e.g.:

head -5 tst.txt | tail -1 |cut -c 5-8

gives the chars in line 5 and chars 5 to 8 of line 5,

Note: tail -1 is used to select the last line displayed by the head.

How do you get the currently selected <option> in a <select> via JavaScript?

This will do it for you:

var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )

What is the function __construct used for?

Its another way to declare the constructor. You can also use the class name, for ex:

class Cat
{
    function Cat()
    {
        echo 'meow';
    }
}

and

class Cat
{
    function __construct()
    {
        echo 'meow';
    }
}

Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:

$cat = new Cat();

Why is String immutable in Java?

Java Developers decide Strings are immutable due to the following aspect design, efficiency, and security.

Design Strings are created in a special memory area in java heap known as "String Intern pool". While you creating new String (Not in the case of using String() constructor or any other String functions which internally use the String() constructor for creating a new String object; String() constructor always create new string constant in the pool unless we call the method intern()) variable it searches the pool to check whether is it already exist. If it is exist, then return reference of the existing String object. If the String is not immutable, changing the String with one reference will lead to the wrong value for the other references.

According to this article on DZone:

Security String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. Mutable strings could cause security problem in Reflection too, as the parameters are strings.

Efficiency The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cached without worrying the changes.That means, there is no need to calculate hashcode every time it is used.

Assert an object is a specific type

You can use the assertThat method and the Matchers that comes with JUnit.

Take a look at this link that describes a little bit about the JUnit Matchers.

Example:

public class BaseClass {
}

public class SubClass extends BaseClass {
}

Test:

import org.junit.Test;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;

/**
 * @author maba, 2012-09-13
 */
public class InstanceOfTest {

    @Test
    public void testInstanceOf() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }
}

How to detect a USB drive has been plugged in?

It is easy to check for removable devices. However, there's no guarantee that it is a USB device:

var drives = DriveInfo.GetDrives()
    .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);

This will return a list of all removable devices that are currently accessible. More information:

Set height 100% on absolute div

Complete stretching (horizontal/vertical)

The accepted answer is great. Just want to point out some things for others coming here. Margins are not necessary in these cases. If you want a centered layout with a specific "Margin", you can add them to the right and left, like so:

.stretched {
  position: absolute;
  right: 50px;  top: 0;  bottom: 0; left: 50px;
  margin: auto;
}

This is extremely useful.

Centering div (vertical/horizontally)

As a bonus, absolute centering which can be used to get extremely simple centering:

.centered {
  height: 100px;  width: 100px;  
  right: 0;  top: 0;  bottom: 0; left: 0;
  margin: auto;
  position: absolute;
}

php codeigniter count rows

You may try this one

    $this->db->where('field1',$filed1);
    $this->db->where('filed2',$filed2);
    $result = $this->db->get('table_name')->num_rows();

How to open a web page automatically in full screen mode

For Chrome via Chrome Fullscreen API

Note that for (Chrome) security reasons it cannot be called or executed automatically, there must be an interaction from the user first. (Such as button click, keydown/keypress etc.)

addEventListener("click", function() {
    var
          el = document.documentElement
        , rfs =
               el.requestFullScreen
            || el.webkitRequestFullScreen
            || el.mozRequestFullScreen
    ;
    rfs.call(el);
});

Javascript Fullscreen API as demo'd by David Walsh that seems to be a cross browser solution

// Find the right method, call on correct element
function launchFullScreen(element) {
  if(element.requestFullScreen) {
    element.requestFullScreen();
  } else if(element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if(element.webkitRequestFullScreen) {
    element.webkitRequestFullScreen();
  }
}

// Launch fullscreen for browsers that support it!
launchFullScreen(document.documentElement); // the whole page
launchFullScreen(document.getElementById("videoElement")); // any individual element

How do I get list of all tables in a database using TSQL?

SELECT name 
FROM sysobjects 
WHERE xtype='U' 
ORDER BY name;

(SQL Server 2000 standard; still supported in SQL Server 2005.)

How to save a BufferedImage as a File

Create and save a java.awt.image.bufferedImage to file:

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );

            File f = new File("MyFile.png");
            int r = 5;
            int g = 25;
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

Notes:

  1. Creates a file called MyFile.png.
  2. Image is 500 by 500 pixels.
  3. Overwrites the existing file.
  4. The color of the image is black with a blue stripe across the top.

How does internationalization work in JavaScript?

You can also try another library - https://github.com/wikimedia/jquery.i18n .

In addition to parameter replacement and multiple plural forms, it has support for gender a rather unique feature of custom grammar rules that some languages need.

Node.js - How to send data from html to express

I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser which is doing most of the work. Where he puts req.body.name, I believe he/she is using body-parser to get the contents of the name attribute(s) received when the form is submitted.

If you do not want to use Express, use querystring which is a built-in Node module. See the answers in the link below for an example of how to use querystring.

It might help to look at this answer, which is very similar to your quest.

How to add image to canvas

You need to wait until the image is loaded before you draw it. Try this instead:

var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');

make_base();

function make_base()
{
  base_image = new Image();
  base_image.src = 'img/base.png';
  base_image.onload = function(){
    context.drawImage(base_image, 0, 0);
  }
}

i.e. draw the image in the onload callback of the image.

How to get longitude and latitude of any address?

You need to access a geocoding service (i.e. from Google), there is no simple formula to transfer addresses to geo coordinates.

How to get the IP address of the docker host from inside a docker container

The only way is passing the host information as environment when you create a container

run --env <key>=<value>

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

concat.js is being included in the concat task's source files public/js/*.js. You could have a task that removes concat.js (if the file exists) before concatenating again, pass an array to explicitly define which files you want to concatenate and their order, or change the structure of your project.

If doing the latter, you could put all your sources under ./src and your built files under ./dest

src
+-- css
¦   +-- 1.css
¦   +-- 2.css
¦   +-- 3.css
+-- js
    +-- 1.js
    +-- 2.js
    +-- 3.js

Then set up your concat task

concat: {
  js: {
    src: 'src/js/*.js',
    dest: 'dest/js/concat.js'
  },
  css: {
    src: 'src/css/*.css',
    dest: 'dest/css/concat.css'
  }
},

Your min task

min: {
  js: {
    src: 'dest/js/concat.js',
    dest: 'dest/js/concat.min.js'
  }
},

The build-in min task uses UglifyJS, so you need a replacement. I found grunt-css to be pretty good. After installing it, load it into your grunt file

grunt.loadNpmTasks('grunt-css');

And then set it up

cssmin: {
  css:{
    src: 'dest/css/concat.css',
    dest: 'dest/css/concat.min.css'
  }
}

Notice that the usage is similar to the built-in min.

Change your default task to

grunt.registerTask('default', 'concat min cssmin');

Now, running grunt will produce the results you want.

dest
+-- css
¦   +-- concat.css
¦   +-- concat.min.css
+-- js
    +-- concat.js
    +-- concat.min.js

MySQL Sum() multiple columns

You could change the database structure such that all subject rows become a column variable (like spreadsheet). This makes such analysis much easier

.ps1 cannot be loaded because the execution of scripts is disabled on this system

There are certain scenarios in which you can follow the steps suggested in the other answers, verify that Execution Policy is set correctly, and still have your scripts fail. If this happens to you, you are probably on a 64-bit machine with both 32-bit and 64-bit versions of PowerShell, and the failure is happening on the version that doesn't have Execution Policy set. The setting does not apply to both versions, so you have to explicitly set it twice.

Look in your Windows directory for System32 and SysWOW64.

Repeat these steps for each directory:

  1. Navigate to WindowsPowerShell\v1.0 and launch powershell.exe
  2. Check the current setting for ExecutionPolicy:

    Get-ExecutionPolicy -List

  3. Set the ExecutionPolicy for the level and scope you want, for example:

    Set-ExecutionPolicy -Scope LocalMachine Unrestricted

Note that you may need to run PowerShell as administrator depending on the scope you are trying to set the policy for.

You can read a lot more here: Running Windows PowerShell Scripts

mvn command not found in OSX Mavrerick

I followed brain storm's instructions and still wasn't getting different results - any new terminal windows would not recognize the mvn command. I don't know why, but breaking out the declarations in smaller chunks .bash_profile worked. As far as I can tell, I'm essentially doing the same thing he did. Here's what looks different in my .bash_profile:

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home
export PATH JAVA_HOME
J2=$JAVA_HOME/bin
export PATH J2
M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1
export PATH M2_HOME
M2=$M2_HOME/bin
export PATH M2

Object of custom type as dictionary key

You need to add 2 methods, note __hash__ and __eq__:

class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

    def __eq__(self, other):
        return (self.name, self.location) == (other.name, other.location)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

The Python dict documentation defines these requirements on key objects, i.e. they must be hashable.

Key Listeners in python?

Although I like using the keyboard module to capture keyboard events, I don't like its record() function because it returns an array like [KeyboardEvent("A"), KeyboardEvent("~")], which I find kind of hard to read. So, to record keyboard events, I like to use the keyboard module and the threading module simultaneously, like this:

import keyboard
import string
from threading import *


# I can't find a complete list of keyboard keys, so this will have to do:
keys = list(string.ascii_lowercase)
"""
Optional code(extra keys):

keys.append("space_bar")
keys.append("backspace")
keys.append("shift")
keys.append("esc")
"""
def listen(key):
    while True:
        keyboard.wait(key)
        print("[+] Pressed",key)
threads = [Thread(target=listen, kwargs={"key":key}) for key in keys]
for thread in threads:
    thread.start()

PHP salt and hash SHA256 for login password

You couldn't login because you did't get proper solt text at login time. There are two options, first is define static salt, second is if you want create dynamic salt than you have to store the salt somewhere (means in database) with associate with user. Than you concatenate user solt+password_hash string now with this you fire query with username in your database table.