Programs & Examples On #Web2py

web2py is a open-source full-stack web framework written in Python 2.x.

Changing specific text's color using NSMutableAttributedString in Swift

This extension works well when configuring the text of a label with an already set default color.

public extension String {
    func setColor(_ color: UIColor, ofSubstring substring: String) -> NSMutableAttributedString {
        let range = (self as NSString).range(of: substring)
        let attributedString = NSMutableAttributedString(string: self)
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
        return attributedString
    }
}

For example

let text = "Hello World!"
let attributedText = text.setColor(.blue, ofSubstring: "World")

let myLabel = UILabel()
myLabel.textColor = .white
myLabel.attributedText = attributedText

How to create directory automatically on SD card

I faced the same problem. There are two types of permissions in Android:

  • Dangerous (access to contacts, write to external storage...)
  • Normal (Normal permissions are automatically approved by Android while dangerous permissions need to be approved by Android users.)

Here is the strategy to get dangerous permissions in Android 6.0

  • Check if you have the permission granted
  • If your app is already granted the permission, go ahead and perform normally.
  • If your app doesn't have the permission yet, ask for user to approve
  • Listen to user approval in onRequestPermissionsResult

Here is my case: I need to write to external storage.

First, I check if I have the permission:

...
private static final int REQUEST_WRITE_STORAGE = 112;
...
boolean hasPermission = (ContextCompat.checkSelfPermission(activity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
    ActivityCompat.requestPermissions(parentActivity,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                REQUEST_WRITE_STORAGE);
}

Then check the user's approval:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode)
    {
        case REQUEST_WRITE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                //reload my activity with permission granted or use the features what required the permission
            } else
            {
                Toast.makeText(parentActivity, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
            }
        }
    }    
}

How to include a sub-view in Blade templates?

As of Laravel 5.6, if you have this kind of structure and you want to include another blade file inside a subfolder,

|--- views

|------- parentFolder (Folder)

|---------- name.blade.php (Blade File)

|---------- childFolder (Folder)

|-------------- mypage.blade.php (Blade File)

name.blade.php

  <html>
      @include('parentFolder.childFolder.mypage')
  </html>

How can I make a countdown with NSTimer?

Swift4

    @IBOutlet weak var actionButton: UIButton!
    @IBOutlet weak var timeLabel: UILabel!
    var timer:Timer?
    var timeLeft = 60

override func viewDidLoad() {
    super.viewDidLoad()
    setupTimer()
}

func setupTimer() {
    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
}

@objc func onTimerFires() {
    timeLeft -= 1
    timeLabel.text = "\(timeLeft) seconds left"

    if timeLeft <= 0 {
        actionButton.isEnabled = true
        actionButton.setTitle("enabled", for: .normal)
        timer?.invalidate()
        timer = nil
    }
}

@IBAction func btnClicked(_ sender: UIButton) {
    print("API Fired")
}

How do I convert a list of ascii values to a string in python?

You are probably looking for 'chr()':

>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(chr(i) for i in L)
'hello, world'

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

When you restore backup, Make sure to try with the same username for the old one and the new one.

Creating a simple login form

Using <table> is not a bad choice. Of course it is bit old fashioned. 

But still not obsolete. But if you prefer you can use "Boostrap". There you have options for panels and enhanced forms.

This is the sample code for your requirement. Used minimal styles to simplify.

<!DOCTYPE html>
<html>
   <head>
      <title>Simple Login Form</title>
   </head>
   <style>
      table{
      border-style: solid;
      position: absolute;
      top: 40%;
      left : 40%;
      padding:10px;
      }
   </style>
   <body>
      <form method="post" action="login.php">
         <table>
            <tr bgcolor="black">
               <th colspan="3"><font color="white">Enter login details</th>
            </tr>
            <tr height="20"></tr>
            <tr>
               <td>User Name</td>
               <td>:</td>
               <td>
                  <input type="text" name="username"/>
               </td>
            </tr>
            <tr>
               <td>Password</td>
               <td>:</td>
               <td>
                  <input type="password" name="password"/>
               </td>
            </tr>
            <tr height="10"></tr>
            <tr>
               <td></td>
               <td></td>
               <td align="center"><input type="submit" value="Submit"></td>
            </tr>
         </table>
      </form>
   </body>
</html>

How to set a default value for an existing column

Just Found 3 simple steps to alter already existing column that was null before

update   orders
set BasicHours=0 where BasicHours is null

alter table orders 
add default(0) for BasicHours

alter table orders 
alter  column CleanBasicHours decimal(7,2) not null 

Regex to match only uppercase "words" with some exceptions

For the first case you propose you can use: '[[:blank:]]+[A-Z0-9]+[[:blank:]]+', for example:

echo "The thing P1 must connect to the J236 thing in the Foo position" | grep -oE '[[:blank:]]+[A-Z0-9]+[[:blank:]]+'

In the second case maybe you need to use something else and not a regex, maybe a script with a dictionary of technical words...

Cheers, Fernando

working with negative numbers in python

The abs() in the while condition is needed, since, well, it controls the number of iterations (how would you define a negative number of iterations?). You can correct it by inverting the sign of the result if numb is negative.

So this is the modified version of your code. Note I replaced the while loop with a cleaner for loop.

#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")

#standing variables
total = 0

#output the total
for count in range(abs(numb)):
    total += numa

if numb < 0:
    total = -total

print total

How to create an HTTPS server in Node.js?

Update

Use Let's Encrypt via Greenlock.js

Original Post

I noticed that none of these answers show that adding a Intermediate Root CA to the chain, here are some zero-config examples to play with to see that:

Snippet:

var options = {
  // this is the private key only
  key: fs.readFileSync(path.join('certs', 'my-server.key.pem'))

// this must be the fullchain (cert + intermediates)
, cert: fs.readFileSync(path.join('certs', 'my-server.crt.pem'))

// this stuff is generally only for peer certificates
//, ca: [ fs.readFileSync(path.join('certs', 'my-root-ca.crt.pem'))]
//, requestCert: false
};

var server = https.createServer(options);
var app = require('./my-express-or-connect-app').create(server);
server.on('request', app);
server.listen(443, function () {
  console.log("Listening on " + server.address().address + ":" + server.address().port);
});

var insecureServer = http.createServer();
server.listen(80, function () {
  console.log("Listening on " + server.address().address + ":" + server.address().port);
});

This is one of those things that's often easier if you don't try to do it directly through connect or express, but let the native https module handle it and then use that to serve you connect / express app.

Also, if you use server.on('request', app) instead of passing the app when creating the server, it gives you the opportunity to pass the server instance to some initializer function that creates the connect / express app (if you want to do websockets over ssl on the same server, for example).

Count number of matches of a regex in Javascript

(('a a a').match(/b/g) || []).length; // 0
(('a a a').match(/a/g) || []).length; // 3

Based on https://stackoverflow.com/a/48195124/16777 but fixed to actually work in zero-results case.

Spring Test & Security: How to mock authentication?

It turned out that the SecurityContextPersistenceFilter, which is part of the Spring Security filter chain, always resets my SecurityContext, which I set calling SecurityContextHolder.getContext().setAuthentication(principal) (or by using the .principal(principal) method). This filter sets the SecurityContext in the SecurityContextHolder with a SecurityContext from a SecurityContextRepository OVERWRITING the one I set earlier. The repository is a HttpSessionSecurityContextRepository by default. The HttpSessionSecurityContextRepository inspects the given HttpRequest and tries to access the corresponding HttpSession. If it exists, it will try to read the SecurityContext from the HttpSession. If this fails, the repository generates an empty SecurityContext.

Thus, my solution is to pass a HttpSession along with the request, which holds the SecurityContext:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;

import eu.ubicon.webapp.test.WebappTestEnvironment;

public class Test extends WebappTestEnvironment {

    public static class MockSecurityContext implements SecurityContext {

        private static final long serialVersionUID = -1386535243513362694L;

        private Authentication authentication;

        public MockSecurityContext(Authentication authentication) {
            this.authentication = authentication;
        }

        @Override
        public Authentication getAuthentication() {
            return this.authentication;
        }

        @Override
        public void setAuthentication(Authentication authentication) {
            this.authentication = authentication;
        }
    }

    @Test
    public void signedIn() throws Exception {

        UsernamePasswordAuthenticationToken principal = 
                this.getPrincipal("test1");

        MockHttpSession session = new MockHttpSession();
        session.setAttribute(
                HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, 
                new MockSecurityContext(principal));


        super.mockMvc
            .perform(
                    get("/api/v1/resource/test")
                    .session(session))
            .andExpect(status().isOk());
    }
}

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Why doesn't [01-12] range work as expected?

The []s in a regex denote a character class. If no ranges are specified, it implicitly ors every character within it together. Thus, [abcde] is the same as (a|b|c|d|e), except that it doesn't capture anything; it will match any one of a, b, c, d, or e. All a range indicates is a set of characters; [ac-eg] says "match any one of: a; any character between c and e; or g". Thus, your match says "match any one of: 0; any character between 1 and 1 (i.e., just 1); or 2.

Your goal is evidently to specify a number range: any number between 01 and 12 written with two digits. In this specific case, you can match it with 0[1-9]|1[0-2]: either a 0 followed by any digit between 1 and 9, or a 1 followed by any digit between 0 and 2. In general, you can transform any number range into a valid regex in a similar manner. There may be a better option than regular expressions, however, or an existing function or module which can construct the regex for you. It depends on your language.

Why does git say "Pull is not possible because you have unmerged files"?

There was same issue with me
In my case, steps are as below-

  1. Removed all file which was being start with U (unmerged) symbol. as-

U   project/app/pages/file1/file.ts
U   project/www/assets/file1/file-name.html
  1. Pull code from master

$ git pull origin master
  1. Checked for status

 $ git status

Here is the message which It appeared-
and have 2 and 1 different commit each, respectively.
(use "git pull" to merge the remote branch into yours)
You have unmerged paths.
(fix conflicts and run "git commit")

Unmerged paths:
(use "git add ..." to mark resolution)

both modified:   project/app/pages/file1/file.ts
both modified:   project/www/assets/file1/file-name.html
  1. Added all new changes -

    $ git add project/app/pages/file1/file.ts
project/www/assets/file1/file-name.html
  1. Commit changes on head-

$ git commit -am "resolved conflict of the app."
  1. Pushed the code -

$ git push origin master

Which turn may issue resolved with this image - enter image description here

Skip a submodule during a Maven build

Sure, this can be done using profiles. You can do something like the following in your parent pom.xml.

  ...
   <modules>
      <module>module1</module>
      <module>module2</module>  
      ...
  </modules>
  ...
  <profiles>
     <profile>
       <id>ci</id>
          <modules>
            <module>module1</module>
            <module>module2</module>
            ...
            <module>module-integration-test</module>
          </modules> 
      </profile>
  </profiles>
 ...

In your CI, you would run maven with the ci profile, i.e. mvn -P ci clean install

Pure CSS collapse/expand div

@gbtimmon's answer is great, but way, way too complicated. I've simplified his code as much as I could.

_x000D_
_x000D_
#answer,
#show,
#hide:target {
    display: none; 
}

#hide:target + #show,
#hide:target ~ #answer {
    display: inherit; 
}
_x000D_
<a href="#hide" id="hide">Show</a>
<a href="#/" id="show">Hide</a>
<div id="answer"><p>Answer</p></div>
_x000D_
_x000D_
_x000D_

ps1 cannot be loaded because running scripts is disabled on this system

Another solution is Remove ng.ps1 from the directory C:\Users%username%\AppData\Roaming\npm\ and clearing the npm cache

Unexpected character encountered while parsing value

Possibly you are not passing JSON to DeserializeObject.

It looks like from File.WriteAllText(tmpfile,... that type of tmpfile is string that contain path to a file. JsonConvert.DeserializeObject takes JSON value, not file path - so it fails trying to convert something like @"c:\temp\fooo" - which is clearly not JSON.

How do I search within an array of hashes by hash values in ruby?

if your array looks like

array = [
 {:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
 {:name => "John" , :age => 26 , :place => "xtz"} ,
 {:name => "Anil" , :age => 26 , :place => "xsz"} 
]

And you Want To know if some value is already present in your array. Use Find Method

array.find {|x| x[:name] == "Hitesh"}

This will return object if Hitesh is present in name otherwise return nil

R - test if first occurrence of string1 is followed by string2

> grepl("^[^_]+_1",s)
[1] FALSE
> grepl("^[^_]+_2",s)
[1] TRUE

basically, look for everything at the beginning except _, and then the _2.

+1 to @Ananda_Mahto for suggesting grepl instead of grep.

How do I send a file in Android from a mobile device to server using http?

Wrap it all up in an Async task to avoid threading errors.

public class AsyncHttpPostTask extends AsyncTask<File, Void, String> {

    private static final String TAG = AsyncHttpPostTask.class.getSimpleName();
    private String server;

    public AsyncHttpPostTask(final String server) {
        this.server = server;
    }

    @Override
    protected String doInBackground(File... params) {
        Log.d(TAG, "doInBackground");
        HttpClient http = AndroidHttpClient.newInstance("MyApp");
        HttpPost method = new HttpPost(this.server);
        method.setEntity(new FileEntity(params[0], "text/plain"));
        try {
            HttpResponse response = http.execute(method);
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            final StringBuilder out = new StringBuilder();
            String line;
            try {
                while ((line = rd.readLine()) != null) {
                    out.append(line);
                }
            } catch (Exception e) {}
            // wr.close();
            try {
                rd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // final String serverResponse = slurp(is);
            Log.d(TAG, "serverResponse: " + out.toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

What is the difference between DAO and Repository patterns?

In the spring framework, there is an annotation called the repository, and in the description of this annotation, there is useful information about the repository, which I think it is useful for this discussion.

Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects".

Teams implementing traditional Java EE patterns such as "Data Access Object" may also apply this stereotype to DAO classes, though care should be taken to understand the distinction between Data Access Object and DDD-style repositories before doing so. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.

A class thus annotated is eligible for Spring DataAccessException translation when used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc.

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

Your problem is that you have declare twice the exec-maven-plugin :

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2.1</version>
    <executions>
        <execution>
            <goals>
                <goal>java</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <mainClass>C:\apache-camel-2.11.0\examples\camel-example-smooks-  
      integration\src\main\java\example\Main< /mainClass>
    </configuration>
</plugin>

...

< plugin>
    < groupId>org.codehaus.mojo</groupId>
    < artifactId>exec-maven-plugin</artifactId>
    < version>1.2</version>
< /plugin>

How to recover Git objects damaged by hard disk failure?

Here are two functions that may help if your backup is corrupted, or you have a few partially corrupted backups as well (this may happen if you backup the corrupted objects).

Run both in the repo you're trying to recover.

Standard warning: only use if you're really desperate and you have backed up your (corrupted) repo. This might not resolve anything, but at least should highlight the level of corruption.

fsck_rm_corrupted() {
    corrupted='a'
    while [ "$corrupted" ]; do
        corrupted=$(                                  \
        git fsck --full --no-dangling 2>&1 >/dev/null \
            | grep 'stored in'                          \
            | sed -r 's:.*(\.git/.*)\).*:\1:'           \
        )
        echo "$corrupted"
        rm -f "$corrupted"
    done
}

if [ -z "$1" ]  || [ ! -d "$1" ]; then
    echo "'$1' is not a directory. Please provide the directory of the git repo"
    exit 1
fi

pushd "$1" >/dev/null
fsck_rm_corrupted
popd >/dev/null

and

unpack_rm_corrupted() {
    corrupted='a'
    while [ "$corrupted" ]; do
        corrupted=$(                                  \
        git unpack-objects -r < "$1" 2>&1 >/dev/null \
            | grep 'stored in'                          \
            | sed -r 's:.*(\.git/.*)\).*:\1:'           \
        )
        echo "$corrupted"
        rm -f "$corrupted"
    done
}

if [ -z "$1" ]  || [ ! -d "$1" ]; then
    echo "'$1' is not a directory. Please provide the directory of the git repo"
    exit 1
fi

for p in $1/objects/pack/pack-*.pack; do
    echo "$p"
    unpack_rm_corrupted "$p"
done

What is the correct way to restore a deleted file from SVN?

Use the Tortoise SVN copy functionality to revert commited changes:

  1. Right click the parent folder that contains the deleted files/folder
  2. Select the "show log"
  3. Select and right click on the version before which the changes/deleted was done
  4. Select the "browse repository"
  5. Select the file/folder which needs to be restored and right click
  6. Select "copy to" which will copy the files/folders to the head revision

Hope that helps

Access Control Request Headers, is added to header in AJAX request with jQuery

This code below works for me. I always use only single quotes, and it works fine. I suggest you should use only single quotes or only double quotes, but not mixed up.

$.ajax({
    url: 'YourRestEndPoint',
    headers: {
        'Authorization':'Basic xxxxxxxxxxxxx',
        'X-CSRF-TOKEN':'xxxxxxxxxxxxxxxxxxxx',
        'Content-Type':'application/json'
    },
    method: 'POST',
    dataType: 'json',
    data: YourData,
    success: function(data){
      console.log('succes: '+data);
    }
  });

Override console.log(); for production

Or if you just want to redefine the behavior of the console (in order to add logs for example) You can do something like that:

// define a new console
var console=(function(oldCons){
    return {
        log: function(text){
            oldCons.log(text);
            // Your code
        },
        info: function (text) {
            oldCons.info(text);
            // Your code
        },
        warn: function (text) {
            oldCons.warn(text);
            // Your code
        },
        error: function (text) {
            oldCons.error(text);
            // Your code
        }
    };
}(window.console));

//Then redefine the old console
window.console = console;

Programmatically shut down Spring Boot application

Closing a SpringApplication basically means closing the underlying ApplicationContext. The SpringApplication#run(String...) method gives you that ApplicationContext as a ConfigurableApplicationContext. You can then close() it yourself.

For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to shut down...
        ctx.close();
    }
}

Alternatively, you can use the static SpringApplication.exit(ApplicationContext, ExitCodeGenerator...) helper method to do it for you. For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to stop...
        int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
            @Override
            public int getExitCode() {
                // no errors
                return 0;
            }
        });

        // or shortened to
        // int exitCode = SpringApplication.exit(ctx, () -> 0);

        System.exit(exitCode);
    }
}

How do I redirect to another webpage?

<script type="text/javascript">
var url = "https://yourdomain.com";

// IE8 and lower fix
if (navigator.userAgent.match(/MSIE\s(?!9.0)/))
{
    var referLink = document.createElement("a");
    referLink.href = url;
    document.body.appendChild(referLink);
    referLink.click();
}

// All other browsers
else { window.location.replace(url); }
</script>

Why is there no xrange function in Python3?

comp:~$ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2

>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.656799077987671

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)

5.579368829727173

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

21.54827117919922

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

22.014557123184204

With timeit number=1 param:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.2245171070098877

>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=1)

0.10750913619995117

comp:~$ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.113872020003328

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)

9.07014398300089

With timeit number=1,2,3,4 param works quick and in linear way:

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=1)

0.09329321900440846

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=2)

0.18501482300052885

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=3)

0.2703447980020428

>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=4)

0.36209142999723554

So it seems if we measure 1 running loop cycle like timeit.timeit("[x for x in range(1000000) if x%4]",number=1) (as we actually use in real code) python3 works quick enough, but in repeated loops python 2 xrange() wins in speed against range() from python 3.

How to do a regular expression replace in MySQL?

I think there is an easy way to achieve this and It's working fine for me.

To SELECT rows using REGEX

SELECT * FROM `table_name` WHERE `column_name_to_find` REGEXP 'string-to-find'

To UPDATE rows using REGEX

UPDATE `table_name` SET column_name_to_find=REGEXP_REPLACE(column_name_to_find, 'string-to-find', 'string-to-replace') WHERE column_name_to_find REGEXP 'string-to-find'

REGEXP Reference: https://www.geeksforgeeks.org/mysql-regular-expressions-regexp/

SQL Not Like Statement not working

If WPP.COMMENT contains NULL, the condition will not match.

This query:

SELECT  1
WHERE   NULL NOT LIKE '%test%'

will return nothing.

On a NULL column, both LIKE and NOT LIKE against any search string will return NULL.

Could you please post relevant values of a row which in your opinion should be returned but it isn't?

How to change 1 char in the string?

Strings are immutable. You can use the string builder class to help!:

string str = "valta is the best place in the World";

StringBuilder strB = new StringBuilder(str);

strB[0] = 'M';

Generating PDF files with JavaScript

Even if you could generate the PDF in-memory in JavaScript, you would still have the issue of how to transfer that data to the user. It's hard for JavaScript to just push a file at the user.

To get the file to the user, you would want to do a server submit in order to get the browser to bring up the save dialog.

With that said, it really isn't too hard to generate PDFs. Just read the spec.

C# winforms combobox dynamic autocomplete

I've found Max Lambertini's answer very helpful, but have modified his HandleTextChanged method as such:

    //I like min length set to 3, to not give too many options 
    //after the first character or two the user types
    public Int32 AutoCompleteMinLength {get; set;}

    private void HandleTextChanged() {
        var txt = comboBox.Text;
        if (txt.Length < AutoCompleteMinLength)
            return;

        //The GetMatches method can be whatever you need to filter 
        //table rows or some other data source based on the typed text.
        var matches = GetMatches(comboBox.Text.ToUpper());

        if (matches.Count() > 0) {
            //The inside of this if block has been changed to allow
            //users to continue typing after the auto-complete results
            //are found.
            comboBox.Items.Clear();
            comboBox.Items.AddRange(matches);
            comboBox.DroppedDown = true;
            Cursor.Current = Cursors.Default;
            comboBox.Select(txt.Length, 0);
            return;
        }
        else {
            comboBox.DroppedDown = false;
            comboBox.SelectionStart = txt.Length;
        }
    }

How do I test axios in Jest?

For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:

File actions.test.js:

describe('SignInUser', () => {
  var history = {
    push: function(str) {
        expect(str).toEqual('/feed');
    }
  }

  it('Dispatches authorization', () => {
    let mock = new MockAdapter(axios);
    mock.onPost(`${ROOT_URL}/auth/signin`, {
        email: '[email protected]',
        password: 'test'
    }).reply(200, {token: 'testToken' });

    const expectedActions = [ { type: types.AUTH_USER } ];
    const store = mockStore({ auth: [] });

    return store.dispatch(actions.signInUser({
        email: '[email protected]',
        password: 'test',
      }, history)).then(() => {
        expect(store.getActions()).toEqual(expectedActions);
  });

});

In order to test a successful case for signInUser in file actions/index.js:

export const signInUser = ({ email, password }, history) => async dispatch => {
  const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
    .catch(({ response: { data } }) => {
        ...
  });

  if (res) {
    dispatch({ type: AUTH_USER });                 // Test verified this
    localStorage.setItem('token', res.data.token); // Test mocked this
    history.push('/feed');                         // Test mocked this
  }
}

Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:

const localStorageMock = {
  removeItem: jest.fn(),
  getItem: jest.fn(),
  setItem: jest.fn(),
  clear: jest.fn()
};
global.localStorage = localStorageMock;

How to make JavaScript execute after page load?

I find sometimes on more complex pages that not all the elements have loaded by the time window.onload is fired. If that's the case, add setTimeout before your function to delay is a moment. It's not elegant but it's a simple hack that renders well.

window.onload = function(){ doSomethingCool(); };

becomes...

window.onload = function(){ setTimeout( function(){ doSomethingCool(); }, 1000); };

Authentication issue when debugging in VS2013 - iis express

You could also modify the project properties for your web project, choose "Web" from left tabs, then change the Servers drop down to "Local IIS". Create a new virtual directory and use IIS manager to setup your site/app pool as desired.

I prefer this method, as you would typically have a local IIS v-directory (or site) to test locally. You won't affect any other sites this way either.

Web Project Properties

How can I troubleshoot Python "Could not find platform independent libraries <prefix>"

Try export PYTHONHOME=/usr/local. Python should be installed in /usr/local on OS X.

This answer has received a little more attention than I anticipated, I'll add a little bit more context.

Normally, Python looks for its libraries in the paths prefix/lib and exec_prefix/lib, where prefix and exec_prefix are configuration options. If the PYTHONHOME environment variable is set, then the value of prefix and exec_prefix are inherited from it. If the PYTHONHOME environment variable is not set, then prefix and exec_prefix default to /usr/local (and I believe there are other ways to set prefix/exec_prefix as well, but I'm not totally familiar with them).

Normally, when you receive the error message Could not find platform independent libraries <prefix>, the string <prefix> would be replaced with the actual value of prefix. However, if prefix has an empty value, then you get the rather cryptic messages posted in the question. One way to get an empty prefix would be to set PYTHONHOME to an empty string. More info about PYTHONHOME, prefix, and exec_prefix is available in the official docs.

Android emulator: could not get wglGetExtensionsStringARB error

For me changing the Emulated Performance setting to "Store a snapshot for faster startup" and unchecking "Use Host GPU" fixed the problem.

How to implement LIMIT with SQL Server?

SELECT TOP 10 * FROM table;

Is the same as

SELECT * FROM table LIMIT 0,10;

Here's an article about implementing Limit in MsSQL Its a nice read, specially the comments.

Resetting remote to a certain commit

I solved problem like yours by this commands:

git reset --hard <commit-hash> 
git push -f <remote> <local branch>:<remote branch> 

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

For non-preemptive system,

waitingTime = startTime - arrivalTime

turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime

startTime = Time at which the process started executing

finishTime = Time at which the process finished executing

You can keep track of the current time elapsed in the system(timeElapsed). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime, when finishes, record its finishTime (both same as timeElapsed). That way you can calculate what you need.

PHP, How to get current date in certain format

date("Y-m-d H:i:s"); // This should do it.

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

PROBLEM SOLVED

I had the same problem and fixed just by converting DB_HOST constant in the .env File FROM 127.0.0.1 into localhost *JUST DO THIS AS GIVEN IN THE BELOW LINE* DB_HOST = localhost.

No need to change anything into config/database.php

Don't forget to run

php artisan config:clear

Default optional parameter in Swift function

Optionals and default parameters are two different things.

An Optional is a variable that can be nil, that's it.

Default parameters use a default value when you omit that parameter, this default value is specified like this: func test(param: Int = 0)

If you specify a parameter that is an optional, you have to provide it, even if the value you want to pass is nil. If your function looks like this func test(param: Int?), you can't call it like this test(). Even though the parameter is optional, it doesn't have a default value.

You can also combine the two and have a parameter that takes an optional where nil is the default value, like this: func test(param: Int? = nil).

How to include PHP files that require an absolute path?

This should work

$root = realpath($_SERVER["DOCUMENT_ROOT"]);

include "$root/inc/include1.php";

Edit: added imporvement by aussieviking

Open firewall port on CentOS 7

Firewalld is a bit non-intuitive for the iptables veteran. For those who prefer an iptables-driven firewall with iptables-like syntax in an easy configurable tree, try replacing firewalld with fwtree: https://www.linuxglobal.com/fwtree-flexible-linux-tree-based-firewall/ and then do the following:

 echo '-p tcp --dport 80 -m conntrack --cstate NEW -j ACCEPT' > /etc/fwtree.d/filter/INPUT/80-allow.rule
 systemctl reload fwtree 

Check if character is number?

You can use this:

function isDigit(n) {
    return Boolean([true, true, true, true, true, true, true, true, true, true][n]);
}

Here, I compared it to the accepted method: http://jsperf.com/isdigittest/5 . I didn't expect much, so I was pretty suprised, when I found out that accepted method was much slower.

Interesting thing is, that while accepted method is faster correct input (eg. '5') and slower for incorrect (eg. 'a'), my method is exact opposite (fast for incorrect and slower for correct).

Still, in worst case, my method is 2 times faster than accepted solution for correct input and over 5 times faster for incorrect input.

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.

Convert DateTime to TimeSpan

TimeSpan.FromTicks(DateTime.Now.Ticks)

Decompile an APK, modify it and then recompile it

Thanks to Chris Jester-Young I managed to make it work!

I think the way I managed to do it will work only on really simple projects:

  • With Dex2jar I obtained the Jar.
  • With jd-gui I convert my Jar back to Java files.
  • With apktool i got the android manifest and the resources files.

  • In Eclipse I create a new project with the same settings as the old one (checking all the information in the manifest file)

  • When the project is created I'm replacing all the resources and the manifest with the ones I obtained with apktool
  • I paste the java files I extracted from the Jar in the src folder (respecting the packages)
  • I modify those files with what I need
  • Everything is compiling!

/!\ be sure you removed the old apk from the device an error will be thrown stating that the apk signature is not the same as the old one!

Difference between Git and GitHub

There are a number of obvious differences between Git and GitHub.

Git itself is really focused on the essential tasks of version control. It maintains a commit history, it allows you to reverse changes through reset and revert commands, and it allows you to share code with other developers through push and pull commands. I think those are the essential features every developer wants from a DVCS tool.

Git versus GitHub Comparison Chart

No Scope Creep with Git

But one thing about Git is that it is really just laser focused on source code control and nothing else. That's awesome, but it also means the tool lacks many features organizations want. For example, there is no built-in user management facilities to authenticate who is connecting and committing code. Integration with things like Jira or Jenkins are left up to developers to figure out through things like hooks. Basically, there are a load of places where features could be integrated. That's where organizations like GitHub and GitLab come in.

Additional GitHub Features

GitHub's primary 'value-add' is that it provides a cloud based platform for Git. That in itself is awesome. On top of that, GitHub also offers:

  • simple task tracking
  • a GitHub desktop app
  • online file editing
  • branch protection rules
  • pull request features
  • organizational tools
  • interaction limits for hotheads
  • emoji support!!! :octocat: :+1:

So GitHub really adds polish and refinement to an already popular DVCS tool.

Git and GitHub competitors

Sometimes when it comes to differentiating between Git and GitHub, I think it's good to look at who they compete against. Git competes on a plane with tools like Mercurial, Subversion and RTC, whereas GitHub is more in the SaaS space competing against cloud vendors such as GitLab and Atlassian's BitBucket.

No GitHub Required

One thing I always like to remind people of is that you don't need GitHub or GitLab or BitBucket to use Git. Git was released in what, 2005? GitHub didn't come on the scene until 2007 or 2008, so big organizations were doing distributed version control with Git long before the cloud hosting vendors came along. So Git is just fine on its own. It doesn't need a cloud hosting service to be effective. But at the same time, having a PaaS provider certainly doesn't hurt.

Working with GitHub Desktop

By the way, you mentioned the mismatch between the repositories in your GitHub account and the repos you have locally? That's understandable. Until you've connected and done a pull or a fetch, the local Git repo doesn't know about the remote GitHub repo. Having said that, GitHub provides a tool known as the GitHub desktop that allows you to connect to GitHub from a desktop client and easily load local Git repos to GitHub, or bring GitHub repos onto your local machine.

GitHub Desktop

I'm not overly impressed by the tool, as once you know Git, these things aren't that hard to do in the Bash shell, but it's an option.

The fight between Git and GitHub

How to make child process die after parent exits?

Under Linux, you can install a parent death signal in the child, e.g.:

#include <sys/prctl.h> // prctl(), PR_SET_PDEATHSIG
#include <signal.h> // signals
#include <unistd.h> // fork()
#include <stdio.h>  // perror()

// ...

pid_t ppid_before_fork = getpid();
pid_t pid = fork();
if (pid == -1) { perror(0); exit(1); }
if (pid) {
    ; // continue parent execution
} else {
    int r = prctl(PR_SET_PDEATHSIG, SIGTERM);
    if (r == -1) { perror(0); exit(1); }
    // test in case the original parent exited just
    // before the prctl() call
    if (getppid() != ppid_before_fork)
        exit(1);
    // continue child execution ...

Note that storing the parent process id before the fork and testing it in the child after prctl() eliminates a race condition between prctl() and the exit of the process that called the child.

Also note that the parent death signal of the child is cleared in newly created children of its own. It is not affected by an execve().

That test can be simplified if we are certain that the system process who is in charge of adopting all orphans has PID 1:

pid_t pid = fork();
if (pid == -1) { perror(0); exit(1); }
if (pid) {
    ; // continue parent execution
} else {
    int r = prctl(PR_SET_PDEATHSIG, SIGTERM);
    if (r == -1) { perror(0); exit(1); }
    // test in case the original parent exited just
    // before the prctl() call
    if (getppid() == 1)
        exit(1);
    // continue child execution ...

Relying on that system process being init and having PID 1 isn't portable, though. POSIX.1-2008 specifies:

The parent process ID of all of the existing child processes and zombie processes of the calling process shall be set to the process ID of an implementation-defined system process. That is, these processes shall be inherited by a special system process.

Traditionally, the system process adopting all orphans is PID 1, i.e. init - which is the ancestor of all processes.

On modern systems like Linux or FreeBSD another process might have that role. For example, on Linux, a process can call prctl(PR_SET_CHILD_SUBREAPER, 1) to establish itself as system process that inherits all orphans of any of its descendants (cf. an example on Fedora 25).

How do I analyze a program's core dump file with GDB when it has command-line parameters?

You can analyze the core dump file using the "gdb" command.

 gdb - The GNU Debugger

 syntax:

 # gdb executable-file core-file

 example: # gdb out.txt core.xxx 

Read a javascript cookie by name

One of the shortest ways is this, however as mentioned previously it can return the wrong cookie if there's similar names (MyCookie vs AnotherMyCookie):

var regex = /MyCookie=(.[^;]*)/ig;
var match = regex.exec(document.cookie);
var value = match[1];

I use this in a chrome extension so I know the name I'm setting, and I can make sure there won't be a duplicate, more or less.

Counting in a FOR loop using Windows Batch script

Here is a batch file that generates all 10.x.x.x addresses

@echo off

SET /A X=0
SET /A Y=0
SET /A Z=0

:loop
SET /A X+=1
echo 10.%X%.%Y%.%Z%
IF "%X%" == "256" (
 GOTO end
 ) ELSE (
 GOTO loop2
 GOTO loop
 )


:loop2
SET /A Y+=1
echo 10.%X%.%Y%.%Z%
IF "%Y%" == "256" (
  SET /A Y=0
  GOTO loop
  ) ELSE (
   GOTO loop3
   GOTO loop2
 )


:loop3

SET /A Z+=1
echo 10.%X%.%Y%.%Z%
IF "%Z%" == "255" (
  SET /A Z=0
  GOTO loop2
 ) ELSE (
   GOTO loop3
 )

:end

Replace first occurrence of string in Python

string replace() function perfectly solves this problem:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'

jQuery issue in Internet Explorer 8

The solution in my case was to take any special characters out of the URL you're trying to access. I had a tilde (~) and a percentage symbol in there, and the $.get() call failed silently.

How do I use tools:overrideLibrary in a build.gradle file?

use this code in manifest.xml

<uses-sdk
android:minSdkVersion="16"
android:maxSdkVersion="17"
tools:overrideLibrary="x"/>

"Integer number too large" error message for 600851475143

Or, you can declare input number as long, and then let it do the code tango :D ...

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.println("Enter a number");
    long n = in.nextLong();

    for (long i = 2; i <= n; i++) {
        while (n % i == 0) {
            System.out.print(", " + i);
            n /= i;
        }
    }
}

What are allowed characters in cookies?

There are 2 versions of cookies specifications
1. Version 0 cookies aka Netscape cookies,
2. Version 1 aka RFC 2965 cookies
In version 0 The name and value part of cookies are sequences of characters, excluding the semicolon, comma, equals sign, and whitespace, if not used with double quotes
version 1 is a lot more complicated you can check it here
In this version specs for name value part is almost same except name can not start with $ sign

Get the new record primary key ID from MySQL insert query?

i used return $this->db->insert_id(); for Codeigniter

jQuery vs. javascript?

Jquery VS javascript, I am completely against the OP in this question. Comparison happens with two similar things, not in such case.

Jquery is Javascript. A javascript library to reduce vague coding, collection commonly used javascript functions which has proven to help in efficient and fast coding.

Javascript is the source, the actual scripts that browser responds to.

Static nested class in Java, why?

static nested class is just like any other outer class, as it doesn't have access to outer class members.

Just for packaging convenience we can club static nested classes into one outer class for readability purpose. Other than this there is no other use case of static nested class.

Example for such kind of usage, you can find in Android R.java (resources) file. Res folder of android contains layouts (containing screen designs), drawable folder (containing images used for project), values folder (which contains string constants), etc..

Sine all the folders are part of Res folder, android tool generates a R.java (resources) file which internally contains lot of static nested classes for each of their inner folders.

Here is the look and feel of R.java file generated in android: Here they are using only for packaging convenience.

/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.techpalle.b17_testthird;

public final class R {
    public static final class drawable {
        public static final int ic_launcher=0x7f020000;
    }
    public static final class layout {
        public static final int activity_main=0x7f030000;
    }
    public static final class menu {
        public static final int main=0x7f070000;
    }
    public static final class string {
        public static final int action_settings=0x7f050001;
        public static final int app_name=0x7f050000;
        public static final int hello_world=0x7f050002;
    }
}

JUnit Testing private variables?

Despite the danger of stating the obvious: With a unit test you want to test the correct behaviour of the object - and this is defined in terms of its public interface. You are not interested in how the object accomplishes this task - this is an implementation detail and not visible to the outside. This is one of the things why OO was invented: That implementation details are hidden. So there is no point in testing private members. You said you need 100% coverage. If there is a piece of code that cannot be tested by using the public interface of the object, then this piece of code is actually never called and hence not testable. Remove it.

Difference between Relative path and absolute path in javascript

I think this example will help you in understanding this more simply.

Path differences in Windows

Windows absolute path C:\Windows\calc.exe

Windows non absolute path (relative path) calc.exe

In the above example, the absolute path contains the full path to the file and not just the file as seen in the non absolute path. In this example, if you were in a directory that did not contain "calc.exe" you would get an error message. However, when using an absolute path you can be in any directory and the computer would know where to open the "calc.exe" file.

Path differences in Linux

Linux absolute path /home/users/c/computerhope/public_html/cgi-bin

Linux non absolute path (relative path) /public_html/cgi-bin

In these example, the absolute path contains the full path to the cgi-bin directory on that computer. How to find the absolute path of a file in Linux Since most users do not want to see the full path as their prompt, by default the prompt is relative to their personal directory as shown above. To find the full absolute path of the current directory use the pwd command.

It is a best practice to use relative file paths (if possible).

When using relative file paths, your web pages will not be bound to your current base URL. All links will work on your own computer (localhost) as well as on your current public domain and your future public domains.

Check if file exists and whether it contains a specific string

Instead of storing the output of grep in a variable and then checking whether the variable is empty, you can do this:

if grep -q "poet" $file_name
then
    echo "poet was found in $file_name"
fi

============

Here are some commonly used tests:

   -d FILE
          FILE exists and is a directory
   -e FILE
          FILE exists
   -f FILE
          FILE exists and is a regular file
   -h FILE
          FILE exists and is a symbolic link (same as -L)
   -r FILE
          FILE exists and is readable
   -s FILE
          FILE exists and has a size greater than zero
   -w FILE
          FILE exists and is writable
   -x FILE
          FILE exists and is executable
   -z STRING
          the length of STRING is zero

Example:

if [ -e "$file_name" ] && [ ! -z "$used_var" ]
then
    echo "$file_name exists and $used_var is not empty"
fi

Find max and second max salary for a employee table MySQL

You can just run 2 queries as inner queries to return 2 columns:

select
  (SELECT MAX(Salary) FROM Employee) maxsalary,
  (SELECT MAX(Salary) FROM Employee
  WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )) as [2nd_max_salary]

SQL Fiddle Demo

Command CompileSwift failed with a nonzero exit code in Xcode 10

Class re-declaration will be the problem. check duplicate class and build.

How to change to an older version of Node.js

Why use any extension when you can do this without extension :)

Install specific version of node

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

Specific version : sudo n 4.4.4 instead of sudo n stable

How to push changes to github after jenkins build completes?

I followed the below Steps. It worked for me.

In Jenkins execute shell under Build, creating a file and trying to push that file from Jenkins workspace to GitHub.

enter image description here

Download Git Publisher Plugin and Configure as shown below snapshot.

enter image description here

Click on Save and Build. Now you can check your git repository whether the file was pushed successfully or not.

Vue.js toggle class on click

I've got a solution that allows you to check for different values of a prop and thus different <th> elements will become active/inactive. Using vue 2 syntax.

<th 
class="initial " 
@click.stop.prevent="myFilter('M')"
:class="[(activeDay == 'M' ? 'active' : '')]">
<span class="wkday">M</span>
</th>
...
<th 
class="initial " 
@click.stop.prevent="myFilter('T')"
:class="[(activeDay == 'T' ? 'active' : '')]">
<span class="wkday">T</span>
</th>



new Vue({
  el: '#my-container',

  data: {
      activeDay: 'M'
  },

  methods: {
    myFilter: function(day){
        this.activeDay = day;
      // some code to filter users
    }
  }
})

How to remove all listeners in an element?

If you’re not opposed to jquery, this can be done in one line:

jQuery 1.7+

$("#myEl").off()

jQuery < 1.7

$('#myEl').replaceWith($('#myEl').clone());

Here’s an example:

http://jsfiddle.net/LkfLezgd/3/

jQuery events .load(), .ready(), .unload()

NOTE: .load() & .unload() have been deprecated


$(window).load();

Will execute after the page along with all its contents are done loading. This means that all images, CSS (and content defined by CSS like custom fonts and images), scripts, etc. are all loaded. This happens event fires when your browser's "Stop" -icon becomes gray, so to speak. This is very useful to detect when the document along with all its contents are loaded.

$(document).ready();

This on the other hand will fire as soon as the web browser is capable of running your JavaScript, which happens after the parser is done with the DOM. This is useful if you want to execute JavaScript as soon as possible.

$(window).unload();

This event will be fired when you are navigating off the page. That could be Refresh/F5, pressing the previous page button, navigating to another website or closing the entire tab/window.

To sum up, ready() will be fired before load(), and unload() will be the last to be fired.

How to automatically crop and center an image

I created an angularjs directive using @Russ's and @Alex's answers

Could be interesting in 2014 and beyond :P

html

<div ng-app="croppy">
  <cropped-image src="http://placehold.it/200x200" width="100" height="100"></cropped-image>
</div>

js

angular.module('croppy', [])
  .directive('croppedImage', function () {
      return {
          restrict: "E",
          replace: true,
          template: "<div class='center-cropped'></div>",
          link: function(scope, element, attrs) {
              var width = attrs.width;
              var height = attrs.height;
              element.css('width', width + "px");
              element.css('height', height + "px");
              element.css('backgroundPosition', 'center center');
              element.css('backgroundRepeat', 'no-repeat');
              element.css('backgroundImage', "url('" + attrs.src + "')");
          }
      }
  });

fiddle link

Getting the name of a variable as a string

If the goal is to help you keep track of your variables, you can write a simple function that labels the variable and returns its value and type. For example, suppose i_f=3.01 and you round it to an integer called i_n to use in a code, and then need a string i_s that will go into a report.

def whatis(string, x):
    print(string+' value=',repr(x),type(x))
    return string+' value='+repr(x)+repr(type(x))
i_f=3.01
i_n=int(i_f)
i_s=str(i_n)
i_l=[i_f, i_n, i_s]
i_u=(i_f, i_n, i_s)

## make report that identifies all types
report='\n'+20*'#'+'\nThis is the report:\n'
report+= whatis('i_f ',i_f)+'\n'
report+=whatis('i_n ',i_n)+'\n'
report+=whatis('i_s ',i_s)+'\n'
report+=whatis('i_l ',i_l)+'\n'
report+=whatis('i_u ',i_u)+'\n'
print(report)

This prints to the window at each call for debugging purposes and also yields a string for the written report. The only downside is that you have to type the variable twice each time you call the function.

I am a Python newbie and found this very useful way to log my efforts as I program and try to cope with all the objects in Python. One flaw is that whatis() fails if it calls a function described outside the procedure where it is used. For example, int(i_f) was a valid function call only because the int function is known to Python. You could call whatis() using int(i_f**2), but if for some strange reason you choose to define a function called int_squared it must be declared inside the procedure where whatis() is used.

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

Using lambda expressions for event handlers

EventHandler handler = (s, e) => MessageBox.Show("Woho");

button.Click += handler;
button.Click -= handler;

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

When I was to get yesterday with just the date in the format Year/Month/Day I use:

$Variable = Get-Date((get-date ).AddDays(-1))  -Format "yyyy-MM-dd"

setImmediate vs. nextTick

Use setImmediate if you want to queue the function behind whatever I/O event callbacks that are already in the event queue. Use process.nextTick to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.

So in a case where you're trying to break up a long running, CPU-bound job using recursion, you would now want to use setImmediate rather than process.nextTick to queue the next iteration as otherwise any I/O event callbacks wouldn't get the chance to run between iterations.

How to replace string in Groovy

You need to escape the backslash \:

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

Outputting data from unit test in Python

I don't think this is quite what your looking for, there's no way to display variable values that don't fail, but this may help you get closer to outputting the results the way you want.

You can use the TestResult object returned by the TestRunner.run() for results analysis and processing. Particularly, TestResult.errors and TestResult.failures

About the TestResults Object:

http://docs.python.org/library/unittest.html#id3

And some code to point you in the right direction:

>>> import random
>>> import unittest
>>>
>>> class TestSequenceFunctions(unittest.TestCase):
...     def setUp(self):
...         self.seq = range(5)
...     def testshuffle(self):
...         # make sure the shuffled sequence does not lose any elements
...         random.shuffle(self.seq)
...         self.seq.sort()
...         self.assertEqual(self.seq, range(10))
...     def testchoice(self):
...         element = random.choice(self.seq)
...         error_test = 1/0
...         self.assert_(element in self.seq)
...     def testsample(self):
...         self.assertRaises(ValueError, random.sample, self.seq, 20)
...         for element in random.sample(self.seq, 5):
...             self.assert_(element in self.seq)
...
>>> suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
>>> testResult = unittest.TextTestRunner(verbosity=2).run(suite)
testchoice (__main__.TestSequenceFunctions) ... ERROR
testsample (__main__.TestSequenceFunctions) ... ok
testshuffle (__main__.TestSequenceFunctions) ... FAIL

======================================================================
ERROR: testchoice (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<stdin>", line 11, in testchoice
ZeroDivisionError: integer division or modulo by zero

======================================================================
FAIL: testshuffle (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "<stdin>", line 8, in testshuffle
AssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

----------------------------------------------------------------------
Ran 3 tests in 0.031s

FAILED (failures=1, errors=1)
>>>
>>> testResult.errors
[(<__main__.TestSequenceFunctions testMethod=testchoice>, 'Traceback (most recent call last):\n  File "<stdin>"
, line 11, in testchoice\nZeroDivisionError: integer division or modulo by zero\n')]
>>>
>>> testResult.failures
[(<__main__.TestSequenceFunctions testMethod=testshuffle>, 'Traceback (most recent call last):\n  File "<stdin>
", line 8, in testshuffle\nAssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n')]
>>>

Suppress/ print without b' prefix for bytes in Python 3

If the bytes use an appropriate character encoding already; you could print them directly:

sys.stdout.buffer.write(data)

or

nwritten = os.write(sys.stdout.fileno(), data)  # NOTE: it may write less than len(data) bytes

How can you float: right in React Native?

using flex

 <View style={{ flexDirection: 'row',}}>
                  <Text style={{fontSize: 12, lineHeight: 30, color:'#9394B3' }}>left</Text>
                  <Text style={{ flex:1, fontSize: 16, lineHeight: 30, color:'#1D2359', textAlign:'right' }}>right</Text>
               </View>

Why does the JFrame setSize() method not set the size correctly?

On OS X, you need to take into account existing window decorations. They add 22 pixels to the height. So on a JFrame, you need to tell the program this:

frame.setSize(width, height + 22);

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....

what difference does this make?

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _ 
"document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.

But, if instead it was written like this (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

Environment variables in Mac OS X

You can read up on linux, which is pretty close to what Mac OS X is. Or you can read up on BSD Unix, which is a little closer. For the most part, the differences between Linux and BSD don't amount to much.

/etc/profile are system environment variables.

~/.profile are user-specific environment variables.

"where should I set my JAVA_HOME variable?"

  • Do you have multiple users? Do they care? Would you mess some other user up by changing a /etc/profile?

Generally, I prefer not to mess with system-wide settings even though I'm the only user. I prefer to edit my local settings.

getting JRE system library unbound error in build path

This is like user3076252's answer, but you'll be choosing a different set of options:

  • Project > Properties > Java Build Path
  • Select Libraries tab > Alternate JRE > Installed JREs...
  • Click "Search." Unless you know the exact folder name, you should choose a drive to search.

It should find your unbound JRE, but this time with all the numbers in it's name (rather than unbound), and you can select it. It will take a while to search the drive, but you can stop it at any time, and it will save the results, if any.

word-wrap break-word does not work in this example

Use this code (taken from css-tricks) that will work on all browser

overflow-wrap: break-word;
word-wrap: break-word;

-ms-word-break: break-all;
/* This is the dangerous one in WebKit, as it breaks things wherever */
word-break: break-all;
/* Instead use this non-standard one: */
word-break: break-word;

/* Adds a hyphen where the word breaks, if supported (No Blink) */
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;

Same font except its weight seems different on different browsers

I have many sites with this issue & finally found a fix to firefox fonts being thicker than chrome.

You need this line next to your -webkit fix -moz-osx-font-smoothing: grayscale;

body{
    text-rendering: optimizeLegibility;
   -webkit-font-smoothing: subpixel-antialiased;
   -webkit-font-smoothing: antialiased;
   -moz-osx-font-smoothing: grayscale;
}

Get just the filename from a path in a Bash script

$ file=${$(basename $file_path)%.*}

Need table of key codes for android and presenter

List Of Key codes:

a - z-> 29 - 54

"0" - "9"-> 7 - 16

BACK BUTTON - 4, MENU BUTTON - 82

UP-19, DOWN-20, LEFT-21, RIGHT-22

SELECT (MIDDLE) BUTTON - 23

SPACE - 62, SHIFT - 59, ENTER - 66, BACKSPACE - 67

Why is there still a row limit in Microsoft Excel?

Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?

14 bits = 16 384, 20 bits = 1 048 576

14 + 20 = 34 bits = more than one 32 bit register can hold.

But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.

Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.

Update 2016:

Found a link to Microsoft's specification for Excel 2013 & 2016

  • Open workbooks: Limited by available memory and system resources
  • Worksheet size: 1,048,576 rows (20 bits) by 16,384 columns (14 bits)
  • Column width: 255 characters (8 bits)
  • Row height: 409 points
  • Page breaks: 1,026 horizontal and vertical (unexpected number, probably wrong, 10 bits is 1024)
  • Total number of characters that a cell can contain: 32,767 characters (signed 16 bits)
  • Characters in a header or footer: 255 (8 bits)
  • Sheets in a workbook: Limited by available memory (default is 1 sheet)
  • Colors in a workbook: 16 million colors (32 bit with full access to 24 bit color spectrum)
  • Named views in a workbook: Limited by available memory
  • Unique cell formats/cell styles: 64,000 (16 bits = 65536)
  • Fill styles: 256 (8 bits)
  • Line weight and styles: 256 (8 bits)
  • Unique font types: 1,024 (10 bits) global fonts available for use; 512 per workbook
  • Number formats in a workbook: Between 200 and 250, depending on the language version of Excel that you have installed
  • Names in a workbook: Limited by available memory
  • Windows in a workbook: Limited by available memory
  • Hyperlinks in a worksheet: 66,530 hyperlinks (unexpected number, probably wrong. 16 bits = 65536)
  • Panes in a window: 4
  • Linked sheets: Limited by available memory
  • Scenarios: Limited by available memory; a summary report shows only the first 251 scenarios
  • Changing cells in a scenario: 32
  • Adjustable cells in Solver: 200
  • Custom functions: Limited by available memory
  • Zoom range: 10 percent to 400 percent
  • Reports: Limited by available memory
  • Sort references: 64 in a single sort; unlimited when using sequential sorts
  • Undo levels: 100
  • Fields in a data form: 32
  • Workbook parameters: 255 parameters per workbook
  • Items displayed in filter drop-down lists: 10,000

onclick or inline script isn't working in extension

Reason

This does not work, because Chrome forbids any kind of inline code in extensions via Content Security Policy.

Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).

How to detect

If this is indeed the problem, Chrome would produce the following error in the console:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

To access a popup's JavaScript console (which is useful for debug in general), right-click your extension's button and select "Inspect popup" from the context menu.

More information on debugging a popup is available here.

How to fix

One needs to remove all inline JavaScript. There is a guide in Chrome documentation.

Suppose the original looks like:

<a onclick="handler()">Click this</a> <!-- Bad -->

One needs to remove the onclick attribute and give the element a unique id:

<a id="click-this">Click this</a> <!-- Fixed -->

And then attach the listener from a script (which must be in a .js file, suppose popup.js):

// Pure JS:
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("click-this").addEventListener("click", handler);
});

// The handler also must go in a .js file
function handler() {
  /* ... */
}

Note the wrapping in a DOMContentLoaded event. This ensures that the element exists at the time of execution. Now add the script tag, for instance in the <head> of the document:

<script src="popup.js"></script>

Alternative if you're using jQuery:

// jQuery
$(document).ready(function() {
  $("#click-this").click(handler);
});

Relaxing the policy

Q: The error mentions ways to allow inline code. I don't want to / can't change my code, how do I enable inline scripts?

A: Despite what the error says, you cannot enable inline script:

There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes 'unsafe-inline' will have no effect.

Update: Since Chrome 46, it's possible to whitelist specific inline code blocks:

As of Chrome 46, inline scripts can be whitelisted by specifying the base64-encoded hash of the source code in the policy. This hash must be prefixed by the used hash algorithm (sha256, sha384 or sha512). See Hash usage for <script> elements for an example.

However, I do not readily see a reason to use this, and it will not enable inline attributes like onclick="code".

doGet and doPost in Servlets

Introduction

You should use doGet() when you want to intercept on HTTP GET requests. You should use doPost() when you want to intercept on HTTP POST requests. That's all. Do not port the one to the other or vice versa (such as in Netbeans' unfortunate auto-generated processRequest() method). This makes no utter sense.

GET

Usually, HTTP GET requests are idempotent. I.e. you get exactly the same result everytime you execute the request (leaving authorization/authentication and the time-sensitive nature of the page —search results, last news, etc— outside consideration). We can talk about a bookmarkable request. Clicking a link, clicking a bookmark, entering raw URL in browser address bar, etcetera will all fire a HTTP GET request. If a Servlet is listening on the URL in question, then its doGet() method will be called. It's usually used to preprocess a request. I.e. doing some business stuff before presenting the HTML output from a JSP, such as gathering data for display in a table.

@WebServlet("/products")
public class ProductsServlet extends HttpServlet {

    @EJB
    private ProductService productService;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Product> products = productService.list();
        request.setAttribute("products", products); // Will be available as ${products} in JSP
        request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
    }

}

Note that the JSP file is explicitly placed in /WEB-INF folder in order to prevent endusers being able to access it directly without invoking the preprocessing servlet (and thus end up getting confused by seeing an empty table).

<table>
    <c:forEach items="${products}" var="product">
        <tr>
            <td>${product.name}</td>
            <td><a href="product?id=${product.id}">detail</a></td>
        </tr>
    </c:forEach>
</table>

Also view/edit detail links as shown in last column above are usually idempotent.

@WebServlet("/product")
public class ProductServlet extends HttpServlet {

    @EJB
    private ProductService productService;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Product product = productService.find(request.getParameter("id"));
        request.setAttribute("product", product); // Will be available as ${product} in JSP
        request.getRequestDispatcher("/WEB-INF/product.jsp").forward(request, response);
    }

}
<dl>
    <dt>ID</dt>
    <dd>${product.id}</dd>
    <dt>Name</dt>
    <dd>${product.name}</dd>
    <dt>Description</dt>
    <dd>${product.description}</dd>
    <dt>Price</dt>
    <dd>${product.price}</dd>
    <dt>Image</dt>
    <dd><img src="productImage?id=${product.id}" /></dd>
</dl>

POST

HTTP POST requests are not idempotent. If the enduser has submitted a POST form on an URL beforehand, which hasn't performed a redirect, then the URL is not necessarily bookmarkable. The submitted form data is not reflected in the URL. Copypasting the URL into a new browser window/tab may not necessarily yield exactly the same result as after the form submit. Such an URL is then not bookmarkable. If a Servlet is listening on the URL in question, then its doPost() will be called. It's usually used to postprocess a request. I.e. gathering data from a submitted HTML form and doing some business stuff with it (conversion, validation, saving in DB, etcetera). Finally usually the result is presented as HTML from the forwarded JSP page.

<form action="login" method="post">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit" value="login">
    <span class="error">${error}</span>
</form>

...which can be used in combination with this piece of Servlet:

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @EJB
    private UserService userService;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.find(username, password);

        if (user != null) {
            request.getSession().setAttribute("user", user);
            response.sendRedirect("home");
        }
        else {
            request.setAttribute("error", "Unknown user, please try again");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

}

You see, if the User is found in DB (i.e. username and password are valid), then the User will be put in session scope (i.e. "logged in") and the servlet will redirect to some main page (this example goes to http://example.com/contextname/home), else it will set an error message and forward the request back to the same JSP page so that the message get displayed by ${error}.

You can if necessary also "hide" the login.jsp in /WEB-INF/login.jsp so that the users can only access it by the servlet. This keeps the URL clean http://example.com/contextname/login. All you need to do is to add a doGet() to the servlet like this:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}

(and update the same line in doPost() accordingly)

That said, I am not sure if it is just playing around and shooting in the dark, but the code which you posted doesn't look good (such as using compareTo() instead of equals() and digging in the parameternames instead of just using getParameter() and the id and password seems to be declared as servlet instance variables — which is NOT threadsafe). So I would strongly recommend to learn a bit more about basic Java SE API using the Oracle tutorials (check the chapter "Trails Covering the Basics") and how to use JSP/Servlets the right way using those tutorials.

See also:


Update: as per the update of your question (which is pretty major, you should not remove parts of your original question, this would make the answers worthless .. rather add the information in a new block) , it turns out that you're unnecessarily setting form's encoding type to multipart/form-data. This will send the request parameters in a different composition than the (default) application/x-www-form-urlencoded which sends the request parameters as a query string (e.g. name1=value1&name2=value2&name3=value3). You only need multipart/form-data whenever you have a <input type="file"> element in the form to upload files which may be non-character data (binary data). This is not the case in your case, so just remove it and it will work as expected. If you ever need to upload files, then you'll have to set the encoding type so and parse the request body yourself. Usually you use the Apache Commons FileUpload there for, but if you're already on fresh new Servlet 3.0 API, then you can just use builtin facilities starting with HttpServletRequest#getPart(). See also this answer for a concrete example: How to upload files to server using JSP/Servlet?

How to send objects through bundle

This is a very belated answer to my own question, but it keep getting attention, so I feel I must address it. Most of these answers are correct and handle the job perfectly. However, it depends on the needs of the application. This answer will be used to describe two solutions to this problem.

Application

The first is the Application, as it has been the most spoken about answer here. The application is a good object to place entities that need a reference to a Context. A `ServerSocket` undoubtedly would need a context (for file I/o or simple `ListAdapter` updates). I, personally, prefer this route. I like application's, they are useful for context retrieving (because they can be made static and not likely cause a memory leak) and have a simple lifecycle.

Service

The Service` is second. A `Service`is actually the better choice for my problem becuase that is what services are designed to do:
A Service is an application component that can perform long-running operations in
the background and does not provide a user interface.
Services are neat in that they have a more defined lifecycle that is easier to control. Further, if needed, services can run externally of the application (ie. on boot). This can be necessary for some apps or just a neat feature.

This wasn't a full description of either, but I left links to the docs for those who want to investigate more. Overall the Service is the better for the instance I needed - running a ServerSocket to my SPP device.

Android read text raw resource file

Here goes mix of weekens's and Vovodroid's solutions.

It is more correct than Vovodroid's solution and more complete than weekens's solution.

    try {
        InputStream inputStream = res.openRawResource(resId);
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                return result.toString();
            } finally {
                reader.close();
            }
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        // process exception
    }

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

You may also have to change the "less secure apps" setting on your Gmail account. EnableSsl, use port 587 and enable "less secure apps". If you google the less secure apps part there are google help pages that will link you right to the page for your account. That was my problem but everything is working now thanks to all the answers above.

What does character set and collation mean exactly?

From MySQL docs:

A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.

Suppose that we have an alphabet with four letters: 'A', 'B', 'a', 'b'. We give each letter a number: 'A' = 0, 'B' = 1, 'a' = 2, 'b' = 3. The letter 'A' is a symbol, the number 0 is the encoding for 'A', and the combination of all four letters and their encodings is a character set.

Now, suppose that we want to compare two string values, 'A' and 'B'. The simplest way to do this is to look at the encodings: 0 for 'A' and 1 for 'B'. Because 0 is less than 1, we say 'A' is less than 'B'. Now, what we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): "compare the encodings." We call this simplest of all possible collations a binary collation.

But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters 'a' and 'b' as equivalent to 'A' and 'B'; (2) then compare the encodings. We call this a case-insensitive collation. It's a little more complex than a binary collation.

In real life, most character sets have many characters: not just 'A' and 'B' but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules: not just case insensitivity but also accent insensitivity (an "accent" is a mark attached to a character as in German 'ö') and multiple-character mappings (such as the rule that 'ö' = 'OE' in one of the two German collations).

How to save a new sheet in an existing excel file, using Pandas?

For creating a new file

x1 = np.random.randn(100, 2)
df1 = pd.DataFrame(x1)
with pd.ExcelWriter('sample.xlsx') as writer:  
    df1.to_excel(writer, sheet_name='x1')

For appending to the file, use the argument mode='a' in pd.ExcelWriter.

x2 = np.random.randn(100, 2)
df2 = pd.DataFrame(x2)
with pd.ExcelWriter('sample.xlsx', engine='openpyxl', mode='a') as writer:  
    df2.to_excel(writer, sheet_name='x2')

Default is mode ='w'. See documentation.

Trim characters in Java

My solution:

private static String trim(String string, String charSequence) {
        var str = string;
        str = str.replace(" ", "$SAVE_SPACE$").
                  replace(charSequence, " ").
                  trim().
                  replace(" ", charSequence).
                  replace("$SAVE_SPACE$", " ");
        return str;
    }

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

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

grid is not present on nonrecursivecountcells's scope.

Either make grid a global array, or pass it as a parameter to the function.

How do I get total physical memory size using PowerShell without WMI?

If you don't want to use WMI, I can suggest systeminfo.exe. But, there may be a better way to do that.

(systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim()

When should I use mmap for file access?

One area where I found mmap() to not be an advantage was when reading small files (under 16K). The overhead of page faulting to read the whole file was very high compared with just doing a single read() system call. This is because the kernel can sometimes satisify a read entirely in your time slice, meaning your code doesn't switch away. With a page fault, it seemed more likely that another program would be scheduled, making the file operation have a higher latency.

How to sum digits of an integer in java?

It might be too late, but I see that many solutions posted here use O(n^2) time complexity, this is okay for small inputs, but as you go ahead with large inputs, you might want to reduce time complexity. Here is something which I worked on to do the same in linear time complexity.

NOTE : The second solution posted by Arunkumar is constant time complexity.

    private int getDigits(int num) {
    int sum =0;
    while(num > 0) { //num consists of 2 digits max, hence O(1) operation
        sum = sum + num % 10;
        num = num / 10;
    }   
    return sum;
}
public int addDigits(int N) {
    int temp1=0, temp2= 0;
    while(N > 0) {
        temp1= N % 10;
        temp2= temp1 + temp2;
        temp2= getDigits(temp2); // this is O(1) operation
        N = N/ 10;
    }
    return temp2;
}   

Please ignore my variable naming convention, I know it is not ideal. Let me explain the code with sample input , e.g. "12345". Output must be 6, in a single traversal.

Basically what I am doing is that I go from LSB to MSB , and add digits of the sum found, in every iteration.

The values look like this

Initially temp1 = temp2 = 0

N     | temp1 ( N % 10)  | temp2 ( temp1 + temp2 )
12345 | 5                | 5   
1234  | 4                | 5 + 4 = 9 ( getDigits(9) = 9)
123   | 3                | 9 + 3 = 12 = 3 (getDigits(12) =3 )
12    | 2                | 3 + 2 = 5 (getDigits(5) = 5)
1     | 1                | 5 + 1 = 6 (getDigits(6) = 6 )

Answer is 6, and we avoided one extra loop. I hope it helps.

Moving Git repository content to another repository preserving history

I think the commands you are looking for are:

cd repo2
git checkout master
git remote add r1remote **url-of-repo1**
git fetch r1remote
git merge r1remote/master --allow-unrelated-histories
git remote rm r1remote

After that repo2/master will contain everything from repo2/master and repo1/master, and will also have the history of both of them.

IPython/Jupyter Problems saving notebook as PDF

To convert .ipynb into pdf, your system should contain 2 components,

  1. nbconvert: Is part of jupyter allows to convert ipynb to pdf

    pip install nbconvert
    OR 
    conda install nbconvert
    
  2. XeTeX: Convert ipynb to .tex format and then converting to pdf.

    sudo apt-get install texlive-xetex
    

Then you can use below command to convert to pdf,

ipython nbconvert --to pdf YOURNOTEBOOK.ipynb

In case, it doesn't work, install pandoc and try again.

sudo apt-get install pandoc

Set selected option of select box

My problem

get_courses(); //// To load the course list
$("#course").val(course); //// Setting default value of the list

I had the same issue . The Only difference from your code is that I was loading the select box through an ajax call and soon as the ajax call was executed I had set the default value of the select box

The Solution

get_courses();
   setTimeout(function() {
     $("#course").val(course);
  }, 10);

Correct file permissions for WordPress

Based on all the reading and agonizing on my own sites and after having been hacked I have come up with the above list that includes permissions for a security plugin for Wordpress called Wordfence. (Not affiliated with it)

In our example, the wordpress document root is /var/www/html/example.com/public_html

Open up the permissions so that www-data can write to the document root as follows:

cd /var/www/html/example.com
sudo chown -R www-data:www-data public_html/

Now from the dashboard in your site, as an admin you can perform updates.

Secure Site after Updates are finished by following these steps:

sudo chown -R wp-user:wp-user public_html/

The above command changes permissions of everything in the wordpress install to the wordpress FTP user.

cd public_html/wp-content
sudo chown -R www-data:wp-user wflogs
sudo chown -R www-data:wp-user uploads

The above command ensures that the security plugin Wordfence has access to its logs. The uploads directory is also writeable by www-data.

cd plugins
sudo chown -R www-data:wp-user wordfence/

The above command also ensures that the security plugin has required read write access for its proper function.

Directory and Files Permissions

# Set all directories permissions to 755
find . -type d -exec chmod 755 {} \;

# Set all files permissions to 644
find . -type f -exec chmod 644 {} \;

Set the permissions for wp-config.php to 640 so that only wp-user can read this file and no one else. Permissions of 440 didn't work for me with above file ownership.

sudo chmod 640 wp-config.php

Wordpress automatic updates using SSH were working with fine with PHP5 but broke with PHP7.0 due to problems with php7.0-ssh2 bundeld with Ubuntu 16.04 and I couldn't find how to install the right version and make it work. Fortunately a very reliable plugin called ssh-sftp-updater-support (free) makes automatic updates using SFTP possible without need for libssh2. So the above permissions never have to be loosened except in rare cases as needed.

How to compare strings in Bash

The following script reads from a file named "testonthis" line by line and then compares each line with a simple string, a string with special characters and a regular expression. If it doesn't match, then the script will print the line, otherwise not.

Space in Bash is so much important. So the following will work:

[ "$LINE" != "table_name" ] 

But the following won't:

["$LINE" != "table_name"] 

So please use as is:

cat testonthis | while read LINE
do
if [ "$LINE" != "table_name" ] && [ "$LINE" != "--------------------------------" ] && [[ "$LINE" =~ [^[:space:]] ]] && [[ "$LINE" != SQL* ]]; then
echo $LINE
fi
done

Fastest JSON reader/writer for C++

https://github.com/quartzjer/js0n

Ugliest interface possible, but does what you ask. Zero allocations.

http://zserge.com/jsmn.html Another zero-allocation approach.

The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.

Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.

And to answer your "writer" part of the question i doubt that you could beat an efficient

printf("{%s:%s}",name,value)

implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.

EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.

Concatenating null strings in Java

The second line is transformed to the following code:

s = (new StringBuilder()).append((String)null).append("hello").toString();

The append methods can handle null arguments.

How to vertically center a container in Bootstrap?

Give the container class

.container{
    height: 100vh;
    width: 100vw;
    display: flex;
}

Give the div that's inside the container:

align-content: center;

All the content inside this div will show up in the middle of the page.

How to update column value in laravel

Version 1:

// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();

Version 2:

$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();

In case of answered question you can use them:

$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();

How to align the checkbox and label in same line in html?

I had the same problem, but non of the asweres worked for me. I am using bootstap and the following css code helped me:

label {
 display: contents!important;
}

awk - concatenate two string variable and assign to a third

Could use sprintf to accomplish this:

awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file

How much memory can a 32 bit process access on a 64 bit operating system?

The limit is not 2g or 3gb its 4gb for 32bit.

The reason people think its 3gb is that the OS shows 3gb free when they really have 4gb of system ram.

Its total RAM of 4gb. So if you have a 1 gb video card that counts as part of the total ram viewed by the 32bit OS.

4Gig not 3 not 2 got it?

How do you reindex an array in PHP but with indexes starting from 1?

Here is the best way:

# Array
$array = array('tomato', '', 'apple', 'melon', 'cherry', '', '', 'banana');

that returns

Array
(
    [0] => tomato
    [1] => 
    [2] => apple
    [3] => melon
    [4] => cherry
    [5] => 
    [6] => 
    [7] => banana
)

by doing this

$array = array_values(array_filter($array));

you get this

Array
(
    [0] => tomato
    [1] => apple
    [2] => melon
    [3] => cherry
    [4] => banana
)

Explanation

array_values() : Returns the values of the input array and indexes numerically.

array_filter() : Filters the elements of an array with a user-defined function (UDF If none is provided, all entries in the input table valued FALSE will be deleted.)

Why .NET String is immutable?

Imagine being an OS working with a string that some other thread was modifying behind your back. How could you validate anything without making a copy?

How to index into a dictionary?

actually I found a novel solution that really helped me out, If you are especially concerned with the index of a certain value in a list or data set, you can just set the value of dictionary to that Index!:

Just watch:

list = ['a', 'b', 'c']
dictionary = {}
counter = 0
for i in list:
   dictionary[i] = counter
   counter += 1

print(dictionary) # dictionary = {'a':0, 'b':1, 'c':2}

Now through the power of hashmaps you can pull the index your entries in constant time (aka a whole lot faster)

Twitter Bootstrap modal: How to remove Slide down effect

The question was clear: remove only the slide: Here is how to change it in Bootstrap v3

In modals.less comment out the translate statement:

&.fade .modal-dialog {
  //   .translate(0, -25%);

why should I make a copy of a data frame in pandas

This expands on Paul's answer. In Pandas, indexing a DataFrame returns a reference to the initial DataFrame. Thus, changing the subset will change the initial DataFrame. Thus, you'd want to use the copy if you want to make sure the initial DataFrame shouldn't change. Consider the following code:

df = DataFrame({'x': [1,2]})
df_sub = df[0:1]
df_sub.x = -1
print(df)

You'll get:

x
0 -1
1  2

In contrast, the following leaves df unchanged:

df_sub_copy = df[0:1].copy()
df_sub_copy.x = -1

Why do package names often begin with "com"

Wikipedia, of all places, actually discusses this.

The idea is to make sure all package names are unique world-wide, by having authors use a variant of a DNS name they own to name the package. For example, the owners of the domain name joda.org created a number of packages whose names begin with org.joda, for example:

  • org.joda.time
  • org.joda.time.base
  • org.joda.time.chrono
  • org.joda.time.convert
  • org.joda.time.field
  • org.joda.time.format

How to create an installer for a .net Windows Service using Visual Studio

Nor Kelsey, nor Brendan solutions does not works for me in Visual Studio 2015 Community.

Here is my brief steps how to create service with installer:

  1. Run Visual Studio, Go to File->New->Project
  2. Select .NET Framework 4, in 'Search Installed Templates' type 'Service'
  3. Select 'Windows Service'. Type Name and Location. Press OK.
  4. Double click Service1.cs, right click in designer and select 'Add Installer'
  5. Double click ProjectInstaller.cs. For serviceProcessInstaller1 open Properties tab and change 'Account' property value to 'LocalService'. For serviceInstaller1 change 'ServiceName' and set 'StartType' to 'Automatic'.
  6. Double click serviceInstaller1. Visual Studio creates serviceInstaller1_AfterInstall event. Write code:

    private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {
        using (System.ServiceProcess.ServiceController sc = new 
        System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
        {
            sc.Start();
        }
    }
    
  7. Build solution. Right click on project and select 'Open Folder in File Explorer'. Go to bin\Debug.

  8. Create install.bat with below script:

    :::::::::::::::::::::::::::::::::::::::::
    :: Automatically check & get admin rights
    :::::::::::::::::::::::::::::::::::::::::
    @echo off
    CLS 
    ECHO.
    ECHO =============================
    ECHO Running Admin shell
    ECHO =============================
    
    :checkPrivileges 
    NET FILE 1>NUL 2>NUL
    if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges ) 
    
    :getPrivileges 
    if '%1'=='ELEV' (shift & goto gotPrivileges)  
    ECHO. 
    ECHO **************************************
    ECHO Invoking UAC for Privilege Escalation 
    ECHO **************************************
    
    setlocal DisableDelayedExpansion
    set "batchPath=%~0"
    setlocal EnableDelayedExpansion
    ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs" 
    ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs" 
    "%temp%\OEgetPrivileges.vbs" 
    exit /B 
    
    :gotPrivileges 
    ::::::::::::::::::::::::::::
    :START
    ::::::::::::::::::::::::::::
    setlocal & pushd .
    
    cd /d %~dp0
    %windir%\Microsoft.NET\Framework\v4.0.30319\InstallUtil /i "WindowsService1.exe"
    pause
    
  9. Create uninstall.bat file (change in pen-ult line /i to /u)
  10. To install and start service run install.bat, to stop and uninstall run uninstall.bat

How to use the CSV MIME-type?

This code can be used to export any file, including csv

// application/octet-stream tells the browser not to try to interpret the file
header('Content-type: application/octet-stream');
header('Content-Length: ' . filesize($data));
header('Content-Disposition: attachment; filename="export.csv"');

Display JSON Data in HTML Table

I created the following function to generate an html table from an arbitrary JSON object:

function toTable(json, colKeyClassMap, rowKeyClassMap){
    let tab;
    if(typeof colKeyClassMap === 'undefined'){
        colKeyClassMap = {};
    }
    if(typeof rowKeyClassMap === 'undefined'){
        rowKeyClassMap = {};
    }

    const newTable = '<table class="table table-bordered table-condensed table-striped" />';
    if($.isArray(json)){
        if(json.length === 0){
            return '[]'
        } else {
            const first = json[0];
            if($.isPlainObject(first)){
                tab = $(newTable);
                const row = $('<tr />');
                tab.append(row);
                $.each( first, function( key, value ) {
                    row.append($('<th />').addClass(colKeyClassMap[key]).text(key))
                });

                $.each( json, function( key, value ) {
                    const row = $('<tr />');
                    $.each( value, function( key, value ) {
                        row.append($('<td />').addClass(colKeyClassMap[key]).html(toTable(value, colKeyClassMap, rowKeyClassMap)))
                    });
                    tab.append(row);
                });

                return tab;
            } else if ($.isArray(first)) {
                tab = $(newTable);

                $.each( json, function( key, value ) {
                    const tr = $('<tr />');
                    const td = $('<td />');
                    tr.append(td);
                    $.each( value, function( key, value ) {
                        td.append(toTable(value, colKeyClassMap, rowKeyClassMap));
                    });
                    tab.append(tr);
                });

                return tab;
            } else {
                return json.join(", ");
            }
        }

    } else if($.isPlainObject(json)){
        tab = $(newTable);
        $.each( json, function( key, value ) {
            tab.append(
                $('<tr />')
                    .append($('<th style="width: 20%;"/>').addClass(rowKeyClassMap[key]).text(key))
                    .append($('<td />').addClass(rowKeyClassMap[key]).html(toTable(value, colKeyClassMap, rowKeyClassMap))));
        });
        return tab;
    } else if (typeof json === 'string') {
        if(json.slice(0, 4) === 'http'){
            return '<a target="_blank" href="'+json+'">'+json+'</a>';
        }
        return json;
    } else {
        return ''+json;
    }
};

So you can simply call:

$('#mydiv').html(toTable([{"city":"AMBALA","cStatus":"Y"},{"city":"ASANKHURD","cStatus":"Y"},{"city":"ASSANDH","cStatus":"Y"}]));

Python foreach equivalent

For a dict we can use a for loop to iterate through the index, key and value:

dictionary = {'a': 0, 'z': 25}
for index, (key, value) in enumerate(dictionary.items()):
     ## Code here ##

What is the proper way to URL encode Unicode characters?

I would always encode in UTF-8. From the Wikipedia page on percent encoding:

The generic URI syntax mandates that new URI schemes that provide for the representation of character data in a URI must, in effect, represent characters from the unreserved set without translation, and should convert all other characters to bytes according to UTF-8, and then percent-encode those values. This requirement was introduced in January 2005 with the publication of RFC 3986. URI schemes introduced before this date are not affected.

It seems like because there were other accepted ways of doing URL encoding in the past, browsers attempt several methods of decoding a URI, but if you're the one doing the encoding you should use UTF-8.

What killed my process and why?

I encountered this problem lately. Finally, I found my processes were killed just after Opensuse zypper update was called automatically. To disable zypper update solved my problem.

Pandas DataFrame concat vs append

Pandas concat vs append vs join vs merge

  • Concat gives the flexibility to join based on the axis( all rows or all columns)

  • Append is the specific case(axis=0, join='outer') of concat

  • Join is based on the indexes (set by set_index) on how variable =['left','right','inner','couter']

  • Merge is based on any particular column each of the two dataframes, this columns are variables on like 'left_on', 'right_on', 'on'

How do I exclude all instances of a transitive dependency when using Gradle?

in the example below I exclude

spring-boot-starter-tomcat

compile("org.springframework.boot:spring-boot-starter-web") {
     //by both name and group
     exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat' 
}

How to unescape a Java string literal in Java?

org.apache.commons.lang3.StringEscapeUtils from commons-lang3 is marked deprecated now. You can use org.apache.commons.text.StringEscapeUtils#unescapeJava(String) instead. It requires an additional Maven dependency:

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-text</artifactId>
            <version>1.4</version>
        </dependency>

and seems to handle some more special cases, it e.g. unescapes:

  • escaped backslashes, single and double quotes
  • escaped octal and unicode values
  • \\b, \\n, \\t, \\f, \\r

How can I compile and run c# program without using visual studio?

I use a batch script to compile and run C#:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc /out:%1 %2

@echo off

if errorlevel 1 (
    pause
    exit
)

start %1 %1

I call it like this:

C:\bin\csc.bat "C:\code\MyProgram.exe" "C:\code\MyProgram.cs"

I also have a shortcut in Notepad++, which you can define by going to Run > Run...:

C:\bin\csc.bat "$(CURRENT_DIRECTORY)\$(NAME_PART).exe" "$(FULL_CURRENT_PATH)"

I assigned this shortcut to my F5 key for maximum laziness.

Is it possible to create a 'link to a folder' in a SharePoint document library?

i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.

Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.

.url files can be made by saving a favourite with internet exploiter.

Create a table without a header in Markdown

At least for the GitHub Flavoured Markdown, you can give the illusion by making all the non-header row entries bold with the regular __ or ** formatting:

|Regular | text | in header | turns bold |
|-|-|-|-|
| __So__ | __bold__ | __all__ | __table entries__ |
| __and__ | __it looks__ | __like a__ | __"headerless table"__ |

Unresolved external symbol on static class members

If you are using C++ 17 you can just use the inline specifier (see https://stackoverflow.com/a/11711082/55721)


If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y

unsigned char test::X;
unsigned char test::Y;

somewhere. You might want to also initialize a static member

unsigned char test::X = 4;

and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)

OPENSSL file_get_contents(): Failed to enable crypto

Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html

For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432

Here is the example:

    $url = 'https://www.example.com/api/list';
    $cn_match = 'www.example.com';

    $data = array (     
        'apikey' => '[example api key here]',               
        'limit' => intval($limit),
        'offset' => intval($offset)
        );

    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',                
            'content' => http_build_query($data)                
            )
        , 'ssl' => array(
            'verify_peer' => true,
            'cafile' => [path to file] . "cacert.pem",
            'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
            'CN_match' => $cn_match,
            'disable_compression' => true,
            )
        );

    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

Hope that helps

Wampserver icon not going green fully, mysql services not starting up?

Wow.. This works for me. Unistall the wamp server Make sure this dependencies are successfully installed Microsoft Visual C++ Redistributable Packages vcredist_Allversions(x32 orx64) depending on your OS. Reinstall the wamp server and you are good to go. Thank you

How to solve munmap_chunk(): invalid pointer error in C++

This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

char *words; // setting this to NULL would have prevented the issue

if (condition) {
    words = malloc( 512 );

    /* calling free sometime later works here */

    free(words)
} else {

    /* do not allocate words in this branch */
}

/* free(words);  -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/

There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer


IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

GitHub Error Message - Permission denied (publickey)

Also in ubuntu, even though there was already SSH key entered in settings in BitBucket, I got this problem. The reason was, I was trying the following:

sudo git push origin master

Not sure why, but it got solved by using

git push origin master

No sudo used.

What is the effect of extern "C" in C++?

A function void f() compiled by a C compiler and a function with the same name void f() compiled by a C++ compiler are not the same function. If you wrote that function in C, and then you tried to call it from C++, then the linker would look for the C++ function and not find the C function.

extern "C" tells the C++ compiler that you have a function which was compiled by the C compiler. Once you tell it that it was compiled by the C compiler, the C++ compiler will know how to call it correctly.

It also allows the C++ compiler to compile a C++ function in such a way that the C compiler can call it. That function would officially be a C function, but since it is compiled by the C++ compiler, it can use all the C++ features and has all the C++ keywords.

Create whole path automatically when writing to a new file

Use FileUtils to handle all these headaches.

Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.

openOutputStream(File file [, boolean append]) 

Difference between Method and Function?

Both are the same, both are a term which means to encapsulate some code into a unit of work which can be called from elsewhere.

Historically, there may have been a subtle difference with a "method" being something which does not return a value, and a "function" one which does. in C# that would translate as:

public void DoSomething() {} // method
public int DoSomethingAndReturnMeANumber(){} // function

But really, I re-iterate that there is really no difference in the 2 concepts.

Fetching data from MySQL database to html dropdown list

To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.

// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query

echo '<select name="DROP DOWN NAME">'; // Open your drop down box

// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   echo '<option value="'.$row['something'].'">'.$row['something'].'</option>';
}

echo '</select>';// Close your drop down box

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.

select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable

List(of String) or Array or ArrayList

You can use IList(Of String) in the function :

Private Function getWriteBits() As IList(Of String)


Dim temp1 As String
Dim temp2 As Boolean
Dim temp3 As Boolean


'Pallet Destination Unique
Dim temp4 As Boolean
Dim temp5 As Boolean
Dim temp6 As Boolean

Dim lstWriteBits As Ilist = {temp1, temp2, temp3, temp4, temp5, temp6}

Return lstWriteBits
End Function

use list1.AddRange(list2) to add lists

Hope it helps.

Iframe transparent background

Set the background color of the src to none and allow transparencey.

[WITHIN SCR PAGE STYLE]
<style type="text/css">
    body
    {
        background:none transparent;
    }
</style>

[IFRAME]
<iframe src="#" allowtransparency="true">Error, iFrame failed to load.</iframe>

NOTE: I code my CSS a little different to how everyone else does.

Multithreading in Bash

Sure, just add & after the command:

read_cfg cfgA &
read_cfg cfgB &
read_cfg cfgC &
wait

all those jobs will then run in the background simultaneously. The optional wait command will then wait for all the jobs to finish.

Each command will run in a separate process, so it's technically not "multithreading", but I believe it solves your problem.

Javadoc link to method in other class

Aside from @see, a more general way of refering to another class and possibly method of that class is {@link somepackage.SomeClass#someMethod(paramTypes)}. This has the benefit of being usable in the middle of a javadoc description.

From the javadoc documentation (description of the @link tag):

This tag is very simliar to @see – both require the same references and accept exactly the same syntax for package.class#member and label. The main difference is that {@link} generates an in-line link rather than placing the link in the "See Also" section. Also, the {@link} tag begins and ends with curly braces to separate it from the rest of the in-line text.

How to reset radiobuttons in jQuery so that none is checked

$('#radio1').removeAttr('checked');
$('#radio2').removeAttr('checked');
$('#radio3').removeAttr('checked');
$('#radio4').removeAttr('checked');

Or

$('input[name="correctAnswer"]').removeAttr('checked');

How to remove first and last character of a string?

Another solution for this issue is use commons-lang (since version 2.0) StringUtils.substringBetween(String str, String open, String close) method. Main advantage is that it's null safe operation.

StringUtils.substringBetween("[wdsd34svdf]", "[", "]"); // returns wdsd34svdf

How to get IP address of running docker container

if you want to obtain it right within the container, you can try

ip a | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" | grep 172.17

How to use JNDI DataSource provided by Tomcat in Spring?

Assuming you have a "sampleDS" datasource definition inside your tomcat configuration, you can add following lines to your applicationContext.xml to access the datasource using JNDI.

<jee:jndi-lookup expected-type="javax.sql.DataSource" id="springBeanIdForSampleDS" jndi-name="sampleDS"/>

You have to define the namespace and schema location for jee prefix using:

xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"

Get DateTime.Now with milliseconds precision

try using datetime.now.ticks. this provides nanosecond precision. taking the delta of two ticks (stoptick - starttick)/10,000 is the millisecond of specified interval.

https://docs.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=netframework-4.7.2

How does OAuth 2 protect against things like replay attacks using the Security Token?

The other answer is very detailed and addresses the bulk of the questions raised by the OP.

To elaborate, and specifically to address the OP's question of "How does OAuth 2 protect against things like replay attacks using the Security Token?", there are two additional protections in the official recommendations for implementing OAuth 2:

1) Tokens will usually have a short expiration period (http://tools.ietf.org/html/rfc6819#section-5.1.5.3):

A short expiration time for tokens is a means of protection against the following threats:

  • replay...

2) When the token is used by Site A, the recommendation is that it will be presented not as URL parameters but in the Authorization request header field (http://tools.ietf.org/html/rfc6750):

Clients SHOULD make authenticated requests with a bearer token using the "Authorization" request header field with the "Bearer" HTTP authorization scheme. ...

The "application/x-www-form-urlencoded" method SHOULD NOT be used except in application contexts where participating browsers do not have access to the "Authorization" request header field. ...

URI Query Parameter... is included to document current use; its use is not recommended, due to its security deficiencies

How can Print Preview be called from Javascript?

I think the best that's possible in cross-browser JavaScript is window.print(), which (in Firefox 3, for me) brings up the 'print' dialog and not the print preview dialog.

FYI, the print dialog is your computer's Print popup, what you get when you do Ctrl-p. The print preview is Firefox's own Preview window, and it has more options. It's what you get with Firefox Menu > Print...

Removing multiple files from a Git repo that have already been deleted from disk

None of the flags to git-add will only stage removed files; if all you have modified are deleted files, then you're fine, but otherwise, you need to run git-status and parse the output.

Working off of Jeremy's answer, this is what I got:

git status |  sed -s "s/^.*deleted: //" | grep "\(\#\|commit\)" -v | xargs git rm
  1. Get status of files.
  2. For deleted files, isolate the name of the file.
  3. Remove all the lines that start with #s, as well as a status line that had the word "deleted" in it; I don't remember what it was, exactly, and it's not there any longer, so you may have to modify this for different situations. I think grouping of expressions might be a GNU-specific feature, so if you're not using gnutils, you may have to add multiple grep -v lines.
  4. Pass the files to git rm.

Sticking this in a shell alias now...

XSL xsl:template match="/"

It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?

But look at this, a well-formed XML document:

<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>

The root of this document has three children: a processing instruction, a comment, and an element.

So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:

<xsl:template match="/comment()"/>

Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*.

Check if a file exists or not in Windows PowerShell?

You can use the Test-Path cmd-let. So something like...

if(!(Test-Path [oldLocation]) -and !(Test-Path [newLocation]))
{
    Write-Host "$file doesn't exist in both locations."
}

How do I generate sourcemaps when using babel and webpack?

On Webpack 2 I tried all 12 devtool options. The following options link to the original file in the console and preserve line numbers. See the note below re: lines only.

https://webpack.js.org/configuration/devtool

devtool best dev options

                                build   rebuild      quality                       look
eval-source-map                 slow    pretty fast  original source               worst
inline-source-map               slow    slow         original source               medium
cheap-module-eval-source-map    medium  fast         original source (lines only)  worst
inline-cheap-module-source-map  medium  pretty slow  original source (lines only)  best

lines only

Source Maps are simplified to a single mapping per line. This usually means a single mapping per statement (assuming you author is this way). This prevents you from debugging execution on statement level and from settings breakpoints on columns of a line. Combining with minimizing is not possible as minimizers usually only emit a single line.

REVISITING THIS

On a large project I find ... eval-source-map rebuild time is ~3.5s ... inline-source-map rebuild time is ~7s

Access properties file programmatically with Spring?

This post also explatis howto access properties: http://maciej-miklas.blogspot.de/2013/07/spring-31-programmatic-access-to.html

You can access properties loaded by spring property-placeholder over such spring bean:

@Named
public class PropertiesAccessor {

    private final AbstractBeanFactory beanFactory;

    private final Map<String,String> cache = new ConcurrentHashMap<>();

    @Inject
    protected PropertiesAccessor(AbstractBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public  String getProperty(String key) {
        if(cache.containsKey(key)){
            return cache.get(key);
        }

        String foundProp = null;
        try {
            foundProp = beanFactory.resolveEmbeddedValue("${" + key.trim() + "}");
            cache.put(key,foundProp);
        } catch (IllegalArgumentException ex) {
           // ok - property was not found
        }

        return foundProp;
    }
}

Making PHP var_dump() values display one line per value

Wrap it in <pre> tags to preserve formatting.

Reading Excel file using node.js

Install 'spread_sheet' node module,it will both add and fetch row from local spreadsheet

How to remove text from a string?

This little function I made has always worked for me :)

String.prototype.deleteWord = function (searchTerm) {
    var str = this;
    var n = str.search(searchTerm);
    while (str.search(searchTerm) > -1) {
        n = str.search(searchTerm);
        str = str.substring(0, n) + str.substring(n + searchTerm.length, str.length);
    }
    return str;
}

// Use it like this:
var string = "text is the cool!!";
string.deleteWord('the'); // Returns text is cool!!

I know it is not the best, but It has always worked for me :)

Copy all values from fields in one class to another through reflection

    public <T1 extends Object, T2 extends Object> void copy(T1 origEntity, T2 destEntity) {
        DozerBeanMapper mapper = new DozerBeanMapper();
        mapper.map(origEntity,destEntity);
    }

 <dependency>
            <groupId>net.sf.dozer</groupId>
            <artifactId>dozer</artifactId>
            <version>5.4.0</version>
        </dependency>

npm install doesn't create node_modules directory

As soon as you have run npm init and you start installing npm packages it'll create the node_moduals folder after that first install

e.g

npm init

(Asks you to set up your package.json file)

npm install <package name here> --save-dev

installs package & creates the node modules directory

How do you find out which version of GTK+ is installed on Ubuntu?

Try,

apt-cache policy libgtk2.0-0 libgtk-3-0 

or,

dpkg -l libgtk2.0-0 libgtk-3-0

Python Request Post with param data

Assign the response to a value and test the attributes of it. These should tell you something useful.

response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
  • status_code should just reconfirm the code you were given before, of course

IP to Location using Javascript

You need a database that contains IP address and location mapping. Or you can use a lot of online tools to achieve this, for example: http://www.ipligence.com/geolocation

Google returs lots of result under keywords: "IP location"

How to kill an application with all its activities?

My understanding of the Android application framework is that this is specifically not permitted. An application is closed automatically when it contains no more current activities. Trying to create a "kill" button is apparently contrary to the intended design of the application system.

To get the sort of effect you want, you could initiate your various activities with startActivityForResult(), and have the exit button send back a result which tells the parent activity to finish(). That activity could then send the same result as part of its onDestroy(), which would cascade back to the main activity and result in no running activities, which should cause the app to close.

MySQL/Writing file error (Errcode 28)

We have experienced similar issue, and the problem was MySQL used /tmp directory for its needs (it's default configuration). And /tmp was located on its own partition, that had too few space for big MySQL requests.

For more details take a look for this answer: https://stackoverflow.com/a/3716778/994302

How to view unallocated free space on a hard disk through terminal

A simple solution to the answer:

parted /dev/sda

Display the help on unit. Then toggle it to the units you want.

To show free space on the device, use:

print free

How do I start a process from C#?

class ProcessStart
{
    static void Main(string[] args)
    {
        Process notePad = new Process();

        notePad.StartInfo.FileName   = "notepad.exe";
        notePad.StartInfo.Arguments = "ProcessStart.cs";

        notePad.Start();
    }
}

How can I add the new "Floating Action Button" between two widgets/layouts

Now it is part of official Design Support Library.

In your gradle:

compile 'com.android.support:design:22.2.0'

http://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html

How to get equal width of input and select fields

Updated answer

Here is how to change the box model used by the input/textarea/select elements so that they all behave the same way. You need to use the box-sizing property which is implemented with a prefix for each browser

-ms-box-sizing:content-box;
-moz-box-sizing:content-box;
-webkit-box-sizing:content-box; 
box-sizing:content-box;

This means that the 2px difference we mentioned earlier does not exist..

example at http://www.jsfiddle.net/gaby/WaxTS/5/

note: On IE it works from version 8 and upwards..


Original

if you reset their borders then the select element will always be 2 pixels less than the input elements..

example: http://www.jsfiddle.net/gaby/WaxTS/2/

Filtering collections in C#

If you're using C# 3.0 you can use linq

Or, if you prefer, use the special query syntax provided by the C# 3 compiler:

var filteredList = from x in myList
                   where x > 7
                   select x;

Pandas DataFrame to List of Dictionaries

If you are interested in only selecting one column this will work.

df[["item1"]].to_dict("records")

The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.

df["item1"].to_dict("records")

I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.

Authenticated HTTP proxy with Java

http://rolandtapken.de/blog/2012-04/java-process-httpproxyuser-and-httpproxypassword says:

Other suggest to use a custom default Authenticator. But that's dangerous because this would send your password to anybody who asks.

This is relevant if some http/https requests don't go through the proxy (which is quite possible depending on configuration). In that case, you would send your credentials directly to some http server, not to your proxy.

He suggests the following fix.

// Java ignores http.proxyUser. Here come's the workaround.
Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        if (getRequestorType() == RequestorType.PROXY) {
            String prot = getRequestingProtocol().toLowerCase();
            String host = System.getProperty(prot + ".proxyHost", "");
            String port = System.getProperty(prot + ".proxyPort", "80");
            String user = System.getProperty(prot + ".proxyUser", "");
            String password = System.getProperty(prot + ".proxyPassword", "");

            if (getRequestingHost().equalsIgnoreCase(host)) {
                if (Integer.parseInt(port) == getRequestingPort()) {
                    // Seems to be OK.
                    return new PasswordAuthentication(user, password.toCharArray());  
                }
            }
        }
        return null;
    }  
});

I haven't tried it yet, but it looks good to me.

I modified the original version slightly to use equalsIgnoreCase() instead of equals(host.toLowerCase()) because of this: http://mattryall.net/blog/2009/02/the-infamous-turkish-locale-bug and I added "80" as the default value for port to avoid NumberFormatException in Integer.parseInt(port).

How to sort a HashSet?

Just in-case you don't wanna use a TreeSet you could try this.

set = set.stream().sorted().collect(Collectors.toCollection(LinkedHashSet::new));

Clearing <input type='file' /> using jQuery

I was able to get mine working with the following code:

var input = $("#control");    
input.replaceWith(input.val('').clone(true));

C++ Vector of pointers

I am not sure what the last line means. Does it mean, I read the file, create multiple Movie objects. Then make a vector of pointers where each element (pointer) points to one of those Movie objects?

I would guess this is what is intended. The intent is probably that you read the data for one movie, allocate an object with new, fill the object in with the data, and then push the address of the data onto the vector (probably not the best design, but most likely what's intended anyway).

How to change indentation in Visual Studio Code?

You can change this in global User level or Workspace level.

Open the settings: Using the shortcut Ctrl , or clicking File > Preferences > Settings as shown below.

Settings on VS Code menu

Then, do the following 2 changes: (type tabSize in the search bar)

  1. Uncheck the checkbox of Detect Indentation
  2. Change the tab size to be 2/4 (Although I strongly think 2 is correct for JS :))

enter image description here

Select multiple columns by labels in pandas

Name- or Label-Based (using regular expression syntax)

df.filter(regex='[A-CEG-I]')   # does NOT depend on the column order

Note that any regular expression is allowed here, so this approach can be very general. E.g. if you wanted all columns starting with a capital or lowercase "A" you could use: df.filter(regex='^[Aa]')

Location-Based (depends on column order)

df[ list(df.loc[:,'A':'C']) + ['E'] + list(df.loc[:,'G':'I']) ]

Note that unlike the label-based method, this only works if your columns are alphabetically sorted. This is not necessarily a problem, however. For example, if your columns go ['A','C','B'], then you could replace 'A':'C' above with 'A':'B'.

The Long Way

And for completeness, you always have the option shown by @Magdalena of simply listing each column individually, although it could be much more verbose as the number of columns increases:

df[['A','B','C','E','G','H','I']]   # does NOT depend on the column order

Results for any of the above methods

          A         B         C         E         G         H         I
0 -0.814688 -1.060864 -0.008088  2.697203 -0.763874  1.793213 -0.019520
1  0.549824  0.269340  0.405570 -0.406695 -0.536304 -1.231051  0.058018
2  0.879230 -0.666814  1.305835  0.167621 -1.100355  0.391133  0.317467

Where do I call the BatchNormalization function in Keras?

This thread has some considerable debate about whether BN should be applied before non-linearity of current layer or to the activations of the previous layer.

Although there is no correct answer, the authors of Batch Normalization say that It should be applied immediately before the non-linearity of the current layer. The reason ( quoted from original paper) -

"We add the BN transform immediately before the nonlinearity, by normalizing x = Wu+b. We could have also normalized the layer inputs u, but since u is likely the output of another nonlinearity, the shape of its distribution is likely to change during training, and constraining its first and second moments would not eliminate the covariate shift. In contrast, Wu + b is more likely to have a symmetric, non-sparse distribution, that is “more Gaussian” (Hyv¨arinen & Oja, 2000); normalizing it is likely to produce activations with a stable distribution."

Use placeholders in yaml

I suppose https://get-ytt.io/ would be an acceptable solution to your problem

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

I was facing the same problem when I'm trying to connecting Mysql database using the Laravel application. I would like to recommend please check the password for the user. MySQL password should not have special characters like #, &, etc...

How to check which locks are held on a table

This is not exactly showing you which rows are locked, but this may helpful to you.

You can check which statements are blocked by running this:

select cmd,* from sys.sysprocesses
where blocked > 0

It will also tell you what each block is waiting on. So you can trace that all the way up to see which statement caused the first block that caused the other blocks.

Edit to add comment from @MikeBlandford:

The blocked column indicates the spid of the blocking process. You can run kill {spid} to fix it.

Swap two variables without using a temporary variable

With C# 7, you can use tuple deconstruction to achieve the desired swap in one line, and it's clear what's going on.

decimal startAngle = Convert.ToDecimal(159.9);
decimal stopAngle = Convert.ToDecimal(355.87);

(startAngle, stopAngle) = (stopAngle, startAngle);

How do I use Spring Boot to serve static content located in Dropbox folder?

Springboot (via Spring) now makes adding to existing resource handlers easy. See Dave Syers answer. To add to the existing static resource handlers, simply be sure to use a resource handler path that doesn't override existing paths.

The two "also" notes below are still valid.

. . .

[Edit: The approach below is no longer valid]

If you want to extend the default static resource handlers, then something like this seems to work:

@Configuration
@AutoConfigureAfter(DispatcherServletAutoConfiguration.class)
public class CustomWebMvcAutoConfig extends
                    WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    String myExternalFilePath = "file:///C:/Temp/whatever/m/";

    registry.addResourceHandler("/m/**").addResourceLocations(myExternalFilePath);

    super.addResourceHandlers(registry);
  }

}

The call to super.addResourceHandlers sets up the default handlers.

Also:

  • Note the trailing slash on the external file path. (Depends on your expectation for URL mappings).
  • Consider reviewing the source code of WebMvcAutoConfigurationAdapter.

Why there is no ConcurrentHashSet against ConcurrentHashMap

As pointed by this the best way to obtain a concurrency-able HashSet is by means of Collections.synchronizedSet()

Set s = Collections.synchronizedSet(new HashSet(...));

This worked for me and I haven't seen anybody really pointing to it.

EDIT This is less efficient than the currently aproved solution, as Eugene points out, since it just wraps your set into a synchronized decorator, while a ConcurrentHashMap actually implements low-level concurrency and it can back your Set just as fine. So thanks to Mr. Stepanenkov for making that clear.

http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedSet-java.util.Set-

Detect if the app was launched/opened from a push notification

Straight from the documentation for

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo:nil

If the app is running and receives a remote notification, the app calls this method to process the notification.

Your implementation of this method should use the notification to take an appropriate course of action.

And a little bit later

If the app is not running when a push notification arrives, the method launches the app and provides the appropriate information in the launch options dictionary.

The app does not call this method to handle that push notification.

Instead, your implementation of the

application:willFinishLaunchingWithOptions:

or

application:didFinishLaunchingWithOptions:

method needs to get the push notification payload data and respond appropriately.

Android studio takes too much memory

In my case, there were two main sources of memory hogging: the IDE and Gradle:

Android Studio (up to 1.5GB)

The IDE's JVM is configured to have a max heap size. You can see this in the lower-right corner of the main interface:

Android Studio showing 725M max heap size

You can reduce this by editing the memory-related settings in the .vmoptions file. For example, I changed my max heap size to 512MB:

-Xmx512m

Unfortunately, I found that lowering this value increases the frequency of Android Studio temporarily freezing, perhaps to do its garbage collection.

Gradle (up to 1.5GB)

Gradle can also use a lot of RAM after developing for a while. Windows just shows it as Java(TM) Platform SE Binary:

Windows 8.1 Task Manager showing "Java(TM Platform SE binary" using 1,460.5 MB of memory

You can fix this by changing the Gradle JVM options. You can do this on a per-user basis by editing gradle.properties:

  1. Open the gradle.properties file, creating it if it doesn't exist:
    • Windows: %USERPROFILE%\.gradle\gradle.properties
    • Linux/Mac: ~/.gradle/gradle.properties
  2. Update the org.gradle.jvmargs property, creating it if necessary. I set mine to this:

    org.gradle.jvmargs=-Xmx256m -XX:MaxPermSize=256m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
    

I haven't noticed any difference in build performance for my small project with the max heap size set to 256MB (-Xmx256m).

Note that you might need to restart Android Studio so the old Gradle process is killed; otherwise you might end up with both running at the same time.

Emulator

Regarding the emulator taking up a lot of your RAM, your screenshot shows it taking about 800MB. You can choose how much RAM to allocate to the emulator:

  1. Edit the AVD
  2. Press Show Advanced Settings
  3. Reduce the value of RAM

Android Virtual Device RAM configuration