Programs & Examples On #Createprocessasuser

Android Saving created bitmap to directory on sd card

This answer is an update with a little more consideration for OOM and various other leaks.

Assumes you have a directory intended as the destination and a name String already defined.

    File destination = new File(directory.getPath() + File.separatorChar + filename);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    source.compress(Bitmap.CompressFormat.PNG, 100, bytes);

    FileOutputStream fo = null;
    try {
        destination.createNewFile();

        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
    } catch (IOException e) {

    } finally {
        try {
            fo.close();
        } catch (IOException e) {}
    }

How to add number of days to today's date?

[UPDATE] Consider reading this before you proceed...

Moment.js

Install moment.js from here.

npm : $ npm i --save moment

Bower : $ bower install --save moment

Next,

var date = moment()
            .add(2,'d') //replace 2 with number of days you want to add
            .toDate(); //convert it to a Javascript Date Object if you like

Link Ref : http://momentjs.com/docs/#/manipulating/add/

Moment.js is an amazing Javascript library to manage Date objects and extremely light weight at 40kb.

Good Luck.

Nginx fails to load css files

I also face this issue, I tried a lot of solutions, but none really worked for me

Here's how I solved it;

A. Grant ownership of the domain document root directory (say my root directory is/var/www/nginx-demo) to the Nginx user (www-data) to avoid any permission issues:

sudo chown -R www-data: /var/www/nginx-demo

B. Confirm that your virtual host server block conforms to this standard (say I am using localhost as my server_name and my root as /var/www/nginx-demo/website)

server {
   listen 80;
   listen [::]:80;

   server_name localhost;

   root /var/www/nginx-demo/website;
   index index.html;

   location / {
            try_files $uri $uri/ =404;
   }
}

C. Test the Nginx configuration for correct syntax:

sudo nginx -t

If there are no errors in the configuration syntax the output will look like this:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

D. Restart the Nginx service for the changes to take effect:

sudo systemctl restart nginx

E. Hard refresh your website in your browser to avoid cached files with incorrect headers using the keyboard keys Ctrl + F5 or Ctrl + Fn + F5.

That's all.

I hope this helps.

How to set Apache Spark Executor memory

create a file called spark-env.sh in spark/conf directory and add this line

SPARK_EXECUTOR_MEMORY=2000m #memory size which you want to allocate for the executor

How to send multiple data fields via Ajax?

This one works for me.

Here's my PHP:

<div id="pageContent">
  <?php
    while($row = mysqli_fetch_assoc($stmt)) {
  ?>
  <br/>
  <input id="vendorName_" name="vendorName_<?php echo $row["id"]; ?>" value='<?php echo $row["vendorName"]; ?>'>
  <input id="owner_" name="owner_<?php echo $row["id"]; ?>" value='<?php echo $row["owner"]; ?>'>
  <input id="city_" name="city_<?php echo $row["id"]; ?>" value='<?php echo $row["city"]; ?>'>
  <button id="btn_update_<?php echo $row["id"]; ?>">Update</button>
  <button id="btn_delete_<?php echo $row["id"]; ?>">Delete</button>
  <?php
    }
  ?>
  </br></br>
  <input id = "vendorName_new" value="">
  <input id = "owner_new" value="">
  <input id = "city_new" value="">
  <button id = "addNewVendor" type="submit">+ New Vendor</button>
</div>

Here's my jQuery using AJAX:

$("#addNewVendor").click(function() {
  alert();
  $.ajax({
    type: "POST",
    url: "create.php",
    data: {vendorName: $("#vendorName_new").val(), owner: $("#owner_new").val(), city: $("#city_new").val()},
    success: function(){
      $(this).hide();
      $('div.success').fadeIn();
      showUsers()
    }
  });
});

How to revert uncommitted changes including files and folders?

A safe and long way:

  1. git branch todelete
  2. git checkout todelete
  3. git add .
  4. git commit -m "I did a bad thing, sorry"
  5. git checkout develop
  6. git branch -D todelete

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

I tried a few times and finally solved the problem by uninstalling several times the VS2010. I think I hadn't uninstalled all the files and that's why it didn't work for the first time.

In the installation of VS2012, it is said that if you have VS2010 SP1 you can't work on the same project in both programs. It is recommended to have only one program.

Thanks!

How to $http Synchronous call with AngularJS

var EmployeeController = ["$scope", "EmployeeService",
        function ($scope, EmployeeService) {
            $scope.Employee = {};
            $scope.Save = function (Employee) {                
                if ($scope.EmployeeForm.$valid) {
                    EmployeeService
                        .Save(Employee)
                        .then(function (response) {
                            if (response.HasError) {
                                $scope.HasError = response.HasError;
                                $scope.ErrorMessage = response.ResponseMessage;
                            } else {

                            }
                        })
                        .catch(function (response) {

                        });
                }
            }
        }]


var EmployeeService = ["$http", "$q",
            function ($http, $q) {
                var self = this;

                self.Save = function (employee) {
                    var deferred = $q.defer();                
                    $http
                        .post("/api/EmployeeApi/Create", angular.toJson(employee))
                        .success(function (response, status, headers, config) {
                            deferred.resolve(response, status, headers, config);
                        })
                        .error(function (response, status, headers, config) {
                            deferred.reject(response, status, headers, config);
                        });

                    return deferred.promise;
                };

Is there a git-merge --dry-run option?

I just had to implement a method that automatically finds conflicts between a repository and its remote. This solution does the merge in memory so it won't touch the index, nor the working tree. I think this is the safest possible way you can solve this problem. Here's how it works:

  1. Fetch the remote to your repository. For example: git fetch origin master
  2. Run git merge-base: git merge-base FETCH_HEAD master
  3. Run git merge-tree: git merge-tree mergebase master FETCH_HEAD (mergebase is the hexadecimal id that merge-base printed in the previous step)

Now suppose that you want to merge the remote master with your local master, but you can use any branches. git merge-tree will execute the merge in memory and print the result to the standard output. Grep for the pattern << or >>. Or you can print the output to a file and check that. If you find a line starting with 'changed in both' then most probably there will be a conflict.

Preventing HTML and Script injections in Javascript

myDiv.textContent = arbitraryHtmlString 

as @Dan pointed out, do not use innerHTML, even in nodes you don't append to the document because deffered callbacks and scripts are always executed. You can check this https://gomakethings.com/preventing-cross-site-scripting-attacks-when-using-innerhtml-in-vanilla-javascript/ for more info.

Batch file for PuTTY/PSFTP file transfer automation

set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"

>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye

:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp

Set values using set commands before above lines.

I believe this helps you.

Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html

Convert a String of Hex into ASCII in Java

Just use a for loop to go through each couple of characters in the string, convert them to a character and then whack the character on the end of a string builder:

String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
    String str = hex.substring(i, i+2);
    output.append((char)Integer.parseInt(str, 16));
}
System.out.println(output);

Or (Java 8+) if you're feeling particularly uncouth, use the infamous "fixed width string split" hack to enable you to do a one-liner with streams instead:

System.out.println(Arrays
        .stream(hex.split("(?<=\\G..)")) //https://stackoverflow.com/questions/2297347/splitting-a-string-at-every-n-th-character
        .map(s -> Character.toString((char)Integer.parseInt(s, 16)))
        .collect(Collectors.joining()));

Either way, this gives a few lines starting with the following:

uTorrent\Completed\nfsuc_ost_by_mustang\Pendulum-9,000 Miles.mp3

Hmmm... :-)

How can I capture the result of var_dump to a string?

You could also do this:

$dump = print_r($variable, true);

selenium - chromedriver executable needs to be in PATH

try this :

driver = webdriver.Chrome(ChromeDriverManager().install())

Gridview get Checkbox.Checked value

Try this,

Using foreach Loop:

foreach (GridViewRow row in GridView1.Rows)
{
     CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
     if (chk != null && chk.Checked)
     {
       // ...
     }
}

Use it in OnRowCommand event and get checked CheckBox value.

GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];

Does --disable-web-security Work In Chrome Anymore?

Check if you have Chrome App Launcher. You can usually see it in your toolbar. It runs as a second instance of chrome, but unlike the browser, it auto-runs so is going to be running whenever you start your PC. Even though it isn't a browser view, it is a chrome instance which is enough to prevent your arguments from taking effect. Go to your task manager and you will probably have to kill 2 chrome processes.

Which terminal command to get just IP address and nothing else?

When looking up your external IP address on a NATed host, quite a few answers suggest using HTTP based methods like ifconfig.me eg:

$ curl ifconfig.me/ip

Over the years I have seen many of these sites come and go, I find this DNS based method more robust:

$ dig +short myip.opendns.com @resolver1.opendns.com

I have this handy alias in my ~/.bashrc:

alias wip='dig +short myip.opendns.com @resolver1.opendns.com'

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

I am using sp_whoisactive, very informative an basically industry standard. it returns percent complete as well.

How to set an image's width and height without stretching it?

This is quite old question, but I have had the exact same annoying issue where everything worked fine for Chrome/Edge (with object-fit property) but same css property did not work in IE11 (since its unsupported in IE11), I ended up using HTML5 "figure" element which solved all my problems.

I personally did not use the outer DIV tag since that did not help at all in my case, so I avoided the outer DIV and simply replaced with 'figure' element.

The below code forces the image to reduce/scale down nicely (without changing the original aspect ratio).

<figure class="figure-class">
  <img class="image-class" src="{{photoURL}}" />
</figure>

and css classes:

.image-class {
    border: 6px solid #E8E8E8;
    max-width: 189px;
    max-height: 189px;
}

.figure-class {
    width: 189px;
    height: 189px;
}

Java Constructor Inheritance

David's answer is correct. I'd like to add that you might be getting a sign from God that your design is messed up, and that "Son" ought not to be a subclass of "Super", but that, instead, Super has some implementation detail best expressed by having the functionality that Son provides, as a strategy of sorts.

EDIT: Jon Skeet's answer is awesomest.

Switch role after connecting to database

If someone still needs it (like I do).

The specified role_name must be a role that the current session user is a member of. https://www.postgresql.org/docs/10/sql-set-role.html

We need to make the current session user a member of the role:

create role myrole;
set role myrole;
grant myrole to myuser;
set role myrole;

produces:

Role ROLE created.


Error starting at line : 4 in command -
set role myrole
Error report -
ERROR: permission denied to set role "myrole"

Grant succeeded.


Role SET succeeded.

How to deal with SettingWithCopyWarning in Pandas

If you have assigned the slice to a variable and want to set using the variable as in the following:

df2 = df[df['A'] > 2]
df2['B'] = value

And you do not want to use Jeffs solution because your condition computing df2 is to long or for some other reason, then you can use the following:

df.loc[df2.index.tolist(), 'B'] = value

df2.index.tolist() returns the indices from all entries in df2, which will then be used to set column B in the original dataframe.

CR LF notepad++ removal

View -> Show Symbol -> uncheck Show All characters

How do I create a singleton service in Angular 2?

  1. If you want to make service singleton at application level you should define it in app.module.ts

    providers: [ MyApplicationService ] (you can define the same in child module as well to make it that module specific)

    • Do not add this service in provider which creates an instance for that component which breaks the singleton concept, just inject through constructor.
  2. If you want to define singleton service at component level create service, add that service in app.module.ts and add in providers array inside specific component as shown in below snipet.

    @Component({ selector: 'app-root', templateUrl: './test.component.html', styleUrls: ['./test.component.scss'], providers : [TestMyService] })

  3. Angular 6 provide new way to add service at application level. Instead of adding a service class to the providers[] array in AppModule , you can set the following config in @Injectable() :

    @Injectable({providedIn: 'root'}) export class MyService { ... }

The "new syntax" does offer one advantage though: Services can be loaded lazily by Angular (behind the scenes) and redundant code can be removed automatically. This can lead to a better performance and loading speed - though this really only kicks in for bigger services and apps in general.

Gradle does not find tools.jar

What solved it for me was the following:

  1. found tools.jar in C:\Program Files\Android\Android Studio\jre\lib
  2. copy paste to C:\Program Files (x86)\Java\jre1.8.0_271\lib
  3. ran the code again and it worked.

Convert all first letter to upper case, rest lower for each word

Untested but something like this should work:

var phrase = "THIS IS MY TEXT RIGHT NOW";
var rx = new System.Text.RegularExpressions.Regex(@"(?<=\w)\w");
var newString = rx.Replace(phrase,new MatchEvaluator(m=>m.Value.ToLowerInvariant()));

Essentially it says "preform a regex match on all occurrences of an alphanumeric character that follows another alphanumeric character and then replace it with a lowercase version of itself"

Python subprocess/Popen with a modified environment

To temporarily set an environment variable without having to copy the os.envrion object etc, I do this:

process = subprocess.Popen(['env', 'RSYNC_PASSWORD=foobar', 'rsync', \
'rsync://[email protected]::'], stdout=subprocess.PIPE)

RegEx for Javascript to allow only alphanumeric

JAVASCRIPT to accept only NUMBERS, ALPHABETS and SPECIAL CHARECTERS

_x000D_
_x000D_
document.getElementById("onlynumbers").onkeypress = function (e) {_x000D_
 onlyNumbers(e.key, e)_x000D_
};_x000D_
_x000D_
document.getElementById("onlyalpha").onkeypress = function (e) {_x000D_
 onlyAlpha(e.key, e)_x000D_
};_x000D_
_x000D_
document.getElementById("speclchar").onkeypress = function (e) {_x000D_
 speclChar(e.key, e)_x000D_
};_x000D_
_x000D_
function onlyNumbers(key, e) {_x000D_
 var letters = /^[0-9]/g; //g means global_x000D_
 if (!(key).match(letters)) e.preventDefault();_x000D_
}_x000D_
_x000D_
function onlyAlpha(key, e) {_x000D_
 var letters = /^[a-z]/gi; //i means ignorecase_x000D_
 if (!(key).match(letters)) e.preventDefault();_x000D_
}_x000D_
_x000D_
function speclChar(key, e) {_x000D_
 var letters = /^[0-9a-z]/gi;_x000D_
 if ((key).match(letters)) e.preventDefault();_x000D_
}
_x000D_
<html>_x000D_
   <head></head>_x000D_
   <body>_x000D_
      Enter Only Numbers: _x000D_
      <input id="onlynumbers" type="text">_x000D_
      <br><br>_x000D_
      Enter Only Alphabets: _x000D_
      <input id="onlyalpha" type="text" >_x000D_
      <br><br>_x000D_
      Enter other than Alphabets and numbers like special characters: _x000D_
      <input id="speclchar" type="text" >_x000D_
   </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I escape white space in a bash loop list?

find . -type d | while read file; do echo $file; done

However, doesn't work if the file-name contains newlines. The above is the only solution i know of when you actually want to have the directory name in a variable. If you just want to execute some command, use xargs.

find . -type d -print0 | xargs -0 echo 'The directory is: '

Can Android do peer-to-peer ad-hoc networking?

Support for peer to peer WiFi networking is available since API level 14.

Remove folder and its contents from git/GitHub's history

For Windows user, please note to use " instead of ' Also added -f to force the command if another backup is already there.

git filter-branch -f --tree-filter "rm -rf FOLDERNAME" --prune-empty HEAD
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
echo FOLDERNAME/ >> .gitignore
git add .gitignore
git commit -m "Removing FOLDERNAME from git history"
git gc
git push origin master --force

AttributeError: Module Pip has no attribute 'main'

Edit file: C:\Users\kpate\hw6\python-zulip-api\zulip_bots\setup.py in line 108

to

rcode = pip.main(['install', '-r', req_path, '--quiet'])

do

rcode = getattr(pip, '_main', pip.main)(['install', '-r', req_path, '--quiet'])´

ORA-28001: The password has expired

Just go to the machine where your database resides, search windows -> search SqlPlus Type the user name, then type password, it will prompt you to give new password. On providing new password, it will say successfully changed the password.

Paging UICollectionView by cells, not screen

Approach 1: Collection View

flowLayout is UICollectionViewFlowLayout property

override func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    if let collectionView = collectionView {

        targetContentOffset.memory = scrollView.contentOffset
        let pageWidth = CGRectGetWidth(scrollView.frame) + flowLayout.minimumInteritemSpacing

        var assistanceOffset : CGFloat = pageWidth / 3.0

        if velocity.x < 0 {
            assistanceOffset = -assistanceOffset
        }

        let assistedScrollPosition = (scrollView.contentOffset.x + assistanceOffset) / pageWidth

        var targetIndex = Int(round(assistedScrollPosition))


        if targetIndex < 0 {
            targetIndex = 0
        }
        else if targetIndex >= collectionView.numberOfItemsInSection(0) {
            targetIndex = collectionView.numberOfItemsInSection(0) - 1
        }

        print("targetIndex = \(targetIndex)")

        let indexPath = NSIndexPath(forItem: targetIndex, inSection: 0)

        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
}

Approach 2: Page View Controller

You could use UIPageViewController if it meets your requirements, each page would have a separate view controller.

How to open a new window on form submit

For a similar effect to form's target attribute, you can also use the formtarget attribute of input[type="submit]" or button[type="submit"].

From MDN:

...this attribute is a name or keyword indicating where to display the response that is received after submitting the form. This is a name of, or keyword for, a browsing context (for example, tab, window, or inline frame). If this attribute is specified, it overrides the target attribute of the elements's form owner. The following keywords have special meanings:

  • _self: Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
  • _blank: Load the response into a new unnamed browsing context.
  • _parent: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self.
  • _top: Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as _self.

R apply function with multiple parameters

To further generalize @Alexander's example, outer is relevant in cases where a function must compute itself on each pair of vector values:

vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
   var1*var2
}
outer(vars1,vars2,mult_one)

gives:

> outer(vars1, vars2, mult_one)
     [,1] [,2] [,3]
[1,]   10   20   30
[2,]   20   40   60
[3,]   30   60   90

Why did Servlet.service() for servlet jsp throw this exception?

The problem is in your JSP, most likely you are calling a method on an object that is null at runtime.

It is happening in the _jspInit() call, which is a little more unusual... the problem code is probably a method declaration like <%! %>


Update: I've only reproduced this by overriding the _jspInit() method. Is that what you're doing? If so, it's not recommended - that's why it starts with an _.

How can I quickly and easily convert spreadsheet data to JSON?

Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

  1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

    Rory Gallagher      Guitar
    Gerry McAvoy        Bass
    Rod de'Ath          Drums
    Lou Martin          Keyboards
    Donkey Kong Sioux   Self-Appointed Semi-official Stomper
    

    Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

  2. Save the file as a CSV file.

  3. Copy the contents of the CSV file to the clipboard

  4. Go to http://www.convertcsv.com/csv-to-json.htm

  5. Verify that the "First row is column names" checkbox is checked

  6. Paste the CSV data into the content area

  7. Mash the "Convert CSV to JSON" button

    With the data shown above, you will now have:

    [
      {
        "MUSICIAN":"Rory Gallagher",
        "INSTRUMENT":"Guitar"
      },
      {
        "MUSICIAN":"Gerry McAvoy",
        "INSTRUMENT":"Bass"
      },
      {
        "MUSICIAN":"Rod D'Ath",
        "INSTRUMENT":"Drums"
      },
      {
        "MUSICIAN":"Lou Martin",
        "INSTRUMENT":"Keyboards"
      }
      {
        "MUSICIAN":"Donkey Kong Sioux",
        "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
      }
    ]
    

    With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

  8. Go here: http://jsonlint.com/

  9. Paste the JSON into the content area

  10. Pres the "Validate" button.

If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

How do I configure HikariCP in my Spring Boot app in my application.properties files?

My SetUp:
Spring Boot v1.5.10
Hikari v.3.2.x (for evaluation)

To really understand the configuration of Hikari Data Source, I recommend to disable Spring Boot's Auto-Configuration for Data Source.

Add following to application.properties:-

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

This will disable Spring Boot's capability to configure the DataSource on its own.

Now is the chance for you to define your own Custom Configuration to create HikariDataSource bean and populate it with the desired properties.

NOTE :::
public class HikariDataSource extends HikariConfig

You need to

  1. populate HikariConfig Object using desired Hikari Properties
  2. initialize HikariDataSource object with HikariConfig object passed as an argument to constructor.

I believe in defining my own Custom Configuration class ( @Configuration ) to create the data source on my own and populate it with the data source properties defined in a separate file (than traditional: application.properties)

In this manner I can define my own sessionFactory Bean using Hibernate recommended: "LocalSessionFactoryBean" class and populate it with your Hikari Data Source > and other Hiberante-JPA based properties.

Summary of Spring Boot based Hikari DataSource Properties:-

spring.datasource.hikari.allow-pool-suspension=true
spring.datasource.hikari.auto-commit=false
spring.datasource.hikari.catalog=
spring.datasource.hikari.connection-init-sql=
spring.datasource.hikari.connection-test-query=
spring.datasource.hikari.connection-timeout=100
spring.datasource.hikari.data-source-class-name=
spring.datasource.hikari.data-source-j-n-d-i=
spring.datasource.hikari.driver-class-name=
spring.datasource.hikari.idle-timeout=50
spring.datasource.hikari.initialization-fail-fast=true
spring.datasource.hikari.isolate-internal-queries=true
spring.datasource.hikari.jdbc-url=
spring.datasource.hikari.leak-detection-threshold=
spring.datasource.hikari.login-timeout=60
spring.datasource.hikari.max-lifetime=
spring.datasource.hikari.maximum-pool-size=500
spring.datasource.hikari.minimum-idle=30
spring.datasource.hikari.password=
spring.datasource.hikari.pool-name=
spring.datasource.hikari.read-only=true
spring.datasource.hikari.register-mbeans=true
spring.datasource.hikari.transaction-isolation=
spring.datasource.hikari.username=
spring.datasource.hikari.validation-timeout=

How to extract or unpack an .ab file (Android Backup file)

I have had to unpack a .ab-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.

Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab-file is password-protected.

Usage:
java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]

Example:

Let's say, you've got a file test.ab, which is not password-protected, you're using Windows and want the resulting .tar-Archive to be called test.tar. Then your command should be:

java.exe -jar abe.jar unpack test.ab test.tar ""

Remove an entire column from a data.frame in R

You can set it to NULL.

> Data$genome <- NULL
> head(Data)
   chr region
1 chr1    CDS
2 chr1   exon
3 chr1    CDS
4 chr1   exon
5 chr1    CDS
6 chr1   exon

As pointed out in the comments, here are some other possibilities:

Data[2] <- NULL    # Wojciech Sobala
Data[[2]] <- NULL  # same as above
Data <- Data[,-2]  # Ian Fellows
Data <- Data[-2]   # same as above

You can remove multiple columns via:

Data[1:2] <- list(NULL)  # Marek
Data[1:2] <- NULL        # does not work!

Be careful with matrix-subsetting though, as you can end up with a vector:

Data <- Data[,-(2:3)]             # vector
Data <- Data[,-(2:3),drop=FALSE]  # still a data.frame

How can I test a change made to Jenkinsfile locally?

TL;DR

Long Version
Jenkins Pipeline testing becomes more and more of a pain. Unlike the classic declarative job configuration approach where the user was limited to what the UI exposed the new Jenkins Pipeline is a full fledged programming language for the build process where you mix the declarative part with your own code. As good developers we want to have some unit tests for this kind of code as well.

There are three steps you should follow when developing Jenkins Pipelines. The step 1. should cover 80% of the uses cases.

  1. Do as much as possible in build scripts (eg. Maven, Gradle, Gulp etc.). Then in your pipeline scripts just calls the build tasks in the right order. The build pipeline just orchestrates and executes the build tasks but does not have any major logic that needs a special testing.
  2. If the previous rule can't be fully applied then move over to Pipeline Shared libraries where you can develop and test custom logic on its own and integrate them into the pipeline.
  3. If all of the above fails you, you can try one of those libraries that came up recently (March-2017). Jenkins Pipeline Unit testing framework or pipelineUnit (examples). Since 2018 there is also Jenkinsfile Runner, a package to execution Jenkins pipelines from a command line tool.

Examples

The pipelineUnit GitHub repo contains some Spock examples on how to use Jenkins Pipeline Unit testing framework

TensorFlow not found using pip

  1. Install python by checking Add Python to Path
  2. pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.12.0-py3-none-any.whl

This works for windows 10.0

Disable vertical sync for glxgears

Putting the other answers all together, here's a command line that will work:

env vblank_mode=0 __GL_SYNC_TO_VBLANK=0 glxgears

This has the advantages of working for both Mesa and NVidia drivers, and not requiring any changes to configuration files.

How to define static property in TypeScript interface

@duncan's solution above specifying new() for the static type works also with interfaces:

interface MyType {
    instanceMethod();
}

interface MyTypeStatic {
    new():MyType;
    staticMethod();
}

How to repeat a char using printf?

If you limit yourself to repeating either a 0 or a space you can do:

For spaces:

printf("%*s", count, "");

For zeros:

printf("%0*d", count, 0);

Internal vs. Private Access Modifiers

Private members are accessible only within the body of the class or the struct in which they are declared.

Internal types or members are accessible only within files in the same assembly

Console logging for react?

If you're just after console logging here's what I'd do:

export default class App extends Component {
  componentDidMount() {
    console.log('I was triggered during componentDidMount')
  }

  render() {
    console.log('I was triggered during render')
    return ( 
      <div> I am the App component </div>
    )
  }
}

Shouldn't be any need for those packages just to do console logging.

How to get character array from a string?

The ES6 way to split a string into an array character-wise is by using the spread operator. It is simple and nice.

array = [...myString];

Example:

_x000D_
_x000D_
let myString = "Hello world!"
array = [...myString];
console.log(array);

// another example:

console.log([..."another splitted text"]);
_x000D_
_x000D_
_x000D_

How to resolve this System.IO.FileNotFoundException

I've been mislead by this error more than once. After spending hours googling, updating nuget packages, version checking, then after sitting with a completely updated solution I re-realize a perfectly valid, simpler reason for the error.

If in a threaded enthronement (UI Dispatcher.Invoke for example), System.IO.FileNotFoundException is thrown if the thread manager dll (file) fails to return. So if your main UI thread A, calls the system thread manager dll B, and B calls your thread code C, but C throws for some unrelated reason (such as null Reference as in my case), then C does not return, B does not return, and A only blames B with FileNotFoundException for being lost...

Before going down the dll version path... Check closer to home and verify your thread code is not throwing.

How to show grep result with complete path or file name

For me

grep -b "searchsomething" *.log

worked as I wanted

Find OpenCV Version Installed on Ubuntu

The other methods here didn't work for me, so here's what does work in Ubuntu 12.04 'precise'.

On Ubuntu and other Debian-derived platforms, dpkg is the typical way to get software package versions. For more recent versions than the one that @Tio refers to, use

 dpkg -l | grep libopencv

If you have the development packages installed, like libopencv-core-dev, you'll probably have .pc files and can use pkg-config:

 pkg-config --modversion opencv

Get protocol + host name from URL

You can simply use urljoin with relative root '/' as second argument:

import urllib.parse


url = 'https://stackoverflow.com/questions/9626535/get-protocol-host-name-from-url'
root_url = urllib.parse.urljoin(url, '/')
print(root_url)

Having both a Created and Last Updated timestamp columns in MySQL 4.0

If you do decide to have MySQL handle the update of timestamps, you can set up a trigger to update the field on insert.

CREATE TRIGGER <trigger_name> BEFORE INSERT ON <table_name> FOR EACH ROW SET NEW.<timestamp_field> = CURRENT_TIMESTAMP;

MySQL Reference: http://dev.mysql.com/doc/refman/5.0/en/triggers.html

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

If you want to ignore the certificate all together then take a look at the answer here: Ignore self-signed ssl cert using Jersey Client

Although this will make your app vulnerable to man-in-the-middle attacks.

Or, try adding the cert to your java store as a trusted cert. This site may be helpful. http://blog.icodejava.com/tag/get-public-key-of-ssl-certificate-in-java/

Here's another thread showing how to add a cert to your store. Java SSL connect, add server cert to keystore programmatically

The key is:

KeyStore.Entry newEntry = new KeyStore.TrustedCertificateEntry(someCert);
ks.setEntry("someAlias", newEntry, null);

The import javax.persistence cannot be resolved

hibernate-distribution-3.6.10.Final\lib\jpa : Add this jar to solve the issue. It is present in lib folder inside that you have a folder called jpa ---> inside that you have hibernate-jpa-2.0-1.0.1.Final jar

Global Angular CLI version greater than local version

This is how I fixed it. in Visual Studio Code's terminal, First cache clean

npm cache clean --force

Then updated cli

ng update @angular/cli

If any module missing after this, use below command

npm install

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

SQL Server: use CASE with LIKE

Add an END at last before alias name.

CASE WHEN countries LIKE '%'+@selCountry+'%' 
     THEN 'national' ELSE 'regional' 
END AS validity

For example:

SELECT CASE WHEN countries LIKE '%'+@selCountry+'%' 
       THEN 'national' ELSE 'regional' 
       END AS validity
FROM TableName

How to Install Font Awesome in Laravel Mix

To install font-awesome you first should install it with npm. So in your project root directory type:

npm install font-awesome --save

(Of course I assume you have node.js and npm already installed. And you've done npm install in your projects root directory)

Then edit the resources/assets/sass/app.scss file and add at the top this line:

@import "node_modules/font-awesome/scss/font-awesome.scss";

Now you can do for example:

npm run dev

This builds unminified versions of the resources in the correct folders. If you wanted to minify them, you would instead run:

npm run production

And then you can use the font.

One liner to check if element is in the list

You can use java.util.Arrays.binarySearch to find an element in an array or to check for its existence:

import java.util.Arrays;
...

char[] array = new char[] {'a', 'x', 'm'};
Arrays.sort(array); 
if (Arrays.binarySearch(array, 'm') >= 0) {
    System.out.println("Yes, m is there");
}

Be aware that for binarySearch to work correctly, the array needs to be sorted. Hence the call to Arrays.sort() in the example. If your data is already sorted, you don't need to do that. Thus, this isn't strictly a one-liner if you need to sort your array first. Unfortunately, Arrays.sort() does not return a reference to the array - thus it is not possible to combine sort and binarySearch (i.e. Arrays.binarySearch(Arrays.sort(myArray), key)) does not work).

If you can afford the extra allocation, using Arrays.asList() seems cleaner.

Round number to nearest integer

For positives, try

int(x + 0.5)

To make it work for negatives too, try

int(x + (0.5 if x > 0 else -0.5))

int() works like a floor function and hence you can exploit this property. This is definitely the fastest way.

onclick or inline script isn't working in extension

As already mentioned, Chrome Extensions don't allow to have inline JavaScript due to security reasons so you can try this workaround as well.

HTML file

<!doctype html>
    <html>
        <head>
            <title>
                Getting Started Extension's Popup
            </title>
            <script src="popup.js"></script>
        </head>
        <body>
            <div id="text-holder">ha</div><br />
            <a class="clickableBtn">
                  hyhy
            </a>
        </body>
    </html>
<!doctype html>

popup.js

window.onclick = function(event) {
    var target = event.target ;
    if(target.matches('.clickableBtn')) {
        var clickedEle = document.activeElement.id ;
        var ele = document.getElementById(clickedEle);
        alert(ele.text);
    }
}

Or if you are having a Jquery file included then

window.onclick = function(event) {
    var target = event.target ;
    if(target.matches('.clickableBtn')) {
        alert($(target).text());
    }
}

What is HTML5 ARIA?

What is ARIA?

ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.

The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.

It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.

Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.

Pretty-print a Map in Java

Using Java 8 Streams:

Map<Object, Object> map = new HashMap<>();

String content = map.entrySet()
                    .stream()
                    .map(e -> e.getKey() + "=\"" + e.getValue() + "\"")
                    .collect(Collectors.joining(", "));

System.out.println(content);

How can I convert NSDictionary to NSData and vice versa?

NSDictionary -> NSData:

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];

NSData -> NSDictionary:

NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:myData];

No templates in Visual Studio 2017

In my case, I had all of the required features, but I had installed the Team Explorer version (accidentally used the wrong installer) before installing Professional.

When running the Team Explorer version, only the Blank Solution option was available.

The Team Explorer EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\TeamExplorer\Common7\IDE\devenv.exe"

Once I launched the correct EXE, Visual Studio started working as expected.

The Professional EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\devenv.exe"

if-else statement inside jsx: ReactJS

                        <Card style={{ backgroundColor: '#ffffff', height: 150, width: 250, paddingTop: 10 }}>
                            
                            <Text style={styles.title}>     {item.lastName}, {item.firstName} ({item.title})</Text> 
                            <Text >     Email: {item.email}</Text>
                            {item.lastLoginTime != null ? <Text >     Last Login: {item.lastLoginTime}</Text> : <Text >     Last Login: None</Text>}
                            {item.lastLoginTime != null ? <Text >     Status: Active</Text> : <Text >     Status: Inactive</Text>}
                           
                        </Card>

What is the correct way to check for string equality in JavaScript?

There are actually two ways in which strings can be made in javascript.

  1. var str = 'Javascript'; This creates a primitive string value.

  2. var obj = new String('Javascript'); This creates a wrapper object of type String.

    typeof str // string
    typeof obj // object

So the best way to check for equality is using the === operator because it checks value as well as type of both operands.

If you want to check for equality between two objects then using String.prototype.valueOf is the correct way.

new String('javascript').valueOf() == new String('javascript').valueOf()

Which Java library provides base64 encoding/decoding?

Within Apache Commons, commons-codec-1.7.jar contains a Base64 class which can be used to encode.

Via Maven:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>20041127.091804</version>
</dependency>

Direct Download

Measure string size in Bytes in php

PHP's strlen() function returns the number of ASCII characters.

strlen('borsc') -> 5 (bytes)

strlen('boršc') -> 7 (bytes)

$limit_in_kBytes = 20000;

$pointer = 0;
while(strlen($your_string) > (($pointer + 1) * $limit_in_kBytes)){
    $str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
    // here you can handle (0 - n) parts of string
    $pointer++;
}

$str_to_handle = substr($your_string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);
// here you can handle last part of string

.. or you can use a function like this:

function parseStrToArr($string, $limit_in_kBytes){
    $ret = array();

    $pointer = 0;
    while(strlen($string) > (($pointer + 1) * $limit_in_kBytes)){
        $ret[] = substr($string, ($pointer * $limit_in_kBytes ), $limit_in_kBytes);
        $pointer++;
    }

    $ret[] = substr($string, ($pointer * $limit_in_kBytes), $limit_in_kBytes);

    return $ret;
}

$arr = parseStrToArr($your_string, $limit_in_kBytes = 20000);

Displaying standard DataTables in MVC

Here is the answer in Razor syntax

 <table border="1" cellpadding="5">
    <thead>
       <tr>
          @foreach (System.Data.DataColumn col in Model.Columns)
          {
             <th>@col.Caption</th>
          }
       </tr>
    </thead>
    <tbody>
    @foreach(System.Data.DataRow row in Model.Rows)
    {
       <tr>
          @foreach (var cell in row.ItemArray)
          {
             <td>@cell.ToString()</td>
          }
       </tr>
    }      
    </tbody>
</table>

Converting from Integer, to BigInteger

The method you want is BigInteger#valueOf(long val).

E.g.,

BigInteger bi = BigInteger.valueOf(myInteger.intValue());

Making a String first is unnecessary and undesired.

Convert a timedelta to days, hours and minutes

I used the following:

delta = timedelta()
totalMinute, second = divmod(delta.seconds, 60)
hour, minute = divmod(totalMinute, 60)
print(f"{hour}h{minute:02}m{second:02}s")

Find Process Name by its Process ID

The basic one, ask tasklist to filter its output and only show the indicated process id information

tasklist /fi "pid eq 4444" 

To only get the process name, the line must be splitted

for /f "delims=," %%a in ('
    tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a

In this case, the list of processes is retrieved without headers (/nh) in csv format (/fo:csv). The commas are used as token delimiters and the first token in the line is the image name

note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command

for /f "delims=," %%a in ('
    tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a

This will generate the task list and filter it searching for the process id in the second column of the csv output.

edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.

tasklist /fi "idp eq 4444" 

Programmatically register a broadcast receiver

for LocalBroadcastManager

   Intent intent = new Intent("any.action.string");
   LocalBroadcastManager.getInstance(context).
                                sendBroadcast(intent);

and register in onResume

LocalBroadcastManager.getInstance(
                    ActivityName.this).registerReceiver(chatCountBroadcastReceiver, filter);

and Unregister it onStop

LocalBroadcastManager.getInstance(
                ActivityName.this).unregisterReceiver(chatCountBroadcastReceiver);

and recieve it ..

mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("mBroadcastReceiver", "onReceive");
        }
    };

where IntentFilter is

 new IntentFilter("any.action.string")

How do you get git to always pull from a specific branch?

Under [branch "master"], try adding the following to the repo's Git config file (.git/config):

[branch "master"]
    remote = origin
    merge = refs/heads/master

This tells Git 2 things:

  1. When you're on the master branch, the default remote is origin.
  2. When using git pull on the master branch, with no remote and branch specified, use the default remote (origin) and merge in the changes from the remote master branch.

I'm not sure why this setup would've been removed from your configuration, though. You may have to follow the suggestions that other people have posted, too, but this may work (or help at least).

If you don't want to edit the config file by hand, you can use the command-line tool instead:

$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master

"CAUTION: provisional headers are shown" in Chrome debugger

Try reloading the page with ctrl + shift +F5 and then check the request headers again

Full headers are not shown because there can be a chance that request is not going to the servers and instead is served directly from Browser's cache for example using service workers

How can I apply a border only inside a table?

Due to mantain compatibility with ie7, ie8 I suggest using first-child and not last-child to doing this:

table tr td{border-top:1px solid #ffffff;border-left:1px solid #ffffff;}

table tr td:first-child{border-left:0;}

table tr:first-child td{border-top:0;}

You can learn about CSS 2.1 Pseudo-classes at: http://msdn.microsoft.com/en-us/library/cc351024(VS.85).aspx

What is the total amount of public IPv4 addresses?

According to Reserved IP addresses there are 588,514,304 reserved addresses and since there are 4,294,967,296 (2^32) IPv4 addressess in total, there are 3,706,452,992 public addresses.

And too many addresses in this post.

Access 2010 VBA query a table and iterate through results

Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:

EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!

Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Set colReturn = New Collection

Dim SQL As String
SQL = _
    "SELECT tblState.State, tblState.StateName " & _
    "FROM tblState"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
    Do Until .EOF
        colReturn.Add Nz(!State, "")
        .MoveNext
    Loop
    End If
    .Close
End With
cn.Close

Set rs = Nothing
Set cn = Nothing

Set StatesCollection = colReturn

End Function

How to add header row to a pandas DataFrame

You can use names directly in the read_csv

names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None

Cov = pd.read_csv("path/to/file.txt", 
                  sep='\t', 
                  names=["Sequence", "Start", "End", "Coverage"])

SQL Server 2000: How to exit a stored procedure?

Unless you specify a severity of 20 or higher, raiserror will not stop execution. See the MSDN documentation.

The normal workaround is to include a return after every raiserror:

if @whoops = 1
    begin
    raiserror('Whoops!', 18, 1)
    return -1
    end

Swift - Split string over multiple lines

Here's a code snippet to split a string by n characters separated over lines:

//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    override func loadView() {

        let str = String(charsPerLine: 5, "Hello World!")
        print(str) // "Hello\n Worl\nd!\n"

    }
}

extension String {

    init(charsPerLine:Int, _ str:String){

        self = ""
        var idx = 0
        for char in str {
            self += "\(char)"
            idx = idx + 1
            if idx == charsPerLine {
                self += "\n"
                idx = 0
            }
        }

    }
}

Twitter Bootstrap Button Text Word Wrap

You can simply add this class.

.btn {
    white-space:normal !important;
    word-wrap: break-word; 
}

How to count rows with SELECT COUNT(*) with SQLAlchemy?

Addition to the Usage from the ORM layer in the accepted answer: count(*) can be done for ORM using the query.with_entities(func.count()), like this:

session.query(MyModel).with_entities(func.count()).scalar()

It can also be used in more complex cases, when we have joins and filters - the important thing here is to place with_entities after joins, otherwise SQLAlchemy could raise the Don't know how to join error.

For example:

  • we have User model (id, name) and Song model (id, title, genre)
  • we have user-song data - the UserSong model (user_id, song_id, is_liked) where user_id + song_id is a primary key)

We want to get a number of user's liked rock songs:

SELECT count(*) 
  FROM user_song
  JOIN song ON user_song.song_id = song.id 
 WHERE user_song.user_id = %(user_id)
   AND user_song.is_liked IS 1
   AND song.genre = 'rock'

This query can be generated in a following way:

user_id = 1

query = session.query(UserSong)
query = query.join(Song, Song.id == UserSong.song_id)
query = query.filter(
    and_(
        UserSong.user_id == user_id, 
        UserSong.is_liked.is_(True),
        Song.genre == 'rock'
    )
)
# Note: important to place `with_entities` after the join
query = query.with_entities(func.count())
liked_count = query.scalar()

Complete example is here.

Remove ALL white spaces from text

.replace(/\s+/, "") 

Will replace the first whitespace only, this includes spaces, tabs and new lines.

To replace all whitespace in the string you need to use global mode

.replace(/\s/g, "")

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

Switch to another branch without changing the workspace files

It sounds like you made changes, committing them to master along the way, and now you want to combine them into a single commit.

If so, you want to rebase your commits, squashing them into a single commit.

I'm not entirely sure of what exactly you want, so I'm not going to tempt you with a script. But I suggest you read up on git rebase and the options for "squash"ing, and try a few things out.

Rolling back local and remote git repository by 1 commit

I just wanted to remove last commit from remote and clear commit history also. The following worked like a charm

git reset --hard HEAD^ 
git push -f 

Extract the maximum value within each group in a dataframe

There are many possibilities to do this in R. Here are some of them:

df <- read.table(header = TRUE, text = 'Gene   Value
A      12
A      10
B      3
B      5
B      6
C      1
D      3
D      4')

# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)

# tapply
tapply(df$Value, df$Gene, max)

# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))

# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))

# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))

# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]

# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)

# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')

# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]

What does a lazy val do?

A lazy val is most easily understood as a "memoized (no-arg) def".

Like a def, a lazy val is not evaluated until it is invoked. But the result is saved so that subsequent invocations return the saved value. The memoized result takes up space in your data structure, like a val.

As others have mentioned, the use cases for a lazy val are to defer expensive computations until they are needed and store their results, and to solve certain circular dependencies between values.

Lazy vals are in fact implemented more or less as memoized defs. You can read about the details of their implementation here:

http://docs.scala-lang.org/sips/pending/improved-lazy-val-initialization.html

How do I calculate a point on a circle’s circumference?

Calculating point around circumference of circle given distance travelled.
For comparison... This may be useful in Game AI when moving around a solid object in a direct path.

enter image description here

public static Point DestinationCoordinatesArc(Int32 startingPointX, Int32 startingPointY,
    Int32 circleOriginX, Int32 circleOriginY, float distanceToMove,
    ClockDirection clockDirection, float radius)
{
    // Note: distanceToMove and radius parameters are float type to avoid integer division
    // which will discard remainder

    var theta = (distanceToMove / radius) * (clockDirection == ClockDirection.Clockwise ? 1 : -1);
    var destinationX = circleOriginX + (startingPointX - circleOriginX) * Math.Cos(theta) - (startingPointY - circleOriginY) * Math.Sin(theta);
    var destinationY = circleOriginY + (startingPointX - circleOriginX) * Math.Sin(theta) + (startingPointY - circleOriginY) * Math.Cos(theta);

    // Round to avoid integer conversion truncation
    return new Point((Int32)Math.Round(destinationX), (Int32)Math.Round(destinationY));
}

/// <summary>
/// Possible clock directions.
/// </summary>
public enum ClockDirection
{
    [Description("Time moving forwards.")]
    Clockwise,
    [Description("Time moving moving backwards.")]
    CounterClockwise
}

private void ButtonArcDemo_Click(object sender, EventArgs e)
{
    Brush aBrush = (Brush)Brushes.Black;
    Graphics g = this.CreateGraphics();

    var startingPointX = 125;
    var startingPointY = 75;
    for (var count = 0; count < 62; count++)
    {
        var point = DestinationCoordinatesArc(
            startingPointX: startingPointX, startingPointY: startingPointY,
            circleOriginX: 75, circleOriginY: 75,
            distanceToMove: 5,
            clockDirection: ClockDirection.Clockwise, radius: 50);
        g.FillRectangle(aBrush, point.X, point.Y, 1, 1);

        startingPointX = point.X;
        startingPointY = point.Y;

        // Pause to visually observe/confirm clock direction
        System.Threading.Thread.Sleep(35);

        Debug.WriteLine($"DestinationCoordinatesArc({point.X}, {point.Y}");
    }
}

keycode and charcode

It is a conditional statement.

If browser supprts e.keyCode then take e.keyCode else e.charCode.

It is similar to

var code = event.keyCode || event.charCode

event.keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event.

event.charCode: Returns the Unicode value of a character key pressed during a keypress event.

Doctrine 2: Update query with query builder

I think you need to use Expr with ->set() (However THIS IS NOT SAFE and you shouldn't do it):

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', $qb->expr()->literal($username))
        ->set('u.email', $qb->expr()->literal($email))
        ->where('u.id = ?1')
        ->setParameter(1, $editId)
        ->getQuery();
$p = $q->execute();

It's much safer to make all your values parameters instead:

$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
        ->set('u.username', '?1')
        ->set('u.email', '?2')
        ->where('u.id = ?3')
        ->setParameter(1, $username)
        ->setParameter(2, $email)
        ->setParameter(3, $editId)
        ->getQuery();
$p = $q->execute();

How to remove last n characters from every element in the R vector

Here's a way with gsub:

cs <- c("foo_bar","bar_foo","apple","beer")
gsub('.{3}$', '', cs)
# [1] "foo_" "bar_" "ap"   "b"

JavaScript moving element in the DOM

There's no need to use a library for such a trivial task:

var divs = document.getElementsByTagName("div");   // order: first, second, third
divs[2].parentNode.insertBefore(divs[2], divs[0]); // order: third, first, second
divs[2].parentNode.insertBefore(divs[2], divs[1]); // order: third, second, first

This takes account of the fact that getElementsByTagName returns a live NodeList that is automatically updated to reflect the order of the elements in the DOM as they are manipulated.

You could also use:

var divs = document.getElementsByTagName("div");   // order: first, second, third
divs[0].parentNode.appendChild(divs[0]);           // order: second, third, first
divs[1].parentNode.insertBefore(divs[0], divs[1]); // order: third, second, first

and there are various other possible permutations, if you feel like experimenting:

divs[0].parentNode.appendChild(divs[0].parentNode.replaceChild(divs[2], divs[0]));

for example :-)

How can I scale an image in a CSS sprite

try using background size: http://webdesign.about.com/od/styleproperties/p/blspbgsize.htm

is there something stopping you from rendering the images at the size you want them in the first place?

Convert dictionary values into array

There is a ToArray() function on Values:

Foo[] arr = new Foo[dict.Count];    
dict.Values.CopyTo(arr, 0);

But I don't think its efficient (I haven't really tried, but I guess it copies all these values to the array). Do you really need an Array? If not, I would try to pass IEnumerable:

IEnumerable<Foo> foos = dict.Values;

How to convert array into comma separated string in javascript

You can simply use JavaScripts join() function for that. This would simply look like a.value.join(','). The output would be a string though.

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The error message explains it pretty well:

ValueError: The truth value of an array with more than one element is ambiguous. 
Use a.any() or a.all()

What should bool(np.array([False, False, True])) return? You can make several plausible arguments:

(1) True, because bool(np.array(x)) should return the same as bool(list(x)), and non-empty lists are truelike;

(2) True, because at least one element is True;

(3) False, because not all elements are True;

and that's not even considering the complexity of the N-d case.

So, since "the truth value of an array with more than one element is ambiguous", you should use .any() or .all(), for example:

>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True,  True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False

and you might want to consider np.allclose if you're comparing arrays of floats:

>>> np.allclose(np.array([1,2,3+1e-8]), np.array([1,2,3]))
True

Remove Datepicker Function dynamically

Just bind the datepicker to a class rather than binding it to the id . Remove the class when you want to revoke the datepicker...

$("#ddlSearchType").change(function () { 
  if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date")                   { 
    $("#txtSearch").addClass("mydate");
    $(".mydate").datepicker()
  } else { 
    $("#txtSearch").removeClass("mydate");
  } 
}); 

How to export settings?

With the current version of Visual Studio Code as of this writing (1.22.1), you can find your settings in

  • ~/.config/Code/User on Linux (in my case, an, Ubuntu derivative)
  • C:\Users\username\AppData\Roaming\Code\User on Windows 10
  • ~/Library/Application Support/Code/User/ on Mac OS X (thank you, Christophe De Troyer)

The files are settings.json and keybindings.json. Simply copy them to the target machine.

Your extensions are in

  • ~/.vscode/extensions on Linux and Mac OS X
  • C:\Users\username\.vscode\extensions on Windows 10 (e.g., essentially the same place)

Alternately, just go to the Extensions, show installed extensions, and install those on your target installation. For me, copying the extensions worked just fine, but it may be extension-specific, particularly if moving between platforms, depending on what the extension does.

How can I put strings in an array, split by new line?

PHP already knows the current system's newline character(s). Just use the EOL constant.

explode(PHP_EOL,$string)

How to trigger click event on href element

The native DOM method does the right thing:

$('.cssbuttongo')[0].click();
                  ^
              Important!

This works regardless of whether the href is a URL, a fragment (e.g. #blah) or even a javascript:.

Note that this calls the DOM click method instead of the jQuery click method (which is very incomplete and completely ignores href).

Hash string in c#

//Secure & Encrypte Data
    public static string HashSHA1(string value)
    {
        var sha1 = SHA1.Create();
        var inputBytes = Encoding.ASCII.GetBytes(value);
        var hash = sha1.ComputeHash(inputBytes);
        var sb = new StringBuilder();
        for (var i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("X2"));
        }
        return sb.ToString();
    }

Query for documents where array size is greater than 1

Although the above answers all work, What you originally tried to do was the correct way, however you just have the syntax backwards (switch "$size" and "$gt")..

Correct:

db.collection.find({items: {$gt: {$size: 1}}})

Incorrect:

db.collection.find({items: {$size: {$gt: 1}}})

How to disable Compatibility View in IE

This should be enough to force an IE user to drop compatibility mode in any IE version:

<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />

However, there are a couple of caveats one should be aware of:

  • The meta tag above should be included as the very first tag under <head>. Only the <title> tag may be placed above it.

If you don't do that, you'll get an error on IE9 Dev Tools: X-UA-Compatible META tag ignored because document mode is already finalized.

  • If you want this markup to validate, make sure you remember to close the meta tag with a /> instead of just >.

  • Starting with IE11, edge mode is the preferred document mode. To support/enable that, use the HTML5 document type declaration <!doctype html>.

  • If you need to support webfonts on IE7, make sure you use <!DOCTYPE html>. I've tested it and found that rendering webfonts on IE7 got pretty unreliable when using <!doctype html>.

The use of Google Chrome Frame is popular, but unfortunately it's going to be dropped sometime this month, Jan. 2014.

<meta http-equiv="X-UA-Compatible" content="IE=EDGE,chrome=1">

Extensive related info here. The tip on using it as the first meta tag is on a previously mentioned source here, which has been updated.

Retrofit 2 - URL Query Parameter

If you specify @GET("foobar?a=5"), then any @Query("b") must be appended using &, producing something like foobar?a=5&b=7.

If you specify @GET("foobar"), then the first @Query must be appended using ?, producing something like foobar?b=7.

That's how Retrofit works.

When you specify @GET("foobar?"), Retrofit thinks you already gave some query parameter, and appends more query parameters using &.

Remove the ?, and you will get the desired result.

Reading a string with scanf

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)

Difference between CR LF, LF and CR line break types?

NL derived from EBCDIC NL = x'15' which would logically compare to CRLF x'odoa ascii... this becomes evident when physcally moving data from mainframes to midrange. Coloquially (as only arcane folks use ebcdic) NL has been equated with either CR or LF or CRLF

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

You can stick the jar in the path of run time of jboss like this:

C:\User\user\workspace\jboss-as-web-7.0.0.Final\standalone\deployments\MYapplicationEAR.ear\test.war\WEB-INF\lib ca marche 100%

Kubernetes how to make Deployment to update image

Another option which is more suitable for debugging but worth mentioning is to check in revision history of your rollout:

$ kubectl rollout history deployment my-dep
deployment.apps/my-dep
 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>
3         <none>

To see the details of each revision, run:

 kubectl rollout history deployment my-dep --revision=2

And then returning to the previous revision by running:

 $kubectl rollout undo deployment my-dep --to-revision=2

And then returning back to the new one.
Like running ctrl+z -> ctrl+y (:

(*) The CHANGE-CAUSE is <none> because you should run the updates with the --record flag - like mentioned here:

kubectl set image deployment/nginx-deployment nginx=nginx:1.16.1 --record

(**) There is a discussion regarding deprecating this flag.

How do I get java logging output to appear on a single line?

I've figured out a way that works. You can subclass SimpleFormatter and override the format method

    public String format(LogRecord record) {
        return new java.util.Date() + " " + record.getLevel() + " " + record.getMessage() + "\r\n";
    }

A bit surprised at this API I would have thought that more functionality/flexibility would have been provided out of the box

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

More information will be useful.

When I was faced with the same error message all I had to do was to correctly configure the credentials page of the DataSource(I am using Report Builder 3). if you chose the default, the report would work fine in Report Builder but would fail on the Report Server.

You may review more details of this fix here: https://hodentekmsss.blogspot.com/2017/05/fix-for-rserroropeningconnection-in.html

How can a Java program get its own process ID?

Since Java 9 there is a method Process.getPid() which returns the native ID of a process:

public abstract class Process {

    ...

    public long getPid();
}

To get the process ID of the current Java process one can use the ProcessHandle interface:

System.out.println(ProcessHandle.current().pid());

Splitting applicationContext to multiple files

There are two types of contexts we are dealing with:

1: root context (parent context. Typically include all jdbc(ORM, Hibernate) initialisation and other spring security related configuration)

2: individual servlet context (child context.Typically Dispatcher Servlet Context and initialise all beans related to spring-mvc (controllers , URL Mapping etc)).

Here is an example of web.xml which includes multiple application context file

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<web-app xmlns="http://java.sun.com/xml/ns/javaee"_x000D_
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee_x000D_
                            http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">_x000D_
_x000D_
    <display-name>Spring Web Application example</display-name>_x000D_
_x000D_
    <!-- Configurations for the root application context (parent context) -->_x000D_
    <listener>_x000D_
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>_x000D_
    </listener>_x000D_
    <context-param>_x000D_
        <param-name>contextConfigLocation</param-name>_x000D_
        <param-value>_x000D_
            /WEB-INF/spring/jdbc/spring-jdbc.xml <!-- JDBC related context -->_x000D_
            /WEB-INF/spring/security/spring-security-context.xml <!-- Spring Security related context -->_x000D_
        </param-value>_x000D_
    </context-param>_x000D_
_x000D_
    <!-- Configurations for the DispatcherServlet application context (child context) -->_x000D_
    <servlet>_x000D_
        <servlet-name>spring-mvc</servlet-name>_x000D_
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>_x000D_
        <init-param>_x000D_
            <param-name>contextConfigLocation</param-name>_x000D_
            <param-value>_x000D_
                /WEB-INF/spring/mvc/spring-mvc-servlet.xml_x000D_
            </param-value>_x000D_
        </init-param>_x000D_
    </servlet>_x000D_
    <servlet-mapping>_x000D_
        <servlet-name>spring-mvc</servlet-name>_x000D_
        <url-pattern>/admin/*</url-pattern>_x000D_
    </servlet-mapping>_x000D_
_x000D_
</web-app>
_x000D_
_x000D_
_x000D_

Multiple IF statements between number ranges

Shorter than accepted A, easily extensible and addresses 0 and below:

=if(or(A2<=0,A2>2000),"?",if(A2<500,"Less than 500","Between "&500*int(A2/500)&" and "&500*(int(A2/500)+1))) 

SSL Proxy/Charles and Android trouble

I wasted 1 day finding the issue , my system was not asking connection "allow" or "reject". i though it was due to some certiifcate issue . tried all methods mentioned above but none of them worked . in the end i found "Firewall was real culprit ". if firewall settings is ON , they will not allow charles to connect with your laptop via proxy IP . make them off and all things will work smoothly .Not sure if that was relevent answer but just want to share.

Regular Expressions: Is there an AND operator?

Is it not possible in your case to do the AND on several matching results? in pseudocode

regexp_match(pattern1, data) && regexp_match(pattern2, data) && ...

Generate random colors (RGB)

With custom colours (for example, dark red, dark green and dark blue):

import random

COLORS = [(139, 0, 0), 
          (0, 100, 0),
          (0, 0, 139)]

def random_color():
    return random.choice(COLORS)

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.

What I finally end up doing was replacing the single quote ' with it code &#39; using a regex after the stringify() method call the following way:

var productToString = JSON.stringify(productObject);
var quoteReplaced = productToString.replace(/'/g, "&#39;");
var anchor = '<a data-product=\'' + quoteReplaced + '\' href=\'#\'>' + productObject.name + '</a>';
// Here you can use the "anchor" variable to update your DOM element.

What is token-based authentication?

From Auth0.com

Token-Based Authentication, relies on a signed token that is sent to the server on each request.

What are the benefits of using a token-based approach?

  • Cross-domain / CORS: cookies + CORS don't play well across different domains. A token-based approach allows you to make AJAX calls to any server, on any domain because you use an HTTP header to transmit the user information.

  • Stateless (a.k.a. Server side scalability): there is no need to keep a session store, the token is a self-contained entity that conveys all the user information. The rest of the state lives in cookies or local storage on the client side.

  • CDN: you can serve all the assets of your app from a CDN (e.g. javascript, HTML, images, etc.), and your server side is just the API.

  • Decoupling: you are not tied to any particular authentication scheme. The token might be generated anywhere, hence your API can be called from anywhere with a single way of authenticating those calls.

  • Mobile ready: when you start working on a native platform (iOS, Android, Windows 8, etc.) cookies are not ideal when consuming a token-based approach simplifies this a lot.

  • CSRF: since you are not relying on cookies, you don't need to protect against cross site requests (e.g. it would not be possible to sib your site, generate a POST request and re-use the existing authentication cookie because there will be none).

  • Performance: we are not presenting any hard perf benchmarks here, but a network roundtrip (e.g. finding a session on database) is likely to take more time than calculating an HMACSHA256 to validate a token and parsing its contents.

sudo echo "something" >> /etc/privilegedFile doesn't work

Using Yoo's answer, put this in your ~/.bashrc:

sudoe() {
    [[ "$#" -ne 2 ]] && echo "Usage: sudoe <text> <file>" && return 1
    echo "$1" | sudo tee --append "$2" > /dev/null
}

Now you can run sudoe 'deb blah # blah' /etc/apt/sources.list


Edit:

A more complete version which allows you to pipe input in or redirect from a file and includes a -a switch to turn off appending (which is on by default):

sudoe() {
  if ([[ "$1" == "-a" ]] || [[ "$1" == "--no-append" ]]); then
    shift &>/dev/null || local failed=1
  else
    local append="--append"
  fi

  while [[ $failed -ne 1 ]]; do
    if [[ -t 0 ]]; then
      text="$1"; shift &>/dev/null || break
    else
      text="$(cat <&0)"
    fi

    [[ -z "$1" ]] && break
    echo "$text" | sudo tee $append "$1" >/dev/null; return $?
  done

  echo "Usage: $0 [-a|--no-append] [text] <file>"; return 1
}

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

You have the wrong table set on the command. You should use the following on your setup:

ALTER TABLE scode_tracker.ap_visits ENGINE=MyISAM;

What is the difference between "SMS Push" and "WAP Push"?

SMS Push uses SMS as a carrier, WAP uses download via WAP.

How do I detect IE 8 with jQuery?

You can easily detect which type and version of the browser, using this jquery

$(document).ready(function()
{
 if ( $.browser.msie ){
    if($.browser.version == '6.0')
    {   $('html').addClass('ie6');
    }
    else if($.browser.version == '7.0')
    {   $('html').addClass('ie7');
    }
    else if($.browser.version == '8.0')
    {   $('html').addClass('ie8');
    }
    else if($.browser.version == '9.0')
    {   $('html').addClass('ie9');
    }
 }
 else if ( $.browser.webkit )
 { $('html').addClass('webkit');
 }
 else if ( $.browser.mozilla )
 { $('html').addClass('mozilla');
 }
 else if ( $.browser.opera )
 { $('html').addClass('opera');
 }
});

When to use extern in C++

This is useful when you want to have a global variable. You define the global variables in some source file, and declare them extern in a header file so that any file that includes that header file will then see the same global variable.

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

I've just experienced this issue. For me it appeared when some erroneous code was trying to redirect to HTTPS on port 80.

e.g.

https://example.com:80/some/page

by removing the port 80 from the url, the redirect works.

HTTPS by default runs over port 443.

Check if a folder exist in a directory and create them using C#

    String path = Server.MapPath("~/MP_Upload/");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

Difference between PCDATA and CDATA in DTD

The very main difference between PCDATA and CDATA is

PCDATA - Basically used for ELEMENTS while

CDATA - Used for Attributes of XML i.e ATTLIST

How can I get the username of the logged-in user in Django?

For classed based views use self.request.user.id

What's the difference between '$(this)' and 'this'?

this is the element, $(this) is the jQuery object constructed with that element

$(".class").each(function(){
 //the iterations current html element 
 //the classic JavaScript API is exposed here (such as .innerHTML and .appendChild)
 var HTMLElement = this;

 //the current HTML element is passed to the jQuery constructor
 //the jQuery API is exposed here (such as .html() and .append())
 var jQueryObject = $(this);
});

A deeper look

thisMDN is contained in an execution context

The scope refers to the current Execution ContextECMA. In order to understand this, it is important to understand the way execution contexts operate in JavaScript.

execution contexts bind this

When control enters an execution context (code is being executed in that scope) the environment for variables are setup (Lexical and Variable Environments - essentially this sets up an area for variables to enter which were already accessible, and an area for local variables to be stored), and the binding of this occurs.

jQuery binds this

Execution contexts form a logical stack. The result is that contexts deeper in the stack have access to previous variables, but their bindings may have been altered. Every time jQuery calls a callback function, it alters the this binding by using applyMDN.

callback.apply( obj[ i ] )//where obj[i] is the current element

The result of calling apply is that inside of jQuery callback functions, this refers to the current element being used by the callback function.

For example, in .each, the callback function commonly used allows for .each(function(index,element){/*scope*/}). In that scope, this == element is true.

jQuery callbacks use the apply function to bind the function being called with the current element. This element comes from the jQuery object's element array. Each jQuery object constructed contains an array of elements which match the selectorjQuery API that was used to instantiate the jQuery object.

$(selector) calls the jQuery function (remember that $ is a reference to jQuery, code: window.jQuery = window.$ = jQuery;). Internally, the jQuery function instantiates a function object. So while it may not be immediately obvious, using $() internally uses new jQuery(). Part of the construction of this jQuery object is to find all matches of the selector. The constructor will also accept html strings and elements. When you pass this to the jQuery constructor, you are passing the current element for a jQuery object to be constructed with. The jQuery object then contains an array-like structure of the DOM elements matching the selector (or just the single element in the case of this).

Once the jQuery object is constructed, the jQuery API is now exposed. When a jQuery api function is called, it will internally iterate over this array-like structure. For each item in the array, it calls the callback function for the api, binding the callback's this to the current element. This call can be seen in the code snippet above where obj is the array-like structure, and i is the iterator used for the position in the array of the current element.

Can I use git diff on untracked files?

For one file:

git diff --no-index /dev/null new_file

For all new files:

for next in $( git ls-files --others --exclude-standard ) ; do git --no-pager diff --no-index /dev/null $next; done;

As alias:

alias gdnew="for next in \$( git ls-files --others --exclude-standard ) ; do git --no-pager diff --no-index /dev/null \$next; done;"

For all modified and new files combined as one command:

{ git --no-pager diff; gdnew }

Smooth scroll without the use of jQuery

edit: this answer has been written in 2013. Please check Cristian Traìna's comment below about requestAnimationFrame

I made it. The code below doesn't depend on any framework.

Limitation : The anchor active is not written in the url.

Version of the code : 1.0 | Github : https://github.com/Yappli/smooth-scroll

(function() // Code in a function to create an isolate scope
{
var speed = 500;
var moving_frequency = 15; // Affects performance !
var links = document.getElementsByTagName('a');
var href;
for(var i=0; i<links.length; i++)
{   
    href = (links[i].attributes.href === undefined) ? null : links[i].attributes.href.nodeValue.toString();
    if(href !== null && href.length > 1 && href.substr(0, 1) == '#')
    {
        links[i].onclick = function()
        {
            var element;
            var href = this.attributes.href.nodeValue.toString();
            if(element = document.getElementById(href.substr(1)))
            {
                var hop_count = speed/moving_frequency
                var getScrollTopDocumentAtBegin = getScrollTopDocument();
                var gap = (getScrollTopElement(element) - getScrollTopDocumentAtBegin) / hop_count;

                for(var i = 1; i <= hop_count; i++)
                {
                    (function()
                    {
                        var hop_top_position = gap*i;
                        setTimeout(function(){  window.scrollTo(0, hop_top_position + getScrollTopDocumentAtBegin); }, moving_frequency*i);
                    })();
                }
            }

            return false;
        };
    }
}

var getScrollTopElement =  function (e)
{
    var top = 0;

    while (e.offsetParent != undefined && e.offsetParent != null)
    {
        top += e.offsetTop + (e.clientTop != null ? e.clientTop : 0);
        e = e.offsetParent;
    }

    return top;
};

var getScrollTopDocument = function()
{
    return document.documentElement.scrollTop + document.body.scrollTop;
};
})();

How to print register values in GDB?

There is also:

info all-registers

Then you can get the register name you are interested in -- very useful for finding platform-specific registers (like NEON Q... on ARM).

How to remove unused C/C++ symbols with GCC and ld?

You'll want to check your docs for your version of gcc & ld:

However for me (OS X gcc 4.0.1) I find these for ld

-dead_strip

Remove functions and data that are unreachable by the entry point or exported symbols.

-dead_strip_dylibs

Remove dylibs that are unreachable by the entry point or exported symbols. That is, suppresses the generation of load command commands for dylibs which supplied no symbols during the link. This option should not be used when linking against a dylib which is required at runtime for some indirect reason such as the dylib has an important initializer.

And this helpful option

-why_live symbol_name

Logs a chain of references to symbol_name. Only applicable with -dead_strip. It can help debug why something that you think should be dead strip removed is not removed.

There's also a note in the gcc/g++ man that certain kinds of dead code elimination are only performed if optimization is enabled when compiling.

While these options/conditions may not hold for your compiler, I suggest you look for something similar in your docs.

Accessing Imap in C#

There is no .NET framework support for IMAP. You'll need to use some 3rd party component.

Try https://www.limilabs.com/mail, it's very affordable and easy to use, it also supports SSL:

using(Imap imap = new Imap())
{
    imap.ConnectSSL("imap.company.com");
    imap.Login("user", "password");

    imap.SelectInbox();
    List<long> uids = imap.SearchFlag(Flag.Unseen);
    foreach (long uid in uids)
    {
        string eml = imap.GetMessageByUID(uid);
        IMail message = new MailBuilder()
            .CreateFromEml(eml);

        Console.WriteLine(message.Subject);
        Console.WriteLine(message.TextDataString);
    }
    imap.Close(true);
}

Please note that this is a commercial product I've created.

You can download it here: https://www.limilabs.com/mail.

ImageMagick security policy 'PDF' blocking conversion

Works in Ubuntu 20.04

Add this line inside <policymap>

<policy domain="module" rights="read|write" pattern="{PS,PDF,XPS}" />

Comment these lines:

  <!--
  <policy domain="coder" rights="none" pattern="PS" />
  <policy domain="coder" rights="none" pattern="PS2" />
  <policy domain="coder" rights="none" pattern="PS3" />
  <policy domain="coder" rights="none" pattern="EPS" />
  <policy domain="coder" rights="none" pattern="PDF" />
  <policy domain="coder" rights="none" pattern="XPS" />
   -->

How to show DatePickerDialog on Button click?

it works for me. if you want to enable future time for choose, you have to delete maximum date. You need to to do like followings.

 btnDate.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                              DialogFragment newFragment = new DatePickerFragment();
                                    newFragment.show(getSupportFragmentManager(), "datePicker");
                            }
                        });

            public static class DatePickerFragment extends DialogFragment
                        implements DatePickerDialog.OnDateSetListener {

                    @Override
                    public Dialog onCreateDialog(Bundle savedInstanceState) {
                        final Calendar c = Calendar.getInstance();
                        int year = c.get(Calendar.YEAR);
                        int month = c.get(Calendar.MONTH);
                        int day = c.get(Calendar.DAY_OF_MONTH);
                        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
                        dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
                        return  dialog;
                    }

                    public void onDateSet(DatePicker view, int year, int month, int day) {
                       btnDate.setText(ConverterDate.ConvertDate(year, month + 1, day));
                    }
                }

Bash write to file without echo?

I've a solution for bash purists.

The function 'define' helps us to assign a multiline value to a variable. This one takes one positional parameter: the variable name to assign the value.

In the heredoc, optionally there're parameter expansions too!

#!/bin/bash

define ()
{
  IFS=$'\n' read -r -d '' $1
}

BUCH="Matthäus 1"

define TEXT<<EOT
Aus dem Buch: ${BUCH}

1 Buch des Geschlechts Jesu Christi, des Sohnes Davids, des Sohnes Abrahams.
2 Abraham zeugte Isaak; Isaak aber zeugte Jakob, Jakob aber zeugte Juda und seine Brüder;
3 Juda aber zeugte Phares und Zara von der Thamar; Phares aber zeugte Esrom, Esrom aber zeugte Aram,

4 Aram aber zeugte Aminadab, Aminadab aber zeugte Nahasson, Nahasson aber zeugte Salmon,
5 Salmon aber zeugte Boas von der Rahab; Boas aber zeugte Obed von der Ruth; Obed aber zeugte Isai,
6 Isai aber zeugte David, den König. David aber zeugte Salomon von der, die Urias Weib gewesen; 

EOT

define TEXTNOEXPAND<<"EOT" # or define TEXTNOEXPAND<<'EOT'
Aus dem Buch: ${BUCH}

1 Buch des Geschlechts Jesu Christi, des Sohnes Davids, des Sohnes Abrahams.
2 Abraham zeugte Isaak; Isaak aber zeugte Jakob, Jakob aber zeugte Juda und seine Brüder;
3 Juda aber zeugte Phares und Zara von der Thamar; Phares aber zeugte Esrom, Esrom aber zeugte Aram,


4 Aram aber zeugte Aminadab, Aminadab aber zeugte Nahasson, Nahasson aber zeugte Salmon,
5 Salmon aber zeugte Boas von der Rahab; Boas aber zeugte Obed von der Ruth; Obed aber zeugte Isai,
6 Isai aber zeugte David, den König. David aber zeugte Salomon von der, die Urias Weib gewesen; 

EOT

OUTFILE="/tmp/matthäus_eins"

# Create file
>"$OUTFILE"

# Write contents
{
   printf "%s\n" "$TEXT"
   printf "%s\n" "$TEXTNOEXPAND"
} >>"$OUTFILE" 

Be lucky!

Difference between binary semaphore and mutex

Mutex work on blocking critical region, But Semaphore work on count.

How to increment a number by 2 in a PHP For Loop

You should do it like this:

 for ($i=1; $i <=10; $i+=2) 
{ 
    echo $i.'<br>';
}

"+=" you can increase your variable as much or less you want. "$i+=5" or "$i+=.5"

ValidateAntiForgeryToken purpose, explanation and example

MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.

It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.

The feature doesn't prevent any other type of data forgery or tampering based attacks.

To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html.AntiForgeryToken() in the forms posting to the method.

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

Check if list<t> contains any of another list

You could use a nested Any() for this check which is available on any Enumerable:

bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x));

Faster performing on larger collections would be to project parameters to source and then use Intersect which internally uses a HashSet<T> so instead of O(n^2) for the first approach (the equivalent of two nested loops) you can do the check in O(n) :

bool hasMatch = parameters.Select(x => x.source)
                          .Intersect(myStrings)
                          .Any(); 

Also as a side comment you should capitalize your class names and property names to conform with the C# style guidelines.

iPhone App Icons - Exact Radius?

You don't need to apply corner radius to your app icon, you can just apply square icons. The device is automatically applying corner radius.

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

Try to use this exact startup tag in your app.config under configuration node

<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    <requiredRuntime version="v4.0.20506" />
  </startup>

How to deserialize JS date using Jackson?

@JsonFormat only work for standard format supported by the jackson version that you are using.

Ex :- compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")) for jackson 2.8.6

Eclipse will not open due to environment variables

I think I found an easier way (for me anyway). Locate your javaw.exe file (either by searching for it or just where you installed it), then drag the javaw.exe file onto the eclipse.exe file and it will use it.

Homebrew install specific version of formula?

Edit: 2021, this answer is no longer functional due to the github install being deprecated. (Thanks Tim Smith for update).

Install an old brew package version (Flyway 4.2.0 example)

Find your local homebrew git dir or clone Homebrew/homebrew-core locally

cd /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/

OR

git clone [email protected]:Homebrew/homebrew-core.git

List all available versions

git log master -- Formula/flyway.rb

Copy the commit ID for the version you want and install it directly

brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/793abfa325531415184e1549836c982b39e89299/Formula/flyway.rb

What does it mean to "program to an interface"?

Q: - ... "Could you use any class that implements an interface?"
A: - Yes.

Q: - ... "When would you need to do that?"
A: - Each time you need a class(es) that implements interface(s).

Note: We couldn't instantiate an interface not implemented by a class - True.

  • Why?
  • Because the interface has only method prototypes, not definitions (just functions names, not their logic)

AnIntf anInst = new Aclass();
// we could do this only if Aclass implements AnIntf.
// anInst will have Aclass reference.


Note: Now we could understand what happened if Bclass and Cclass implemented same Dintf.

Dintf bInst = new Bclass();  
// now we could call all Dintf functions implemented (defined) in Bclass.

Dintf cInst = new Cclass();  
// now we could call all Dintf functions implemented (defined) in Cclass.

What we have: Same interface prototypes (functions names in interface), and call different implementations.

Bibliography: Prototypes - wikipedia

VBScript -- Using error handling

Note that On Error Resume Next is not set globally. You can put your unsafe part of code eg into a function, which will interrupted immediately if error occurs, and call this function from sub containing precedent OERN statement.

ErrCatch()

Sub ErrCatch()
    Dim Res, CurrentStep

    On Error Resume Next

    Res = UnSafeCode(20, CurrentStep)
    MsgBox "ErrStep " & CurrentStep & vbCrLf & Err.Description

End Sub

Function UnSafeCode(Arg, ErrStep)

    ErrStep = 1
    UnSafeCode = 1 / (Arg - 10)

    ErrStep = 2
    UnSafeCode = 1 / (Arg - 20)

    ErrStep = 3
    UnSafeCode = 1 / (Arg - 30)

    ErrStep = 0
End Function

How to output JavaScript with PHP

You need to escape your quotes.

You can do this:

echo "<script type=\"text/javascript\">";

or this:

echo "<script type='text/javascript'>";

or this:

echo '<script type="text/javascript">';

Or just stay out of php

<script type="text/javascript">

How can I determine if a .NET assembly was built for x86 or x64?

Try to use CorFlagsReader from this project at CodePlex. It has no references to other assemblies and it can be used as is.

PHP - Getting the index of a element from a array

There is no way to get a position which you really want.
For associative array, to determine last iteration you can use already mentioned counter variable, or determine last item's key first:

end($array);
$last = key($array);
foreach($array as $key => value)
  if($key == $last) ....

How to leave/exit/deactivate a Python virtualenv

It is very simple, in order to deactivate your virtual env

  • If using Anaconda - use conda deactivate
  • If not using Anaconda - use source deactivate

How do I use shell variables in an awk script?

I just changed @Jotne's answer for "for loop".

for i in `seq 11 20`; do host myserver-$i | awk -v i="$i" '{print "myserver-"i" " $4}'; done

Kill process by name?

For me the only thing that worked is been:

For example

import subprocess
proc = subprocess.Popen(["pkill", "-f", "scriptName.py"], stdout=subprocess.PIPE)
proc.wait()

C# looping through an array

This should work:

//iterate the array
for (int i = 0; i < theData.Length; i+=3)
{
    //grab 3 items at a time and do db insert, continue until all items are gone. 'theData' will always be divisible by 3.
    var a = theData[i];
    var b = theData[i + 1];
    var c = theData[i + 2];
}

I've been downvoted for this answer once. I'm pretty sure it is related to the use of theData.Length for the upperbound. The code as is works fine because array is guaranteed to be a multiple of three as the question states. If this guarantee wasn't in place, you would need to check the upper bound with theData.Length - 2 instead.

Change onclick action with a Javascript function

Do not invoke the method when assigning the new onclick handler.

Simply remove the parenthesis:

document.getElementById("a").onclick = Foo;

UPDATE (due to new information):

document.getElementById("a").onclick = function () { Foo(param); };

Event binding on dynamically created elements?

I was looking a solution to get $.bind and $.unbind working without problems in dynamically added elements.

As on() makes the trick to attach events, in order to create a fake unbind on those I came to:

const sendAction = function(e){ ... }
// bind the click
$('body').on('click', 'button.send', sendAction );

// unbind the click
$('body').on('click', 'button.send', function(){} );

Build the full path filename in Python

Um, why not just:

>>>> import os
>>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'

How to disable a link using only CSS?

Demo here
Try this one

$('html').on('click', 'a.Link', function(event){
    event.preventDefault();
});

Get CPU Usage from Windows Command Prompt

typeperf gives me issues when it randomly doesn't work on some computers (Error: No valid counters.) or if the account has insufficient rights. Otherwise, here is a way to extract just the value from its output. It still needs rounding though:

@for /f "delims=, tokens=2" %p in ('typeperf "\Processor(_Total)\% Processor Time" -sc 3 ^| find ":"') do @echo %~p%

Powershell has two cmdlets to get the percent utilization for all CPUs: Get-Counter (preferred) or Get-WmiObject:

Powershell "Get-Counter '\Processor(*)\% Processor Time' | Select -Expand Countersamples | Select InstanceName, CookedValue"

Or,

Powershell "Get-WmiObject Win32_PerfFormattedData_PerfOS_Processor | Select Name, PercentProcessorTime"


To get the overall CPU load with formatted output exactly like the question:

Powershell "[string][int](Get-Counter '\Processor(*)\% Processor Time').Countersamples[0].CookedValue + '%'"

Or,

 Powershell "gwmi Win32_PerfFormattedData_PerfOS_Processor | Select -First 1 | %{'{0}%' -f $_.PercentProcessorTime}"

@font-face src: local - How to use the local font if the user already has it?

I haven’t actually done anything with font-face, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.

The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.

Does Firefox download the font when you actually use it in a font declaration? (e.g. h1 { font: 'DejaVu Serif';)?

What is the most effective way for float and double comparison?

The portable way to get epsilon in C++ is

#include <limits>
std::numeric_limits<double>::epsilon()

Then the comparison function becomes

#include <cmath>
#include <limits>

bool AreSame(double a, double b) {
    return std::fabs(a - b) < std::numeric_limits<double>::epsilon();
}

How to convert numpy arrays to standard TensorFlow format?

You can use tf.convert_to_tensor():

import tensorflow as tf
import numpy as np

data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)

data_tf = tf.convert_to_tensor(data_np, np.float32)

sess = tf.InteractiveSession()  
print(data_tf.eval())

sess.close()

Here's a link to the documentation for this method:

https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor

SSH library for Java

I took miku's answer and jsch example code. I then had to download multiple files during the session and preserve original timestamps. This is my example code how to do it, probably many people find it usefull. Please ignore filenameHack() function its my own usecase.

package examples;

import com.jcraft.jsch.*;
import java.io.*;
import java.util.*;

public class ScpFrom2 {

    public static void main(String[] args) throws Exception {
        Map<String,String> params = parseParams(args);
        if (params.isEmpty()) {
            System.err.println("usage: java ScpFrom2 "
                    + " user=myid password=mypwd"
                    + " host=myhost.com port=22"
                    + " encoding=<ISO-8859-1,UTF-8,...>"
                    + " \"remotefile1=/some/file.png\""
                    + " \"localfile1=file.png\""
                    + " \"remotefile2=/other/file.txt\""
                    + " \"localfile2=file.txt\""

            );
            return;
        }

        // default values
        if (params.get("port") == null)
            params.put("port", "22");
        if (params.get("encoding") == null)
            params.put("encoding", "ISO-8859-1"); //"UTF-8"

        Session session = null;
        try {
            JSch jsch=new JSch();
            session=jsch.getSession(
                    params.get("user"),  // myuserid
                    params.get("host"),  // my.server.com
                    Integer.parseInt(params.get("port")) // 22
            );
            session.setPassword( params.get("password") );
            session.setConfig("StrictHostKeyChecking", "no"); // do not prompt for server signature

            session.connect();

            // this is exec command and string reply encoding
            String encoding = params.get("encoding");

            int fileIdx=0;
            while(true) {
                fileIdx++;

                String remoteFile = params.get("remotefile"+fileIdx);
                String localFile = params.get("localfile"+fileIdx);
                if (remoteFile == null || remoteFile.equals("")
                        || localFile == null || localFile.equals("") )
                    break;

                remoteFile = filenameHack(remoteFile);
                localFile  = filenameHack(localFile);

                try {
                    downloadFile(session, remoteFile, localFile, encoding);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

        } catch(Exception ex) {
            ex.printStackTrace();
        } finally {
            try{ session.disconnect(); } catch(Exception ex){}
        }
    }

    private static void downloadFile(Session session, 
            String remoteFile, String localFile, String encoding) throws Exception {
        // send exec command: scp -p -f "/some/file.png"
        // -p = read file timestamps
        // -f = From remote to local
        String command = String.format("scp -p -f \"%s\"", remoteFile); 
        System.console().printf("send command: %s%n", command);
        Channel channel=session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command.getBytes(encoding));

        // get I/O streams for remote scp
        byte[] buf=new byte[32*1024];
        OutputStream out=channel.getOutputStream();
        InputStream in=channel.getInputStream();

        channel.connect();

        buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'

        // reply: T<mtime> 0 <atime> 0\n
        // times are in seconds, since 1970-01-01 00:00:00 UTC 
        int c=checkAck(in);
        if(c!='T')
            throw new IOException("Invalid timestamp reply from server");

        long tsModified = -1; // millis
        for(int idx=0; ; idx++){
            in.read(buf, idx, 1);
            if(tsModified < 0 && buf[idx]==' ') {
                tsModified = Long.parseLong(new String(buf, 0, idx))*1000;
            } else if(buf[idx]=='\n') {
                break;
            }
        }

        buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'

        // reply: C0644 <binary length> <filename>\n
        // length is given as a text "621873" bytes
        c=checkAck(in);
        if(c!='C')
            throw new IOException("Invalid filename reply from server");

        in.read(buf, 0, 5); // read '0644 ' bytes

        long filesize=-1;
        for(int idx=0; ; idx++){
            in.read(buf, idx, 1);
            if(buf[idx]==' ') {
                filesize = Long.parseLong(new String(buf, 0, idx));
                break;
            }
        }

        // read remote filename
        String origFilename=null;
        for(int idx=0; ; idx++){
            in.read(buf, idx, 1);
            if(buf[idx]=='\n') {
                origFilename=new String(buf, 0, idx, encoding); // UTF-8, ISO-8859-1
                break;
            }
        }

        System.console().printf("size=%d, modified=%d, filename=%s%n"
                , filesize, tsModified, origFilename);

        buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'

        // read binary data, write to local file
        FileOutputStream fos = null;
        try {
            File file = new File(localFile);
            fos = new FileOutputStream(file);
            while(filesize > 0) {
                int read = Math.min(buf.length, (int)filesize);
                read=in.read(buf, 0, read);
                if(read < 0)
                    throw new IOException("Reading data failed");

                fos.write(buf, 0, read);
                filesize -= read;
            }
            fos.close(); // we must close file before updating timestamp
            fos = null;
            if (tsModified > 0)
                file.setLastModified(tsModified);               
        } finally {
            try{ if (fos!=null) fos.close(); } catch(Exception ex){}
        }

        if(checkAck(in) != 0)
            return;

        buf[0]=0; out.write(buf, 0, 1); out.flush(); // send '\0'
        System.out.println("Binary data read");     
    }

    private static int checkAck(InputStream in) throws IOException {
        // b may be 0 for success
        //          1 for error,
        //          2 for fatal error,
        //          -1
        int b=in.read();
        if(b==0) return b;
        else if(b==-1) return b;
        if(b==1 || b==2) {
            StringBuilder sb=new StringBuilder();
            int c;
            do {
                c=in.read();
                sb.append((char)c);
            } while(c!='\n');
            throw new IOException(sb.toString());
        }
        return b;
    }


    /**
     * Parse key=value pairs to hashmap.
     * @param args
     * @return
     */
    private static Map<String,String> parseParams(String[] args) throws Exception {
        Map<String,String> params = new HashMap<String,String>();
        for(String keyval : args) {
            int idx = keyval.indexOf('=');
            params.put(
                    keyval.substring(0, idx),
                    keyval.substring(idx+1)
            );
        }
        return params;
    }

    private static String filenameHack(String filename) {
        // It's difficult reliably pass unicode input parameters 
        // from Java dos command line.
        // This dirty hack is my very own test use case. 
        if (filename.contains("${filename1}"))
            filename = filename.replace("${filename1}", "Korilla ABC ÅÄÖ.txt");
        else if (filename.contains("${filename2}"))
            filename = filename.replace("${filename2}", "test2 ABC ÅÄÖ.txt");           
        return filename;
    }

}

Image size (Python, OpenCV)

Here is a method that returns the image dimensions:

from PIL import Image
import os

def get_image_dimensions(imagefile):
    """
    Helper function that returns the image dimentions

    :param: imagefile str (path to image)
    :return dict (of the form: {width:<int>, height=<int>, size_bytes=<size_bytes>)
    """
    # Inline import for PIL because it is not a common library
    with Image.open(imagefile) as img:
        # Calculate the width and hight of an image
        width, height = img.size

    # calculat ethe size in bytes
    size_bytes = os.path.getsize(imagefile)

    return dict(width=width, height=height, size_bytes=size_bytes)

How to test the `Mosquitto` server?

In separate terminal windows do the following:

  1. Start the broker:

    mosquitto
    
  2. Start the command line subscriber:

    mosquitto_sub -v -t 'test/topic'
    
  3. Publish test message with the command line publisher:

    mosquitto_pub -t 'test/topic' -m 'helloWorld'
    

As well as seeing both the subscriber and publisher connection messages in the broker terminal the following should be printed in the subscriber terminal:

test/topic helloWorld

How to read a string one letter at a time in python

Use 'index'.

def GetMorseCode(letter):
   index = letterList.index(letter)
   code = codeList[index]
   return code

Of course, you'll want to validate your input letter (convert its case as necessary, make sure it's in the list in the first place by checking that index != -1), but that should get you down the path.

Is it possible to get the index you're sorting over in Underscore.js?

If you'd rather transform your array, then the iterator parameter of underscore's map function is also passed the index as a second argument. So:

_.map([1, 4, 2, 66, 444, 9], function(value, index){ return index + ':' + value; });

... returns:

["0:1", "1:4", "2:2", "3:66", "4:444", "5:9"]

How are iloc and loc different?

iloc works based on integer positioning. So no matter what your row labels are, you can always, e.g., get the first row by doing

df.iloc[0]

or the last five rows by doing

df.iloc[-5:]

You can also use it on the columns. This retrieves the 3rd column:

df.iloc[:, 2]    # the : in the first position indicates all rows

You can combine them to get intersections of rows and columns:

df.iloc[:3, :3] # The upper-left 3 X 3 entries (assuming df has 3+ rows and columns)

On the other hand, .loc use named indices. Let's set up a data frame with strings as row and column labels:

df = pd.DataFrame(index=['a', 'b', 'c'], columns=['time', 'date', 'name'])

Then we can get the first row by

df.loc['a']     # equivalent to df.iloc[0]

and the second two rows of the 'date' column by

df.loc['b':, 'date']   # equivalent to df.iloc[1:, 1]

and so on. Now, it's probably worth pointing out that the default row and column indices for a DataFrame are integers from 0 and in this case iloc and loc would work in the same way. This is why your three examples are equivalent. If you had a non-numeric index such as strings or datetimes, df.loc[:5] would raise an error.

Also, you can do column retrieval just by using the data frame's __getitem__:

df['time']    # equivalent to df.loc[:, 'time']

Now suppose you want to mix position and named indexing, that is, indexing using names on rows and positions on columns (to clarify, I mean select from our data frame, rather than creating a data frame with strings in the row index and integers in the column index). This is where .ix comes in:

df.ix[:2, 'time']    # the first two rows of the 'time' column

I think it's also worth mentioning that you can pass boolean vectors to the loc method as well. For example:

 b = [True, False, True]
 df.loc[b] 

Will return the 1st and 3rd rows of df. This is equivalent to df[b] for selection, but it can also be used for assigning via boolean vectors:

df.loc[b, 'name'] = 'Mary', 'John'

How to implode array with key and value without foreach in PHP

I spent measurements (100000 iterations), what fastest way to glue an associative array?

Objective: To obtain a line of 1,000 items, in this format: "key:value,key2:value2"

We have array (for example):

$array = [
    'test0' => 344,
    'test1' => 235,
    'test2' => 876,
    ...
];

Test number one:

Use http_build_query and str_replace:

str_replace('=', ':', http_build_query($array, null, ','));

Average time to implode 1000 elements: 0.00012930955084904

Test number two:

Use array_map and implode:

implode(',', array_map(
        function ($v, $k) {
            return $k.':'.$v;
        },
        $array,
        array_keys($array)
    ));

Average time to implode 1000 elements: 0.0004890081976675

Test number three:

Use array_walk and implode:

array_walk($array,
        function (&$v, $k) {
            $v = $k.':'.$v;
        }
    );
implode(',', $array);

Average time to implode 1000 elements: 0.0003874126245348

Test number four:

Use foreach:

    $str = '';
    foreach($array as $key=>$item) {
        $str .= $key.':'.$item.',';
    }
    rtrim($str, ',');

Average time to implode 1000 elements: 0.00026632803902445

I can conclude that the best way to glue the array - use http_build_query and str_replace

PHP __get and __set magic methods

From the PHP manual:

  • __set() is run when writing data to inaccessible properties.
  • __get() is utilized for reading data from inaccessible properties.

This is only called on reading/writing inaccessible properties. Your property however is public, which means it is accessible. Changing the access modifier to protected solves the issue.

Get list of all tables in Oracle?

select * from dba_tables

gives all the tables of all the users only if the user with which you logged in is having the sysdba privileges.

Can I change the color of Font Awesome's icon color?

Try this:

<i class="icon-cog text-red">
<i class="icon-cog text-blue">
<i class="icon-cog text-yellow">

How to SELECT a dropdown list item by value programmatically

If you know that the dropdownlist contains the value you're looking to select, use:

ddl.SelectedValue = "2";

If you're not sure if the value exists, use (or you'll get a null reference exception):

ListItem selectedListItem = ddl.Items.FindByValue("2");

if (selectedListItem != null)
{
    selectedListItem.Selected = true;
}

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

Facebook Architecture

Well Facebook has undergone MANY many changes and it wasn't originally designed to be efficient. It was designed to do it's job. I have absolutely no idea what the code looks like and you probably won't find much info about it (for obvious security and copyright reasons), but just take a look at the API. Look at how often it changes and how much of it doesn't work properly, anymore, or at all.

I think the biggest ace up their sleeve is the Hiphop. http://developers.facebook.com/blog/post/358 You can use HipHop yourself: https://github.com/facebook/hiphop-php/wiki

But if you ask me it's a very ambitious and probably time wasting task. Hiphop only supports so much, it can't simply convert everything to C++. So what does this tell us? Well, it tells us that Facebook is NOT fully taking advantage of the PHP language. It's not using the latest 5.3 and I'm willing to bet there's still a lot that is PHP 4 compatible. Otherwise, they couldn't use HipHop. HipHop IS A GOOD IDEA and needs to grow and expand, but in it's current state it's not really useful for that many people who are building NEW PHP apps.

There's also PHP to JAVA via things like Resin/Quercus. Again, it doesn't support everything...

Another thing to note is that if you use any non-standard PHP module, you aren't going to be able to convert that code to C++ or Java either. However...Let's take a look at PHP modules. They are ARE compiled in C++. So if you can build PHP modules that do things (like parse XML, etc.) then you are basically (minus some interaction) working at the same speed. Of course you can't just make a PHP module for every possible need and your entire app because you would have to recompile and it would be much more difficult to code, etc.

However...There are some handy PHP modules that can help with speed concerns. Though at the end of the day, we have this awesome thing known as "the cloud" and with it, we can scale our applications (PHP included) so it doesn't matter as much anymore. Hardware is becoming cheaper and cheaper. Amazon just lowered it's prices (again) speaking of.

So as long as you code your PHP app around the idea that it will need to one day scale...Then I think you're fine and I'm not really sure I'd even look at Facebook and what they did because when they did it, it was a completely different world and now trying to hold up that infrastructure and maintain it...Well, you get things like HipHop.

Now how is HipHop going to help you? It won't. It can't. You're starting fresh, you can use PHP 5.3. I'd highly recommend looking into PHP 5.3 frameworks and all the new benefits that PHP 5.3 brings to the table along with the SPL libraries and also think about your database too. You're most likely serving up content from a database, so check out MongoDB and other types of databases that are schema-less and document-oriented. They are much much faster and better for the most "common" type of web site/app.

Look at NEW companies like Foursquare and Smugmug and some other companies that are utilizing NEW technology and HOW they are using it. For as successful as Facebook is, I honestly would not look at them for "how" to build an efficient web site/app. I'm not saying they don't have very (very) talented people that work there that are solving (their) problems creatively...I'm also not saying that Facebook isn't a great idea in general and that it's not successful and that you shouldn't get ideas from it....I'm just saying that if you could view their entire source code, you probably wouldn't benefit from it.

javascript unexpected identifier

Yes, you have a } too many. Anyway, compressing yourself tends to result in errors.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
} // <-- end function?
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

Use Closure Compiler instead.

Programmatically change UITextField Keyboard type

Swift 4

If you are trying to change your keyboard type when a condition is met, follow this. For example: If we want to change the keyboard type from Default to Number Pad when the count of the textfield is 4 or 5, then do this:

textField.addTarget(self, action: #selector(handleTextChange), for: .editingChanged)

@objc func handleTextChange(_ textChange: UITextField) {
 if textField.text?.count == 4 || textField.text?.count == 5 {
   textField.keyboardType = .numberPad
   textField.reloadInputViews() // need to reload the input view for this to work
 } else {
   textField.keyboardType = .default
   textField.reloadInputViews()
 }

enum to string in modern C++11 / C++14 / C++17 and future C++20

#define ENUM_MAKE(TYPE, ...) \
        enum class TYPE {__VA_ARGS__};\
        struct Helper_ ## TYPE { \
            static const String& toName(TYPE type) {\
                int index = static_cast<int>(type);\
                return splitStringVec()[index];}\
            static const TYPE toType(const String& name){\
                static std::unordered_map<String,TYPE> typeNameMap;\
                if( typeNameMap.empty() )\
                {\
                    const StringVector& ssVec = splitStringVec();\
                    for (size_t i = 0; i < ssVec.size(); ++i)\
                        typeNameMap.insert(std::make_pair(ssVec[i], static_cast<TYPE>(i)));\
                }\
                return typeNameMap[name];}\
            static const StringVector& splitStringVec() {\
                static StringVector typeNameVector;\
                if(typeNameVector.empty()) \
                {\
                    typeNameVector = StringUtil::split(#__VA_ARGS__, ",");\
                    for (auto& name : typeNameVector)\
                    {\
                        name.erase(std::remove(name.begin(), name.end(), ' '),name.end()); \
                        name = String(#TYPE) + "::" + name;\
                    }\
                }\
                return typeNameVector;\
            }\
        };


using String = std::string;
using StringVector = std::vector<String>;

   StringVector StringUtil::split( const String& str, const String& delims, unsigned int maxSplits, bool preserveDelims)
    {
        StringVector ret;
        // Pre-allocate some space for performance
        ret.reserve(maxSplits ? maxSplits+1 : 10);    // 10 is guessed capacity for most case

        unsigned int numSplits = 0;

        // Use STL methods 
        size_t start, pos;
        start = 0;
        do 
        {
            pos = str.find_first_of(delims, start);
            if (pos == start)
            {
                // Do nothing
                start = pos + 1;
            }
            else if (pos == String::npos || (maxSplits && numSplits == maxSplits))
            {
                // Copy the rest of the string
                ret.push_back( str.substr(start) );
                break;
            }
            else
            {
                // Copy up to delimiter
                ret.push_back( str.substr(start, pos - start) );

                if(preserveDelims)
                {
                    // Sometimes there could be more than one delimiter in a row.
                    // Loop until we don't find any more delims
                    size_t delimStart = pos, delimPos;
                    delimPos = str.find_first_not_of(delims, delimStart);
                    if (delimPos == String::npos)
                    {
                        // Copy the rest of the string
                        ret.push_back( str.substr(delimStart) );
                    }
                    else
                    {
                        ret.push_back( str.substr(delimStart, delimPos - delimStart) );
                    }
                }

                start = pos + 1;
            }
            // parse up to next real data
            start = str.find_first_not_of(delims, start);
            ++numSplits;

        } while (pos != String::npos);



        return ret;
    }

example

ENUM_MAKE(MY_TEST, MY_1, MY_2, MY_3)


    MY_TEST s1 = MY_TEST::MY_1;
    MY_TEST s2 = MY_TEST::MY_2;
    MY_TEST s3 = MY_TEST::MY_3;

    String z1 = Helper_MY_TEST::toName(s1);
    String z2 = Helper_MY_TEST::toName(s2);
    String z3 = Helper_MY_TEST::toName(s3);

    MY_TEST q1 = Helper_MY_TEST::toType(z1);
    MY_TEST q2 = Helper_MY_TEST::toType(z2);
    MY_TEST q3 = Helper_MY_TEST::toType(z3);

automatically ENUM_MAKE macro generate 'enum class' and helper class with 'enum reflection function'.

In order to reduce mistakes, at once Everything is defined with only one ENUM_MAKE.

The advantage of this code is automatically created for reflection and a close look at macro code ,easy-to-understand code. 'enum to string' , 'string to enum' performance both is algorithm O(1).

Disadvantages is when first use , helper class for enum relection 's string vector and map is initialized. but If you want you'll also be pre-initialized. –

How to create a generic array?

Here is the implementation of LinkedList<T>#toArray(T[]):

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(
                            a.getClass().getComponentType(), size);
    int i = 0;
    Object[] result = a;
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;

    if (a.length > size)
        a[size] = null;

    return a;
}

In short, you could only create generic arrays through Array.newInstance(Class, int) where int is the size of the array.

async/await - when to return a Task vs void?

The problem with calling async void is that

you don’t even get the task back. You have no way of knowing when the function’s task has completed. —— Crash course in async and await | The Old New Thing

Here are the three ways to call an async function:

async Task<T> SomethingAsync() { ... return t; }
async Task SomethingAsync() { ... }
async void SomethingAsync() { ... }

In all the cases, the function is transformed into a chain of tasks. The difference is what the function returns.

In the first case, the function returns a task that eventually produces the t.

In the second case, the function returns a task which has no product, but you can still await on it to know when it has run to completion.

The third case is the nasty one. The third case is like the second case, except that you don't even get the task back. You have no way of knowing when the function's task has completed.

The async void case is a "fire and forget": You start the task chain, but you don't care about when it's finished. When the function returns, all you know is that everything up to the first await has executed. Everything after the first await will run at some unspecified point in the future that you have no access to.

How to create JSON object Node.js

The other answers are helpful, but the JSON in your question isn't valid. I have formatted it to make it clearer below, note the missing single quote on line 24.

  1 {
  2     'Orientation Sensor':
  3     [
  4         {
  5             sampleTime: '1450632410296',
  6             data: '76.36731:3.4651554:0.5665419'
  7         },
  8         {
  9             sampleTime: '1450632410296',
 10             data: '78.15431:0.5247617:-0.20050584'
 11         }
 12     ],
 13     'Screen Orientation Sensor':
 14     [
 15         {
 16             sampleTime: '1450632410296',
 17             data: '255.0:-1.0:0.0'
 18         }
 19     ],
 20     'MPU6500 Gyroscope sensor UnCalibrated':
 21     [
 22         {
 23             sampleTime: '1450632410296',
 24             data: '-0.05006743:-0.013848438:-0.0063915867
 25         },
 26         {
 27             sampleTime: '1450632410296',
 28             data: '-0.051132694:-0.0127831735:-0.003325345'
 29         }
 30     ]
 31 }

There are a lot of great articles on how to manipulate objects in Javascript (whether using Node JS or a browser). I suggest here is a good place to start: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Rails: Default sort order for a rails model?

A quick update to Michael's excellent answer above.

For Rails 4.0+ you need to put your sort in a block like this:

class Book < ActiveRecord::Base
  default_scope { order('created_at DESC') }
end

Notice that the order statement is placed in a block denoted by the curly braces.

They changed it because it was too easy to pass in something dynamic (like the current time). This removes the problem because the block is evaluated at runtime. If you don't use a block you'll get this error:

Support for calling #default_scope without a block is removed. For example instead of default_scope where(color: 'red'), please use default_scope { where(color: 'red') }. (Alternatively you can just redefine self.default_scope.)

As @Dan mentions in his comment below, you can do a more rubyish syntax like this:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

or with multiple columns:

class Book < ActiveRecord::Base
  default_scope { order({begin_date: :desc}, :name) }
end

Thanks @Dan!

What's the difference between using "let" and "var"?

Function VS block scope:

The main difference between var and let is that variables declared with var are function scoped. Whereas functions declared with let are block scoped. For example:

function testVar () {
  if(true) {
    var foo = 'foo';
  }

  console.log(foo);
}

testVar();  
// logs 'foo'


function testLet () {
  if(true) {
    let bar = 'bar';
  }

  console.log(bar);
}

testLet(); 
// reference error
// bar is scoped to the block of the if statement 

variables with var:

When the first function testVar gets called the variable foo, declared with var, is still accessible outside the if statement. This variable foo would be available everywhere within the scope of the testVar function.

variables with let:

When the second function testLet gets called the variable bar, declared with let, is only accessible inside the if statement. Because variables declared with let are block scoped (where a block is the code between curly brackets e.g if{} , for{}, function{}).

let variables don't get hoisted:

Another difference between var and let is variables with declared with let don't get hoisted. An example is the best way to illustrate this behavior:

variables with let don't get hoisted:

console.log(letVar);

let letVar = 10;
// referenceError, the variable doesn't get hoisted

variables with var do get hoisted:

console.log(varVar);

var varVar = 10;
// logs undefined, the variable gets hoisted

Global let doesn't get attached to window:

A variable declared with let in the global scope (which is code that is not in a function) doesn't get added as a property on the global window object. For example (this code is in global scope):

var bar = 5;
let foo  = 10;

console.log(bar); // logs 5
console.log(foo); // logs 10

console.log(window.bar);  
// logs 5, variable added to window object

console.log(window.foo);
// logs undefined, variable not added to window object


When should let be used over var?

Use let over var whenever you can because it is simply scoped more specific. This reduces potential naming conflicts which can occur when dealing with a large number of variables. var can be used when you want a global variable explicitly to be on the window object (always consider carefully if this is really necessary).

Click outside menu to close in jquery

Use the ':visible' selector. Where .menuitem is the to-hide element(s) ...

$('body').click(function(){
  $('.menuitem:visible').hide('fast');
});

Or if you already have the .menuitem element(s) in a var ...

var menitems = $('.menuitem');
$('body').click(function(){
  menuitems.filter(':visible').hide('fast');
});

Measuring elapsed time with the Time module

time.time() will do the job.

import time

start = time.time()
# run your code
end = time.time()

elapsed = end - start

You may want to look at this question, but I don't think it will be necessary.

How do I alias commands in git?

Just to get the aliases even shorter than the standard git config way mentioned in other answers, I created an npm package mingit (npm install -g mingit) so that most commands would become 2 characters instead of 2 words. Here's the examples:

g a .                   // git add .
g b other-branch        // git branch other-branch
g c "made some changes" // git commit -m "made some changes"
g co master             // git checkout master
g d                     // git diff
g f                     // git fetch
g i                     // git init 
g m hotfix              // git merge hotfix
g pll                   // git pull
g psh                   // git push
g s                     // git status

and other commands would be similarly short. This also keeps bash completions. The package adds a bash function to your dotfiles, works on osx, linux, and windows. Also, unlike the other aliases, it aliases git -> g as well as the second parameter.

How do I create a copy of an object in PHP?

In PHP 5+ objects are passed by reference. In PHP 4 they are passed by value (that's why it had runtime pass by reference, which became deprecated).

You can use the 'clone' operator in PHP5 to copy objects:

$objectB = clone $objectA;

Also, it's just objects that are passed by reference, not everything as you've said in your question...

Subtract a value from every number in a list in Python?

To clarify an already posted solution due to questions in the comments

import numpy

array = numpy.array([49, 51, 53, 56])
array = array - 13

will output:

array([36, 38, 40, 43])

How to insert 1000 rows at a time

By the way why don't you use XML data insertion through Stored Procedure?

Here is the link to do that... Inserting Bulk Data through XML-Stored Procedure