Programs & Examples On #Concordion

Concordion is an open source tool for writing automated acceptance tests in Java

ImportError: Cannot import name X

In my case, I was working in a Jupyter notebook and this was happening due the import already being cached from when I had defined the class/function inside my working file.

I restarted my Jupyter kernel and the error disappeared.

How to add an image to a JPanel?

This answer is a complement to @shawalli's answer...

I wanted to reference an image within my jar too, but instead of having a BufferedImage, I simple did this:

 JPanel jPanel = new JPanel();      
 jPanel.add(new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resource/images/polygon.jpg"))));

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

The error is because there is some non-ascii character in the dictionary and it can't be encoded/decoded. One simple way to avoid this error is to encode such strings with encode() function as follows (if a is the string with non-ascii character):

a.encode('utf-8').strip()

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

This also need.

<?php
header("Access-Control-Allow-Origin: *");

Return a string method in C#

You forgot the () at the end. It is not a variable, but a function and when there are not parameters, you still need the () at the end.

For future coding practices, I would highly recommend reforming the code a little bit as this can become frustrating to read:

 public string LastName
 { get { return lastName; } set { lastName = value; } }

If there is any kind of processing which happens in here (thankfully doesn't happen here), it will become very confusing. If you're going to pass your code onto someone else, I would recommend:

public string LastName
{
  get
  {
     return lastName;
  }
  set
  {
     lastName = value;
  }
}

It's a lot longer, but it's much easier to read when glancing at a huge section of code.

[] and {} vs list() and dict(), which is better?

In the case of difference between [] and list(), there is a pitfall that I haven't seen anyone else point out. If you use a dictionary as a member of the list, the two will give entirely different results:

In [1]: foo_dict = {"1":"foo", "2":"bar"}

In [2]: [foo_dict]
Out [2]: [{'1': 'foo', '2': 'bar'}]

In [3]: list(foo_dict)
Out [3]: ['1', '2'] 

Could not load file or assembly 'Microsoft.Web.Infrastructure,

Experienced this issue on new Windows 10 machine on VS2015 with an existing project. Package Manager 3.4.4. Restore packages enabled.

The restore doesn't seem to work completely. Had to run the following on the Package Manager Command line

Update-Package -ProjectName "YourProjectName" -Id Microsoft.Web.Infrastructure -Reinstall

This made the following changes to my solution file which the restore did NOT do.

<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
  <Private>True</Private>
</Reference>

Just adding the above elements to the ItemGroup section in you solution file will ALSO solve the issue provided that ..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll exist.

Easier to just do the -Reinstall but good to understand what it does differently to the package restore.

Bootstrap 3 Horizontal Divider (not in a dropdown)

Currently it only works for the .dropdown-menu:

.dropdown-menu .divider {
  height: 1px;
  margin: 9px 0;
  overflow: hidden;
  background-color: #e5e5e5;
}

If you want it for other use, in your own css, following the bootstrap.css create another one:

.divider {
  height: 1px;
  width:100%;
  display:block; /* for use on default inline elements like span */
  margin: 9px 0;
  overflow: hidden;
  background-color: #e5e5e5;
}

Cannot find R.layout.activity_main

Happened once. Don't know the reason.

Build> Clean Project removed the error for me.

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

Remove the :iml file found in java and test folders inside the project and invalidate and restart .

It will ask can I remove the projects . Put Yes. The error will goes off.

Passing in class names to react components

pill ${this.props.styleName} will get "pill undefined" when you don't set the props

I prefer

className={ "pill " + ( this.props.styleName || "") }

or

className={ "pill " + ( this.props.styleName ? this.props.styleName : "") }

How to ping multiple servers and return IP address and Hostnames using batch script?

I worked on the code given earlier by Eitan-T and reworked to output to CSV file. Found the results in earlier code weren't always giving correct values as well so i've improved it.

testservers.txt

SOMESERVER
DUDSERVER

results.csv

HOSTNAME    LONGNAME                    IPADDRESS   STATE 
SOMESERVER  SOMESERVER.DOMAIN.SUF       10.1.1.1    UP 
DUDSERVER   UNRESOLVED                  UNRESOLVED  DOWN 

pingtest.bat

 @echo off
    setlocal enabledelayedexpansion
    set OUTPUT_FILE=result.csv

    >nul copy nul %OUTPUT_FILE%
    echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
    for /f %%i in (testservers.txt) do (
        set SERVER_ADDRESS_I=UNRESOLVED
        set SERVER_ADDRESS_L=UNRESOLVED
        for /f "tokens=1,2,3" %%x in ('ping -n 1 %%i ^&^& echo SERVER_IS_UP') do (
        if %%x==Pinging set SERVER_ADDRESS_L=%%y
        if %%x==Pinging set SERVER_ADDRESS_I=%%z
            if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
        )
        echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
        echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
    )

Create an array or List of all dates between two dates

LINQ:

Enumerable.Range(0, 1 + end.Subtract(start).Days)
          .Select(offset => start.AddDays(offset))
          .ToArray(); 

For loop:

var dates = new List<DateTime>();

for (var dt = start; dt <= end; dt = dt.AddDays(1))
{
   dates.Add(dt);
}

EDIT: As for padding values with defaults in a time-series, you could enumerate all the dates in the full date-range, and pick the value for a date directly from the series if it exists, or the default otherwise. For example:

var paddedSeries = fullDates.ToDictionary(date => date, date => timeSeries.ContainsDate(date) 
                                               ? timeSeries[date] : defaultValue);

Xcode 4: create IPA file instead of .xcarchive

I went threw the same problem. None of the answers above worked for me, but i ended finding the solution on my own. The ipa file wasn't created because there was library files (libXXX.a) in Target-> Build Phases -> Copy Bundle with resources

Hope it will help someone :)

Is there a pretty print for PHP?

Both print_r() and var_dump() will output visual representations of objects within PHP.

$arr = array('one' => 1);
print_r($arr);
var_dump($arr);

Python: Differentiating between row and column vectors

row vectors are (1,0) tensor, vectors are (0, 1) tensor. if using v = np.array([[1,2,3]]), v become (0,2) tensor. Sorry, i am confused.

MySQL query to select events between start/end date

You need the events that start and end within the scope. But that's not all: you also want the events that start within the scope and the events that end within the scope. But then you're still not there because you also want the events that start before the scope and end after the scope.

Simplified:

  1. events with a start date in the scope
  2. events with an end date in the scope
  3. events with the scope startdate between the startdate and enddate

Because point 2 results in records that also meet the query in point 3 we will only need points 1 and 3

So the SQL becomes:

SELECT * FROM events 
WHERE start BETWEEN '2014-09-01' AND '2014-10-13' 
OR '2014-09-01' BETWEEN start AND end

Difference between & and && in Java?

'&' performs both tests, while '&&' only performs the 2nd test if the first is also true. This is known as shortcircuiting and may be considered as an optimization. This is especially useful in guarding against nullness(NullPointerException).

if( x != null && x.equals("*BINGO*") {
  then do something with x...
}

How to sort by column in descending order in Spark SQL?

import org.apache.spark.sql.functions.desc

df.orderBy(desc("columnname1"),desc("columnname2"),asc("columnname3"))

Is there a way to programmatically minimize a window

FormName.WindowState = FormWindowState.Minimized;

How to remove trailing whitespace in code, using another script?

fileinput seems to be for multiple input streams. This is what I would do:

with open("test.txt") as file:
    for line in file:
        line = line.rstrip()
        if line:
            print(line)

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

Here is my problem and solution:

I removed two files from the source code using source tree(Version controller). After applying the diff, that contains the two classes I removed, Xcode didn't add it automatically. So I got linker error.

I manually added the files, by right click on group name and select "Add files to ". Now my error got resolved.

If anyone faced the linker error regarding class file, then try to add it manually.

How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

Paging with LINQ for objects

_x000D_
_x000D_
var results = (medicineInfo.OrderBy(x=>x.id)_x000D_
                       .Skip((pages -1) * 2)_x000D_
                       .Take(2));
_x000D_
_x000D_
_x000D_

How to "EXPIRE" the "HSET" child key in redis?

You can expire Redis hashes in ease, Eg using python

import redis
conn = redis.Redis('localhost')
conn.hmset("hashed_user", {'name': 'robert', 'age': 32})
conn.expire("hashed_user", 10)

This will expire all child keys in hash hashed_user after 10 seconds

same from redis-cli,

127.0.0.1:6379> HMSET testt username wlc password P1pp0 age 34
OK
127.0.0.1:6379> hgetall testt
1) "username"
2) "wlc"
3) "password"
4) "P1pp0"
5) "age"
6) "34"
127.0.0.1:6379> expire testt 10
(integer) 1
127.0.0.1:6379> hgetall testt
1) "username"
2) "wlc"
3) "password"
4) "P1pp0"
5) "age"
6) "34"

after 10 seconds

127.0.0.1:6379> hgetall testt
(empty list or set)

Programmatically add custom event in the iPhone Calendar

Calendar access is being added in iPhone OS 4.0:

Calendar Access
Apps can now create and edit events directly in the Calendar app with Event Kit.
Create recurring events, set up start and end times and assign them to any calendar on the device.

Javascript require() function giving ReferenceError: require is not defined

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

IE 6+ .......... compatible ?
Firefox 2+ ..... compatible ?
Safari 3.2+ .... compatible ?
Chrome 3+ ...... compatible ?
Opera 10+ ...... compatible ?

http://requirejs.org/docs/download.html

Add this to your project: https://requirejs.org/docs/release/2.3.5/minified/require.js

and take a look at this http://requirejs.org/docs/api.html

Collection was modified; enumeration operation may not execute in ArrayList

You are removing the item during a foreach, yes? Simply, you can't. There are a few common options here:

  • use List<T> and RemoveAll with a predicate
  • iterate backwards by index, removing matching items

    for(int i = list.Count - 1; i >= 0; i--) {
        if({some test}) list.RemoveAt(i);
    }
    
  • use foreach, and put matching items into a second list; now enumerate the second list and remove those items from the first (if you see what I mean)

Is there a destructor for Java?

Use of finalize() methods should be avoided. They are not a reliable mechanism for resource clean up and it is possible to cause problems in the garbage collector by abusing them.

If you require a deallocation call in your object, say to release resources, use an explicit method call. This convention can be seen in existing APIs (e.g. Closeable, Graphics.dispose(), Widget.dispose()) and is usually called via try/finally.

Resource r = new Resource();
try {
    //work
} finally {
    r.dispose();
}

Attempts to use a disposed object should throw a runtime exception (see IllegalStateException).


EDIT:

I was thinking, if all I did was just to dereference the data and wait for the garbage collector to collect them, wouldn't there be a memory leak if my user repeatedly entered data and pressed the reset button?

Generally, all you need to do is dereference the objects - at least, this is the way it is supposed to work. If you are worried about garbage collection, check out Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning (or the equivalent document for your JVM version).

SQL DELETE with INNER JOIN

if the database is InnoDB you dont need to do joins in deletion. only

DELETE FROM spawnlist WHERE spawnlist.type = "monster";

can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.

CREATE TABLE IF NOT EXIST spawnlist (
  npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY

)ENGINE=InnoDB;

CREATE TABLE IF NOT EXIST npc (
  idTemplate VARCHAR(20) NOT NULL,

  FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE

)ENGINE=InnoDB;

if you uses MyISAM you can delete records joining like this

DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';

in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.

Jquery asp.net Button Click Event via ajax

In the client side handle the click event of the button, use the ClientID property to get he id of the button:

$(document).ready(function() {
$("#<%=myButton.ClientID %>,#<%=muSecondButton.ClientID%>").click(

    function() {
     $.get("/myPage.aspx",{id:$(this).attr('id')},function(data) {
       // do something with the data
     return false;
     }
    });
 });

In your page on the server:

protected void Page_Load(object sender,EventArgs e) {
 // check if it is an ajax request
 if (Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
  if (Request.QueryString["id"]==myButton.ClientID) {
    // call the click event handler of the myButton here
    Response.End();
  }
  if (Request.QueryString["id"]==mySecondButton.ClientID) {
    // call the click event handler of the mySecondButton here
    Response.End();
  }
 }
}

Access index of the parent ng-repeat from child ng-repeat

You can simply use use $parent.$index .where parent will represent object of parent repeating object .

How to compare values which may both be null in T-SQL

You could use SET ANSI_NULLS in order to specify the behavior of the Equals (=) and Not Equal To (<>) comparison operators when they are used with null values.

C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

Trying with a different version of gcc worked for me - gcc 4.9 in my case.

How do I get the collection of Model State Errors in ASP.NET MVC?

Got this from BrockAllen's answer that worked for me, it displays the keys that have errors:

    var errors =
    from item in ModelState
    where item.Value.Errors.Count > 0
    select item.Key;
    var keys = errors.ToArray();

Source: https://forums.asp.net/t/1805163.aspx?Get+the+Key+value+of+the+Model+error

How to run a class from Jar which is not the Main-Class in its Manifest file

First of all jar creates a jar, and does not run it. Try java -jar instead.

Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2) and as file (com/mycomp/myproj/dir2/MainClass2.class)?

Edit:

It seems as if java -jar requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ... instead. -cp sets the jar on the classpath and enables java to look up the main class there.

Solving a "communications link failure" with JDBC and MySQL

In phpstorm + vagrant autoReconnect driver option helped.

How to stop the Timer in android?

I had a similar problem and it was caused by the placement of the Timer initialisation.

It was placed in a method that was invoked oftener.

Try this:

Timer waitTimer;

  void exampleMethod() {

   if (waitTimer == null ) {
    //initialize your Timer here
    ...
   }

The "cancel()" method only canceled the latest Timer. The older ones were ignored an didn't stop running.

React: how to update state.item[1] in state using setState?

@JonnyBuchanan's answer works perfectly, but for only array state variable. In case the state variable is just a single dictionary, follow this:

inputChange = input => e => {
    this.setState({
        item: update(this.state.item, {[input]: {$set: e.target.value}})
    })
}

You can replace [input] by the field name of your dictionary and e.target.value by its value. This code performs the update job on input change event of my form.

Twitter Bootstrap Datepicker within modal window

for me it only worked with !important in css

.datepicker {z-index: 1151 !important;}

How can I get the status code from an http error in Axios?

You can put the error into an object and log the object, like this:

axios.get('foo.com')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });

Hope this help someone out there.

Align text to the bottom of a div

Flex Solution

It is perfectly fine if you want to go with the display: table-cell solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;. flex is something which has a decent support.

_x000D_
_x000D_
.wrap {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border: 1px solid #aaa;_x000D_
  margin: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
  align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <span>Align me to the bottom</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In the above example, we first set the parent element to display: flex; and later, we use align-self to flex-end. This helps you push the item to the end of the flex parent.


Old Solution (Valid if you are not willing to use flex)

If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell; with vertical-align: bottom; is enough

_x000D_
_x000D_
div {_x000D_
  display: table-cell;_x000D_
  vertical-align: bottom;_x000D_
  border: 1px solid #f00;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
_x000D_
_x000D_

(Or JSFiddle)

Elevating process privilege programmatically?

[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]

This will do it without UAC - no need to start a new process. If the running user is member of Admin group as for my case.

Update multiple columns in SQL

here is one that works:

UPDATE  `table_1`
INNER JOIN 
 `table_2` SET  col1= value, col2= val,col3= val,col4= val;

value is the column from table_2

How to reference a file for variables using Bash?

even shorter using the dot:

#!/bin/bash
. CONFIG_FILE

sudo -u wwwrun svn up /srv/www/htdocs/$production
sudo -u wwwrun svn up /srv/www/htdocs/$playschool

What exactly are DLL files, and how do they work?

DLLs (dynamic link libraries) and SLs (shared libraries, equivalent under UNIX) are just libraries of executable code which can be dynamically linked into an executable at load time.

Static libraries are inserted into an executable at compile time and are fixed from that point. They increase the size of the executable and cannot be shared.

Dynamic libraries have the following advantages:

1/ They are loaded at run time rather than compile time so they can be updated independently of the executable (all those fancy windows and dialog boxes you see in Windows come from DLLs so the look-and-feel of your application can change without you having to rewrite it).

2/ Because they're independent, the code can be shared across multiple executables - this saves memory since, if you're running 100 apps with a single DLL, there may only be one copy of the DLL in memory.

Their main disadvantage is advantage #1 - having DLLs change independent your application may cause your application to stop working or start behaving in a bizarre manner. DLL versioning tend not to be managed very well under Windows and this leads to the quaintly-named "DLL Hell".

How to print GETDATE() in SQL Server with milliseconds in time?

Try Following

DECLARE @formatted_datetime char(23)
SET @formatted_datetime = CONVERT(char(23), GETDATE(), 121)
print @formatted_datetime

MySQL export into outfile : CSV escaping chars

I think your statement should look like:

SELECT id, 
   client,
   project,
   task,
   description, 
   time,
   date  
  INTO OUTFILE '/path/to/file.csv'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM ts

Mainly without the FIELDS ESCAPED BY '""' option, OPTIONALLY ENCLOSED BY '"' will do the trick for description fields etc and your numbers will be treated as numbers in Excel (not strings comprising of numerics)

Also try calling:

SET NAMES utf8;

before your outfile select, that might help getting the character encodings inline (all UTF8)

Let us know how you get on.

How can you customize the numbers in an ordered list?

Nope... just use a DL:

dl { overflow:hidden; }
dt {
 float:left;
 clear: left;
 width:4em; /* adjust the width; make sure the total of both is 100% */
 text-align: right
}
dd {
 float:left;
 width:50%; /* adjust the width; make sure the total of both is 100% */
 margin: 0 0.5em;
}

Arraylist swap elements

In Java, you cannot set a value in ArrayList by assigning to it, there's a set() method to call:

String a = words.get(0);
words.set(0, words.get(words.size() - 1));
words.set(words.size() - 1, a)

Resource leak: 'in' is never closed

If you are using JDK7 or 8, you can use try-catch with resources.This will automatically close the scanner.

try ( Scanner scanner = new Scanner(System.in); )
  {
    System.out.println("Enter the width of the Rectangle: ");
    width = scanner.nextDouble();
    System.out.println("Enter the height of the Rectangle: ");
    height = scanner.nextDouble();
  }
catch(Exception ex)
{
    //exception handling...do something (e.g., print the error message)
    ex.printStackTrace();
}

Tools to generate database tables diagram with Postgresql?

Just found http://www.sqlpower.ca/page/architect through the Postgres Community Guide mentioned by Frank Heikens. It can easily generate a diagram, and then lets you adjust the connectors!

Tomcat 7: How to set initial heap size correctly?

You must not use =. Simply use this:

export CATALINA_OPTS="-Xms512M -Xmx1024M"

MySQL with Node.js

You can skip the ORM, builders, etc. and simplify your DB/SQL management using sqler and sqler-mdb.

-- create this file at: db/mdb/setup/create.database.sql
CREATE DATABASE IF NOT EXISTS sqlermysql
const conf = {
  "univ": {
    "db": {
      "mdb": {
        "host": "localhost",
        "username":"admin",
        "password": "mysqlpassword"
      }
    }
  },
  "db": {
    "dialects": {
      "mdb": "sqler-mdb"
    },
    "connections": [
      {
        "id": "mdb",
        "name": "mdb",
        "dir": "db/mdb",
        "service": "MySQL",
        "dialect": "mdb",
        "pool": {},
        "driverOptions": {
          "connection": {
            "multipleStatements": true
          }
        }
      }
    ]
  }
};

// create/initialize manager
const manager = new Manager(conf);
await manager.init();

// .sql file path is path to db function
const result = await manager.db.mdb.setup.create.database();

console.log('Result:', result);

// after we're done using the manager we should close it
process.on('SIGINT', async function sigintDB() {
  await manager.close();
  console.log('Manager has been closed');
});

Link to download apache http server for 64bit windows.

Check out the link given it has Apache HTTP Server 2.4.2 x86 and x64 Windows Installers http://www.anindya.com/apache-http-server-2-4-2-x86-and-x64-windows-installers/

laravel throwing MethodNotAllowedHttpException

I encountered this problem as well and the other answers here were helpful, but I am using a Route::resource which takes care of GET, POST, and other requests.

In my case I left my route as is:

Route::resource('file', 'FilesController');

And simply modified my form to submit to the store function in my FilesController

{{ Form::open(array('route' => 'file.store')) }}

This fixed the issue, and I thought it was worth pointing out as a separate answer since various other answers suggest adding a new POST route. This is an option but it's not necessary.

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

How to split data into trainset and testset randomly?

To answer @desmond.carros question, I modified the best answer as follows,

 import random
 file=open("datafile.txt","r")
 data=list()
 for line in file:
    data.append(line.split(#your preferred delimiter))
 file.close()
 random.shuffle(data)
 train_data = data[:int((len(data)+1)*.80)] #Remaining 80% to training set
 test_data = data[int((len(data)+1)*.80):] #Splits 20% data to test set

The code splits the entire dataset to 80% train and 20% test data

Redirect to a page/URL after alert button is pressed

Working example in php.
First Alert then Redirect works....
Enjoy...

echo "<script>";
echo " alert('Import has successfully Done.');      
        window.location.href='".site_url('home')."';
      </script>";

Convert to/from DateTime and Time in Ruby

You can use to_date, e.g.

> Event.last.starts_at
=> Wed, 13 Jan 2021 16:49:36.292979000 CET +01:00
> Event.last.starts_at.to_date
=> Wed, 13 Jan 2021

How can I catch a ctrl-c event?

Yeah, this is a platform dependent question.

If you are writing a console program on POSIX, use the signal API (#include <signal.h>).

In a WIN32 GUI application you should handle the WM_KEYDOWN message.

Browser: Identifier X has already been declared

Remember that window is the global namespace. These two lines attempt to declare the same variable:

window.APP = { ... }
const APP = window.APP

The second definition is not allowed in strict mode (enabled with 'use strict' at the top of your file).

To fix the problem, simply remove the const APP = declaration. The variable will still be accessible, as it belongs to the global namespace.

How do I hide the PHP explode delimiter from submitted form results?

<select name="FakeName" id="Fake-ID" aria-required="true" required>  <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options);  foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>";  } ?> </select> 

jQuery call function after load

Crude, but does what you want, breaks the execution scope:

$(function(){
setTimeout(function(){
//Code to call
},1);
});

How to access the last value in a vector?

Package data.table includes last function

library(data.table)
last(c(1:10))
# [1] 10

error: RPC failed; curl transfer closed with outstanding read data remaining

For me, the issue was that the connection closes before the whole clone complete. I used ethernet instead of wifi connection. Then it solves for me

Where does Android emulator store SQLite database?

An update mentioned in the comments below:

You don't need to be on the DDMS perspective anymore, just open the File Explorer from Eclipse Window > Show View > Other... It seems the app doesn't need to be running even, I can browse around in different apps file contents. I'm running ADB version 1.0.29


Or, you can try the old approach:

Open the DDMS perspective on your Eclipse IDE

(Window > Open Perspective > Other > DDMS)

and the most important:

YOUR APPLICATION MUST BE RUNNING SO YOU CAN SEE THE HIERARCHY OF FOLDERS AND FILES.

Then in the File Explorer Tab you will follow the path :

data > data > your-package-name > databases > your-database-file.

Then select the file, click on the disket icon in the right corner of the screen to download the .db file. If you want to upload a database file to the emulator you can click on the phone icon(beside disket icon) and choose the file to upload.

If you want to see the content of the .db file, I advise you to use SQLite Database Browser, which you can download here.

PS: If you want to see the database from a real device, you must root your phone.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

its happen when you try to delete the same object and then again update the same object use this after delete

session.clear();

How to tell if node.js is installed or not

Ctrl + R - to open the command line and then writes:

node -v

Remove a marker from a GoogleMap

use the following code:

 mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
       @Override
       public boolean onMarkerClick(Marker marker) {

           marker.remove();
           return true;
       }
   });

once you click on "a marker", you can remove it.

Fixed point vs Floating point number

A fixed point number just means that there are a fixed number of digits after the decimal point. A floating point number allows for a varying number of digits after the decimal point.

For example, if you have a way of storing numbers that requires exactly four digits after the decimal point, then it is fixed point. Without that restriction it is floating point.

Often, when fixed point is used, the programmer actually uses an integer and then makes the assumption that some of the digits are beyond the decimal point. For example, I might want to keep two digits of precision, so a value of 100 means actually means 1.00, 101 means 1.01, 12345 means 123.45, etc.

Floating point numbers are more general purpose because they can represent very small or very large numbers in the same way, but there is a small penalty in having to have extra storage for where the decimal place goes.

Using request.setAttribute in a JSP page

You can do it using pageContext attributes, though:

In the JSP:

<form action="Enter.do">
    <button type="SUBMIT" id="btnSubmit" name="btnSubmit">SUBMIT</button>
</form>
<% String s="opportunity";
pageContext.setAttribute("opp", s, PageContext.APPLICATION_SCOPE); %>

In the Servlet (linked to the "Enter.do" url-pattern):

String s=(String) request.getServletContext().getAttribute("opp");

There are other scopes besides APPLICATION_SCOPE like SESSION_SCOPE. APPLICATION_SCOPE is used for ServletContext attributes.

Can we overload the main method in Java?

Yes, main method can be overloaded. Overloaded main method has to be called from inside the "public static void main(String args[])" as this is the entry point when the class is launched by the JVM. Also overloaded main method can have any qualifier as a normal method have.

CSS hover vs. JavaScript mouseover

The problem with :hover is that IE6 only supports it on links. I use jQuery for this kind of thing these days:

$("div input").hover(function() {
  $(this).addClass("blue");
}, function() {
  $(this).removeClass("blue");
});

Makes things a lot easier. That'll work in IE6, FF, Chrome and Safari.

Flutter: how to make a TextField with HintText but no Underline?

I found no other answer gives a border radius, you can simply do it like this, no nested Container

  TextField(
    decoration: InputDecoration(
      border: OutlineInputBorder(
        borderSide: BorderSide.none,
        borderRadius: BorderRadius.circular(20),
      ),
    ),
  );

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

lock_guard and unique_lock are pretty much the same thing; lock_guard is a restricted version with a limited interface.

A lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.

So you always use lock_guard, unless you need the capabilities of unique_lock. A condition_variable needs a unique_lock.

Sorting multiple keys with Unix sort

Here is one to sort various columns in a csv file by numeric and dictionary order, columns 5 and after as dictionary order

~/test>sort -t, -k1,1n -k2,2n -k3,3d -k4,4n -k5d  sort.csv
1,10,b,22,Ga
2,2,b,20,F
2,2,b,22,Ga
2,2,c,19,Ga
2,2,c,19,Gb,hi
2,2,c,19,Gb,hj
2,3,a,9,C

~/test>cat sort.csv
2,3,a,9,C
2,2,b,20,F
2,2,c,19,Gb,hj
2,2,c,19,Gb,hi
2,2,c,19,Ga
2,2,b,22,Ga
1,10,b,22,Ga

Note the -k1,1n means numeric starting at column 1 and ending at column 1. If I had done below, it would have concatenated column 1 and 2 making 1,10 sorted as 110

~/test>sort -t, -k1,2n -k3,3 -k4,4n -k5d  sort.csv
2,2,b,20,F
2,2,b,22,Ga
2,2,c,19,Ga
2,2,c,19,Gb,hi
2,2,c,19,Gb,hj
2,3,a,9,C
1,10,b,22,Ga

C++ Loop through Map

Try the following

for ( const auto &p : table )
{
   std::cout << p.first << '\t' << p.second << std::endl;
} 

The same can be written using an ordinary for loop

for ( auto it = table.begin(); it != table.end(); ++it  )
{
   std::cout << it->first << '\t' << it->second << std::endl;
} 

Take into account that value_type for std::map is defined the following way

typedef pair<const Key, T> value_type

Thus in my example p is a const reference to the value_type where Key is std::string and T is int

Also it would be better if the function would be declared as

void output( const map<string, int> &table );

How do I find the length of an array?

Doing sizeof( myArray ) will get you the total number of bytes allocated for that array. You can then find out the number of elements in the array by dividing by the size of one element in the array: sizeof( myArray[0] )

CSS: How to position two elements on top of each other, without specifying a height?

Here's some reusable css that will preserve the height of each element without using position: absolute:

.stack {
    display: grid;
}
.stack > * {
    grid-row: 1;
    grid-column: 1;
}

The first element in your stack is the background, and the second is the foreground.

How to Compare a long value is equal to Long value

Since Java 7 you can use java.util.Objects.equals(Object a, Object b):

These utilities include null-safe or null-tolerant methods

Long id1 = null;
Long id2 = 0l;
Objects.equals(id1, id2));

Get single row result with Doctrine NativeQuery

You can use $query->getSingleResult(), which will throw an exception if more than one result are found, or if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791)

There's also the less famous $query->getOneOrNullResult() which will throw an exception if more than one result are found, and return null if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752)

What are Makefile.am and Makefile.in?

DEVELOPER runs autoconf and automake:

  1. autoconf -- creates shippable configure script
    (which the installer will later run to make the Makefile)
  1. automake - creates shippable Makefile.in data file
    (which configure will later read to make the Makefile)

INSTALLER runs configure, make and sudo make install:

./configure       # Creates  Makefile        (from     Makefile.in).  
make              # Creates  the application (from the Makefile just created).  

sudo make install # Installs the application 
                  #   Often, by default its files are installed into /usr/local


INPUT/OUTPUT MAP

Notation below is roughly: inputs --> programs --> outputs

DEVELOPER runs these:

configure.ac -> autoconf -> configure (script) --- (*.ac = autoconf)
configure.in --> autoconf -> configure (script) --- (configure.in depreciated. Use configure.ac)

Makefile.am -> automake -> Makefile.in ----------- (*.am = automake)

INSTALLER runs these:

Makefile.in -> configure -> Makefile (*.in = input file)

Makefile -> make ----------> (puts new software in your downloads or temporary directory)
Makefile -> make install -> (puts new software in system directories)


"autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls."

"automake is a tool for automatically generating Makefile.in files compliant with the GNU Coding Standards. Automake requires the use of Autoconf."

Manuals:

Free online tutorials:


Example:

The main configure.ac used to build LibreOffice is over 12k lines of code, (but there are also 57 other configure.ac files in subfolders.)

From this my generated configure is over 41k lines of code.

And while the Makefile.in and Makefile are both only 493 lines of code. (But, there are also 768 more Makefile.in's in subfolders.)

Get element inside element by class and ID - JavaScript

Recursive function :

function getElementInsideElement(baseElement, wantedElementID) {
    var elementToReturn;
    for (var i = 0; i < baseElement.childNodes.length; i++) {
        elementToReturn = baseElement.childNodes[i];
        if (elementToReturn.id == wantedElementID) {
            return elementToReturn;
        } else {
            return getElementInsideElement(elementToReturn, wantedElementID);
        }
    }
}

What is %2C in a URL?

It's the ASCII keycode in hexadecimal for a comma (,).

You should use your language's URL encoding methods when placing strings in URLs.

You can see a handy list of characters with man ascii. It has this compact diagram available for mapping hexadecimal codes to the character:

   2 3 4 5 6 7       
 -------------      
0:   0 @ P ` p     
1: ! 1 A Q a q     
2: " 2 B R b r     
3: # 3 C S c s     
4: $ 4 D T d t     
5: % 5 E U e u     
6: & 6 F V f v     
7: ' 7 G W g w     
8: ( 8 H X h x     
9: ) 9 I Y i y     
A: * : J Z j z
B: + ; K [ k {
C: , < L \ l |
D: - = M ] m }
E: . > N ^ n ~
F: / ? O _ o DEL

You can also quickly check a character's hexadecimal equivalent with:

$ echo -n , | xxd -p
2c

Colouring plot by factor in R

The col argument in the plot function assign colors automatically to a vector of integers. If you convert iris$Species to numeric, notice you have a vector of 1,2 and 3s So you can apply this as:

plot(iris$Sepal.Length, iris$Sepal.Width, col=as.numeric(iris$Species))

Suppose you want red, blue and green instead of the default colors, then you can simply adjust it:

plot(iris$Sepal.Length, iris$Sepal.Width, col=c('red', 'blue', 'green')[as.numeric(iris$Species)])

You can probably see how to further modify the code above to get any unique combination of colors.

NodeJS w/Express Error: Cannot GET /

Where is your get method for "/"?

Also you cant serve static html directly in Express.First you need to configure it.

app.configure(function(){
  app.set('port', process.env.PORT || 3000);  
  app.set("view options", {layout: false});  //This one does the trick for rendering static html
  app.engine('html', require('ejs').renderFile); 
  app.use(app.router);

});

Now add your get method.

app.get('/', function(req, res) {
  res.render('default.htm');
});

ascending/descending in LINQ - can one change the order via parameter?

What about ordering desc by the desired property,

   blah = blah.OrderByDescending(x => x.Property);

And then doing something like

  if (!descending)
  {
       blah = blah.Reverse()
  }
  else
  {
      // Already sorted desc ;)
  }

Is it Reverse() too slow?

How do I extend a class with c# extension methods?

Use an extension method.

Ex:

namespace ExtensionMethods
{
    public static class MyExtensionMethods
    {
        public static DateTime Tomorrow(this DateTime date)
        {
            return date.AddDays(1);
        }    
    }
}

Usage:

DateTime.Now.Tomorrow();

or

AnyObjectOfTypeDateTime.Tomorrow();

react-router (v4) how to go back?

I think the issue is with binding:

constructor(props){
   super(props);
   this.goBack = this.goBack.bind(this); // i think you are missing this
}

goBack(){
    this.props.history.goBack();
}

.....

<button onClick={this.goBack}>Go Back</button>

As I have assumed before you posted the code:

constructor(props) {
    super(props);
    this.handleNext = this.handleNext.bind(this);
    this.handleBack = this.handleBack.bind(this); // you are missing this line
}

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I've got the same error. I have been trying to fixing this by setting higher permission to account running SQL Client service, however it didnt help. The problem was that I run MS Sql Management studio just within my account. So, next time... assure that you are running it as Run as Administrator, if using Win7 with UAC enabled.

How to call python script on excel vba?

To those who are stuck wondering why a window flashes and goes away without doing anything the python script is meant to do after calling the shell command from VBA: In my program

Sub runpython()

Dim Ret_Val
args = """F:\my folder\helloworld.py"""
Ret_Val = Shell("C:\Users\username\AppData\Local\Programs\Python\Python36\python.exe " & " " & args, vbNormalFocus)
If Ret_Val = 0 Then
   MsgBox "Couldn't run python script!", vbOKOnly
End If
End Sub

In the line args = """F:\my folder\helloworld.py""", I had to use triple quotes for this to work. If I use just regular quotes like: args = "F:\my folder\helloworld.py" the program would not work. The reason for this is that there is a space in the path (my folder). If there is a space in the path, in VBA, you need to use triple quotes.

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.

Create two string data type variables namely DirPath and FilePath. Set the value C:\backup\ to the variable DirPath. Do not set any value to the variable FilePath.

Variables

Select the variable FilePath and select F4 to view the properties. Set the EvaluateAsExpression property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)

Expression

How to calculate distance between two locations using their longitude and latitude value

Get KM from lat long

public static float getKmFromLatLong(float lat1, float lng1, float lat2, float lng2){
            Location loc1 = new Location("");
            loc1.setLatitude(lat1);
            loc1.setLongitude(lng1);
            Location loc2 = new Location("");
            loc2.setLatitude(lat2);
            loc2.setLongitude(lng2);
            float distanceInMeters = loc1.distanceTo(loc2);
            return distanceInMeters/1000;
        }

Chrome ignores autocomplete="off"

No clue why this worked in my case, but on chrome I used autocomplete="none" and Chrome stopped suggesting addresses for my text field.

Is there a way to list open transactions on SQL Server 2000 database?

DBCC OPENTRAN helps to identify active transactions that may be preventing log truncation. DBCC OPENTRAN displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the transaction log of the specified database. Results are displayed only if there is an active transaction that exists in the log or if the database contains replication information.

An informational message is displayed if there are no active transactions in the log.

DBCC OPENTRAN

MATLAB - multiple return values from a function?

Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed

Improve SQL Server query performance on large tables

One of the reasons your 1M test ran quicker is likely because the temp tables are entirely in memory and would only go to disk if your server experiences memory pressure. You can either re-craft your query to remove the order by, add a good clustered index and covering index(es) as previously mentioned, or query the DMV to check for IO pressure to see if hardware related.

-- From Glen Barry
-- Clear Wait Stats (consider clearing and running wait stats query again after a few minutes)
-- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);

-- Check Task Counts to get an initial idea what the problem might be

-- Avg Current Tasks Count, Avg Runnable Tasks Count, Avg Pending Disk IO Count across all schedulers
-- Run several times in quick succession
SELECT AVG(current_tasks_count) AS [Avg Task Count], 
       AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
       AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
FROM sys.dm_os_schedulers WITH (NOLOCK)
WHERE scheduler_id < 255 OPTION (RECOMPILE);

-- Sustained values above 10 suggest further investigation in that area
-- High current_tasks_count is often an indication of locking/blocking problems
-- High runnable_tasks_count is a good indication of CPU pressure
-- High pending_disk_io_count is an indication of I/O pressure

Not receiving Google OAuth refresh token

Setting this will cause the refresh token to be sent every time:

$client->setApprovalPrompt('force');

an example is given below (php):

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("email");
$client->addScope("profile"); 
$client->setAccessType('offline');
$client->setApprovalPrompt('force');

Get last 30 day records from today date in SQL Server

This Should Work Fine

SELECT * FROM product 
WHERE pdate BETWEEN datetime('now', '-30 days') AND datetime('now', 'localtime')

How to mock location on device?

What Dr1Ku posted works. Used the code today but needed to add more locs. So here are some improvements:

Optional: Instead of using the LocationManager.GPS_PROVIDER String, you might want to define your own constat PROVIDER_NAME and use it. When registering for location updates, pick a provider via criteria instead of directly specifying it in as a string.

First: Instead of calling removeTestProvider, first check if there is a provider to be removed (to avoid IllegalArgumentException):

if (mLocationManager.getProvider(PROVIDER_NAME) != null) {
  mLocationManager.removeTestProvider(PROVIDER_NAME);
}

Second: To publish more than one location, you have to set the time for the location:

newLocation.setTime(System.currentTimeMillis());
...
mLocationManager.setTestProviderLocation(PROVIDER_NAME, newLocation);

There also seems to be a google Test that uses MockLocationProviders: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/android/location/LocationManagerProximityTest.java

Another good working example can be found at: http://pedroassuncao.com/blog/2009/11/12/android-location-provider-mock/

Another good article is: http://ballardhack.wordpress.com/2010/09/23/location-gps-and-automated-testing-on-android/#comment-1358 You'll also find some code that actually works for me on the emulator.

Listing all the folders subfolders and files in a directory using php

If you're looking for a recursive directory listing solutions and arrange them in a multidimensional array. Use below code:

<?php
/**
 * Function for recursive directory file list search as an array.
 *
 * @param mixed $dir Main Directory Path.
 *
 * @return array
 */
function listFolderFiles($dir)
{
    $fileInfo     = scandir($dir);
    $allFileLists = [];

    foreach ($fileInfo as $folder) {
        if ($folder !== '.' && $folder !== '..') {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $folder) === true) {
                $allFileLists[$folder] = listFolderFiles($dir . DIRECTORY_SEPARATOR . $folder);
            } else {
                $allFileLists[$folder] = $folder;
            }
        }
    }

    return $allFileLists;
}//end listFolderFiles()


$dir = listFolderFiles('your searching directory path ex:-F:\xampp\htdocs\abc');
echo '<pre>';
print_r($dir);
echo '</pre>'

?>

How to show first commit by 'git log'?

You can just reverse your log and just head it for the first result.

git log --pretty=oneline --reverse | head -1

What is Node.js?

I use Node.js at work, and find it to be very powerful. Forced to choose one word to describe Node.js, I'd say "interesting" (which is not a purely positive adjective). The community is vibrant and growing. JavaScript, despite its oddities can be a great language to code in. And you will daily rethink your own understanding of "best practice" and the patterns of well-structured code. There's an enormous energy of ideas flowing into Node.js right now, and working in it exposes you to all this thinking - great mental weightlifting.

Node.js in production is definitely possible, but far from the "turn-key" deployment seemingly promised by the documentation. With Node.js v0.6.x, "cluster" has been integrated into the platform, providing one of the essential building blocks, but my "production.js" script is still ~150 lines of logic to handle stuff like creating the log directory, recycling dead workers, etc. For a "serious" production service, you also need to be prepared to throttle incoming connections and do all the stuff that Apache does for PHP. To be fair, Ruby on Rails has this exact problem. It is solved via two complementary mechanisms: 1) Putting Ruby on Rails/Node.js behind a dedicated webserver (written in C and tested to hell and back) like Nginx (or Apache / Lighttd). The webserver can efficiently serve static content, access logging, rewrite URLs, terminate SSL, enforce access rules, and manage multiple sub-services. For requests that hit the actual node service, the webserver proxies the request through. 2) Using a framework like Unicorn that will manage the worker processes, recycle them periodically, etc. I've yet to find a Node.js serving framework that seems fully baked; it may exist, but I haven't found it yet and still use ~150 lines in my hand-rolled "production.js".

Reading frameworks like Express makes it seem like the standard practice is to just serve everything through one jack-of-all-trades Node.js service ... "app.use(express.static(__dirname + '/public'))". For lower-load services and development, that's probably fine. But as soon as you try to put big time load on your service and have it run 24/7, you'll quickly discover the motivations that push big sites to have well baked, hardened C-code like Nginx fronting their site and handling all of the static content requests (...until you set up a CDN, like Amazon CloudFront)). For a somewhat humorous and unabashedly negative take on this, see this guy.

Node.js is also finding more and more non-service uses. Even if you are using something else to serve web content, you might still use Node.js as a build tool, using npm modules to organize your code, Browserify to stitch it into a single asset, and uglify-js to minify it for deployment. For dealing with the web, JavaScript is a perfect impedance match and frequently that makes it the easiest route of attack. For example, if you want to grovel through a bunch of JSON response payloads, you should use my underscore-CLI module, the utility-belt of structured data.

Pros / Cons:

  • Pro: For a server guy, writing JavaScript on the backend has been a "gateway drug" to learning modern UI patterns. I no longer dread writing client code.
  • Pro: Tends to encourage proper error checking (err is returned by virtually all callbacks, nagging the programmer to handle it; also, async.js and other libraries handle the "fail if any of these subtasks fails" paradigm much better than typical synchronous code)
  • Pro: Some interesting and normally hard tasks become trivial - like getting status on tasks in flight, communicating between workers, or sharing cache state
  • Pro: Huge community and tons of great libraries based on a solid package manager (npm)
  • Con: JavaScript has no standard library. You get so used to importing functionality that it feels weird when you use JSON.parse or some other build in method that doesn't require adding an npm module. This means that there are five versions of everything. Even the modules included in the Node.js "core" have five more variants should you be unhappy with the default implementation. This leads to rapid evolution, but also some level of confusion.

Versus a simple one-process-per-request model (LAMP):

  • Pro: Scalable to thousands of active connections. Very fast and very efficient. For a web fleet, this could mean a 10X reduction in the number of boxes required versus PHP or Ruby
  • Pro: Writing parallel patterns is easy. Imagine that you need to fetch three (or N) blobs from Memcached. Do this in PHP ... did you just write code the fetches the first blob, then the second, then the third? Wow, that's slow. There's a special PECL module to fix that specific problem for Memcached, but what if you want to fetch some Memcached data in parallel with your database query? In Node.js, because the paradigm is asynchronous, having a web request do multiple things in parallel is very natural.
  • Con: Asynchronous code is fundamentally more complex than synchronous code, and the up-front learning curve can be hard for developers without a solid understanding of what concurrent execution actually means. Still, it's vastly less difficult than writing any kind of multithreaded code with locking.
  • Con: If a compute-intensive request runs for, for example, 100 ms, it will stall processing of other requests that are being handled in the same Node.js process ... AKA, cooperative-multitasking. This can be mitigated with the Web Workers pattern (spinning off a subprocess to deal with the expensive task). Alternatively, you could use a large number of Node.js workers and only let each one handle a single request concurrently (still fairly efficient because there is no process recycle).
  • Con: Running a production system is MUCH more complicated than a CGI model like Apache + PHP, Perl, Ruby, etc. Unhandled exceptions will bring down the entire process, necessitating logic to restart failed workers (see cluster). Modules with buggy native code can hard-crash the process. Whenever a worker dies, any requests it was handling are dropped, so one buggy API can easily degrade service for other cohosted APIs.

Versus writing a "real" service in Java / C# / C (C? really?)

  • Pro: Doing asynchronous in Node.js is easier than doing thread-safety anywhere else and arguably provides greater benefit. Node.js is by far the least painful asynchronous paradigm I've ever worked in. With good libraries, it is only slightly harder than writing synchronous code.
  • Pro: No multithreading / locking bugs. True, you invest up front in writing more verbose code that expresses a proper asynchronous workflow with no blocking operations. And you need to write some tests and get the thing to work (it is a scripting language and fat fingering variable names is only caught at unit-test time). BUT, once you get it to work, the surface area for heisenbugs -- strange problems that only manifest once in a million runs -- that surface area is just much much lower. The taxes writing Node.js code are heavily front-loaded into the coding phase. Then you tend to end up with stable code.
  • Pro: JavaScript is much more lightweight for expressing functionality. It's hard to prove this with words, but JSON, dynamic typing, lambda notation, prototypal inheritance, lightweight modules, whatever ... it just tends to take less code to express the same ideas.
  • Con: Maybe you really, really like coding services in Java?

For another perspective on JavaScript and Node.js, check out From Java to Node.js, a blog post on a Java developer's impressions and experiences learning Node.js.


Modules When considering node, keep in mind that your choice of JavaScript libraries will DEFINE your experience. Most people use at least two, an asynchronous pattern helper (Step, Futures, Async), and a JavaScript sugar module (Underscore.js).

Helper / JavaScript Sugar:

  • Underscore.js - use this. Just do it. It makes your code nice and readable with stuff like _.isString(), and _.isArray(). I'm not really sure how you could write safe code otherwise. Also, for enhanced command-line-fu, check out my own Underscore-CLI.

Asynchronous Pattern Modules:

  • Step - a very elegant way to express combinations of serial and parallel actions. My personal reccomendation. See my post on what Step code looks like.
  • Futures - much more flexible (is that really a good thing?) way to express ordering through requirements. Can express things like "start a, b, c in parallel. When A, and B finish, start AB. When A, and C finish, start AC." Such flexibility requires more care to avoid bugs in your workflow (like never calling the callback, or calling it multiple times). See Raynos's post on using futures (this is the post that made me "get" futures).
  • Async - more traditional library with one method for each pattern. I started with this before my religious conversion to step and subsequent realization that all patterns in Async could be expressed in Step with a single more readable paradigm.
  • TameJS - Written by OKCupid, it's a precompiler that adds a new language primative "await" for elegantly writing serial and parallel workflows. The pattern looks amazing, but it does require pre-compilation. I'm still making up my mind on this one.
  • StreamlineJS - competitor to TameJS. I'm leaning toward Tame, but you can make up your own mind.

Or to read all about the asynchronous libraries, see this panel-interview with the authors.

Web Framework:

  • Express Great Ruby on Rails-esk framework for organizing web sites. It uses JADE as a XML/HTML templating engine, which makes building HTML far less painful, almost elegant even.
  • jQuery While not technically a node module, jQuery is quickly becoming a de-facto standard for client-side user interface. jQuery provides CSS-like selectors to 'query' for sets of DOM elements that can then be operated on (set handlers, properties, styles, etc). Along the same vein, Twitter's Bootstrap CSS framework, Backbone.js for an MVC pattern, and Browserify.js to stitch all your JavaScript files into a single file. These modules are all becoming de-facto standards so you should at least check them out if you haven't heard of them.

Testing:

  • JSHint - Must use; I didn't use this at first which now seems incomprehensible. JSLint adds back a bunch of the basic verifications you get with a compiled language like Java. Mismatched parenthesis, undeclared variables, typeos of many shapes and sizes. You can also turn on various forms of what I call "anal mode" where you verify style of whitespace and whatnot, which is OK if that's your cup of tea -- but the real value comes from getting instant feedback on the exact line number where you forgot a closing ")" ... without having to run your code and hit the offending line. "JSHint" is a more-configurable variant of Douglas Crockford's JSLint.
  • Mocha competitor to Vows which I'm starting to prefer. Both frameworks handle the basics well enough, but complex patterns tend to be easier to express in Mocha.
  • Vows Vows is really quite elegant. And it prints out a lovely report (--spec) showing you which test cases passed / failed. Spend 30 minutes learning it, and you can create basic tests for your modules with minimal effort.
  • Zombie - Headless testing for HTML and JavaScript using JSDom as a virtual "browser". Very powerful stuff. Combine it with Replay to get lightning fast deterministic tests of in-browser code.
  • A comment on how to "think about" testing:
    • Testing is non-optional. With a dynamic language like JavaScript, there are very few static checks. For example, passing two parameters to a method that expects 4 won't break until the code is executed. Pretty low bar for creating bugs in JavaScript. Basic tests are essential to making up the verification gap with compiled languages.
    • Forget validation, just make your code execute. For every method, my first validation case is "nothing breaks", and that's the case that fires most often. Proving that your code runs without throwing catches 80% of the bugs and will do so much to improve your code confidence that you'll find yourself going back and adding the nuanced validation cases you skipped.
    • Start small and break the inertial barrier. We are all lazy, and pressed for time, and it's easy to see testing as "extra work". So start small. Write test case 0 - load your module and report success. If you force yourself to do just this much, then the inertial barrier to testing is broken. That's <30 min to do it your first time, including reading the documentation. Now write test case 1 - call one of your methods and verify "nothing breaks", that is, that you don't get an error back. Test case 1 should take you less than one minute. With the inertia gone, it becomes easy to incrementally expand your test coverage.
    • Now evolve your tests with your code. Don't get intimidated by what the "correct" end-to-end test would look like with mock servers and all that. Code starts simple and evolves to handle new cases; tests should too. As you add new cases and new complexity to your code, add test cases to exercise the new code. As you find bugs, add verifications and / or new cases to cover the flawed code. When you are debugging and lose confidence in a piece of code, go back and add tests to prove that it is doing what you think it is. Capture strings of example data (from other services you call, websites you scrape, whatever) and feed them to your parsing code. A few cases here, improved validation there, and you will end up with highly reliable code.

Also, check out the official list of recommended Node.js modules. However, GitHub's Node Modules Wiki is much more complete and a good resource.


To understand Node, it's helpful to consider a few of the key design choices:

Node.js is EVENT BASED and ASYNCHRONOUS / NON-BLOCKING. Events, like an incoming HTTP connection will fire off a JavaScript function that does a little bit of work and kicks off other asynchronous tasks like connecting to a database or pulling content from another server. Once these tasks have been kicked off, the event function finishes and Node.js goes back to sleep. As soon as something else happens, like the database connection being established or the external server responding with content, the callback functions fire, and more JavaScript code executes, potentially kicking off even more asynchronous tasks (like a database query). In this way, Node.js will happily interleave activities for multiple parallel workflows, running whatever activities are unblocked at any point in time. This is why Node.js does such a great job managing thousands of simultaneous connections.

Why not just use one process/thread per connection like everyone else? In Node.js, a new connection is just a very small heap allocation. Spinning up a new process takes significantly more memory, a megabyte on some platforms. But the real cost is the overhead associated with context-switching. When you have 10^6 kernel threads, the kernel has to do a lot of work figuring out who should execute next. A bunch of work has gone into building an O(1) scheduler for Linux, but in the end, it's just way way more efficient to have a single event-driven process than 10^6 processes competing for CPU time. Also, under overload conditions, the multi-process model behaves very poorly, starving critical administration and management services, especially SSHD (meaning you can't even log into the box to figure out how screwed it really is).

Node.js is SINGLE THREADED and LOCK FREE. Node.js, as a very deliberate design choice only has a single thread per process. Because of this, it's fundamentally impossible for multiple threads to access data simultaneously. Thus, no locks are needed. Threads are hard. Really really hard. If you don't believe that, you haven't done enough threaded programming. Getting locking right is hard and results in bugs that are really hard to track down. Eliminating locks and multi-threading makes one of the nastiest classes of bugs just go away. This might be the single biggest advantage of node.

But how do I take advantage of my 16 core box?

Two ways:

  1. For big heavy compute tasks like image encoding, Node.js can fire up child processes or send messages to additional worker processes. In this design, you'd have one thread managing the flow of events and N processes doing heavy compute tasks and chewing up the other 15 CPUs.
  2. For scaling throughput on a webservice, you should run multiple Node.js servers on one box, one per core, using cluster (With Node.js v0.6.x, the official "cluster" module linked here replaces the learnboost version which has a different API). These local Node.js servers can then compete on a socket to accept new connections, balancing load across them. Once a connection is accepted, it becomes tightly bound to a single one of these shared processes. In theory, this sounds bad, but in practice it works quite well and allows you to avoid the headache of writing thread-safe code. Also, this means that Node.js gets excellent CPU cache affinity, more effectively using memory bandwidth.

Node.js lets you do some really powerful things without breaking a sweat. Suppose you have a Node.js program that does a variety of tasks, listens on a TCP port for commands, encodes some images, whatever. With five lines of code, you can add in an HTTP based web management portal that shows the current status of active tasks. This is EASY to do:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(myJavascriptObject.getSomeStatusInfo());
}).listen(1337, "127.0.0.1");

Now you can hit a URL and check the status of your running process. Add a few buttons, and you have a "management portal". If you have a running Perl / Python / Ruby script, just "throwing in a management portal" isn't exactly simple.

But isn't JavaScript slow / bad / evil / spawn-of-the-devil? JavaScript has some weird oddities, but with "the good parts" there's a very powerful language there, and in any case, JavaScript is THE language on the client (browser). JavaScript is here to stay; other languages are targeting it as an IL, and world class talent is competing to produce the most advanced JavaScript engines. Because of JavaScript's role in the browser, an enormous amount of engineering effort is being thrown at making JavaScript blazing fast. V8 is the latest and greatest javascript engine, at least for this month. It blows away the other scripting languages in both efficiency AND stability (looking at you, Ruby). And it's only going to get better with huge teams working on the problem at Microsoft, Google, and Mozilla, competing to build the best JavaScript engine (It's no longer a JavaScript "interpreter" as all the modern engines do tons of JIT compiling under the hood with interpretation only as a fallback for execute-once code). Yeah, we all wish we could fix a few of the odder JavaScript language choices, but it's really not that bad. And the language is so darn flexible that you really aren't coding JavaScript, you are coding Step or jQuery -- more than any other language, in JavaScript, the libraries define the experience. To build web applications, you pretty much have to know JavaScript anyway, so coding with it on the server has a sort of skill-set synergy. It has made me not dread writing client code.

Besides, if you REALLY hate JavaScript, you can use syntactic sugar like CoffeeScript. Or anything else that creates JavaScript code, like Google Web Toolkit (GWT).

Speaking of JavaScript, what's a "closure"? - Pretty much a fancy way of saying that you retain lexically scoped variables across call chains. ;) Like this:

var myData = "foo";
database.connect( 'user:pass', function myCallback( result ) {
    database.query("SELECT * from Foo where id = " + myData);
} );
// Note that doSomethingElse() executes _BEFORE_ "database.query" which is inside a callback
doSomethingElse();

See how you can just use "myData" without doing anything awkward like stashing it into an object? And unlike in Java, the "myData" variable doesn't have to be read-only. This powerful language feature makes asynchronous-programming much less verbose and less painful.

Writing asynchronous code is always going to be more complex than writing a simple single-threaded script, but with Node.js, it's not that much harder and you get a lot of benefits in addition to the efficiency and scalability to thousands of concurrent connections...

SQL to search objects, including stored procedures, in Oracle

i reached this question while trying to find all procedures which use a certain table

Oracle SQL Developer offers this capability, as pointed out in this article : https://www.thatjeffsmith.com/archive/2012/09/search-and-browse-database-objects-with-oracle-sql-developer/

From the View menu, choose Find DB Object. Choose a DB connection. Enter the name of the table. At Object Types, keep only functions, procedures and packages. At Code section, check All source lines.

enter image description here

Format an Excel column (or cell) as Text in C#?

Use your WorkSheet.Columns.NumberFormat, and set it to string "@", here is the sample:

Excel._Worksheet workSheet = (Excel._Worksheet)_Excel.Worksheets.Add();
//set columns format to text format
workSheet.Columns.NumberFormat = "@";

Note: this text format will apply for your hole excel sheet!

If you want a particular column to apply the text format, for example, the first column, you can do this:

workSheet.Columns[0].NumberFormat = "@";

or this will apply the specified range of woorkSheet to text format:

workSheet.get_Range("A1", "D1").NumberFormat = "@";

How to get the server path to the web directory in Symfony2 from inside the controller?

For Symfony3 In your controller try

$request->server->get('DOCUMENT_ROOT').$request->getBasePath()

Array or List in Java. Which is faster?

I agree that in most cases you should choose the flexibility and elegance of ArrayLists over arrays - and in most cases the impact to program performance will be negligible.

However, if you're doing constant, heavy iteration with little structural change (no adds and removes) for, say, software graphics rendering or a custom virtual machine, my sequential access benchmarking tests show that ArrayLists are 1.5x slower than arrays on my system (Java 1.6 on my one year-old iMac).

Some code:

import java.util.*;

public class ArrayVsArrayList {
    static public void main( String[] args ) {

        String[] array = new String[300];
        ArrayList<String> list = new ArrayList<String>(300);

        for (int i=0; i<300; ++i) {
            if (Math.random() > 0.5) {
                array[i] = "abc";
            } else {
                array[i] = "xyz";
            }

            list.add( array[i] );
        }

        int iterations = 100000000;
        long start_ms;
        int sum;

        start_ms = System.currentTimeMillis();
        sum = 0;

        for (int i=0; i<iterations; ++i) {
          for (int j=0; j<300; ++j) sum += array[j].length();
        }

        System.out.println( (System.currentTimeMillis() - start_ms) + " ms (array)" );
        // Prints ~13,500 ms on my system

        start_ms = System.currentTimeMillis();
        sum = 0;

        for (int i=0; i<iterations; ++i) {
          for (int j=0; j<300; ++j) sum += list.get(j).length();
        }

        System.out.println( (System.currentTimeMillis() - start_ms) + " ms (ArrayList)" );
        // Prints ~20,800 ms on my system - about 1.5x slower than direct array access
    }
}

Google Maps API - Get Coordinates of address

A Nuget solved my problem:Geocoding.Google 4.0.0. Install it so not necessary to write extra classes etc.

https://www.nuget.org/packages/Geocoding.Google/

How do I initialize a byte array in Java?

You can use this utility function:

public static byte[] fromHexString(String src) {
    byte[] biBytes = new BigInteger("10" + src.replaceAll("\\s", ""), 16).toByteArray();
    return Arrays.copyOfRange(biBytes, 1, biBytes.length);
}

Unlike variants of Denys Séguret and stefan.schwetschke, it allows inserting separator symbols (spaces, tabs, etc.) into the input string, making it more readable.

Example of usage:

private static final byte[] CDRIVES
    = fromHexString("e0 4f d0 20 ea 3a 69 10 a2 d8 08 00 2b 30 30 9d");
private static final byte[] CMYDOCS
    = fromHexString("BA8A0D4525ADD01198A80800361B1103");
private static final byte[] IEFRAME
    = fromHexString("80531c87 a0426910 a2ea0800 2b30309d");

How can I insert values into a table, using a subquery with more than one result?

INSERT INTO prices(group, id, price)
SELECT 7, articleId, 1.50
FROM article where name like 'ABC%';

How to get/generate the create statement for an existing hive table?

As of Hive 0.10 this patch-967 implements SHOW CREATE TABLE which "shows the CREATE TABLE statement that creates a given table, or the CREATE VIEW statement that creates a given view."

Usage:

SHOW CREATE TABLE myTable;

How do I access the $scope variable in browser's console using AngularJS?

To add and enhance the other answers, in the console, enter $($0) to get the element. If it's an Angularjs application, a jQuery lite version is loaded by default.

If you are not using jQuery, you can use angular.element($0) as in:

angular.element($0).scope()

To check if you have jQuery and the version, run this command in the console:

$.fn.jquery

If you have inspected an element, the currently selected element is available via the command line API reference $0. Both Firebug and Chrome have this reference.

However, the Chrome developer tools will make available the last five elements (or heap objects) selected through the properties named $0, $1, $2, $3, $4 using these references. The most recently selected element or object can be referenced as $0, the second most recent as $1 and so on.

Here is the Command Line API reference for Firebug that lists it's references.

$($0).scope() will return the scope associated with the element. You can see its properties right away.

Some other things that you can use are:

  • View an elements parent scope:

$($0).scope().$parent.

  • You can chain this too:

$($0).scope().$parent.$parent

  • You can look at the root scope:

$($0).scope().$root

  • If you highlighted a directive with isolate scope, you can look at it with:

$($0).isolateScope()

See Tips and Tricks for Debugging Unfamiliar Angularjs Code for more details and examples.

Get random boolean in Java

Words in a text are always a source of randomness. Given a certain word, nothing can be inferred about the next word. For each word, we can take the ASCII codes of its letters, add those codes to form a number. The parity of this number is a good candidate for a random boolean.

Possible drawbacks:

  1. this strategy is based upon using a text file as a source for the words. At some point, the end of the file will be reached. However, you can estimate how many times you are expected to call the randomBoolean() function from your app. If you will need to call it about 1 million times, then a text file with 1 million words will be enough. As a correction, you can use a stream of data from a live source like an online newspaper.

  2. using some statistical analysis of the common phrases and idioms in a language, one can estimate the next word in a phrase, given the first words of the phrase, with some degree of accuracy. But statistically, these cases are rare, when we can accuratelly predict the next word. So, in most cases, the next word is independent on the previous words.

    package p01;

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

    public class Main {

    String words[];
    int currentIndex=0;
    
    public static String readFileAsString()throws Exception 
      { 
        String data = ""; 
        File file = new File("the_comedy_of_errors");
        //System.out.println(file.exists());
        data = new String(Files.readAllBytes(Paths.get(file.getName()))); 
        return data; 
      } 
    
    public void init() throws Exception
    {
        String data = readFileAsString(); 
        words = data.split("\\t| |,|\\.|'|\\r|\\n|:");
    }
    
    public String getNextWord() throws Exception
    {
        if(currentIndex>words.length-1)
            throw new Exception("out of words; reached end of file");
    
        String currentWord = words[currentIndex];
        currentIndex++;
    
        while(currentWord.isEmpty())
        {
            currentWord = words[currentIndex];
            currentIndex++;
        }
    
        return currentWord;
    }
    
    public boolean getNextRandom() throws Exception
    {
        String nextWord = getNextWord();
        int asciiSum = 0;
    
        for (int i = 0; i < nextWord.length(); i++){
            char c = nextWord.charAt(i);        
            asciiSum = asciiSum + (int) c;
        }
    
        System.out.println(nextWord+"-"+asciiSum);
    
        return (asciiSum%2==1) ;
    }
    
    public static void main(String args[]) throws Exception
    {
        Main m = new Main();
        m.init();
        while(true)
        {
            System.out.println(m.getNextRandom());
            Thread.sleep(100);
        }
    }
    

    }

In Eclipse, in the root of my project, there is a file called 'the_comedy_of_errors' (no extension) - created with File> New > File , where I pasted some content from here: http://shakespeare.mit.edu/comedy_errors/comedy_errors.1.1.html

How to use ArrayAdapter<myClass>

Subclass the ArrayAdapter and override the method getView() to return your own view that contains the contents that you want to display.

Refresh DataGridView when updating data source

Try this Code

List itemStates = new List();

for (int i = 0; i < 10; i++)
{ 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = itemStates;
    dataGridView1.DataBind();
    System.Threading.Thread.Sleep(500);
}

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

I was getting the same error in python 3.4.3 too and I tried using the solutions mentioned here and elsewhere with no success.

Microsoft makes a compiler available for Python 2.7 but it didn't do me much good since I am on 3.4.3.

Python since 3.3 has transitioned over to 2010 and you can download and install Visual C++ 2010 Express for free here: https://www.visualstudio.com/downloads/download-visual-studio-vs#d-2010-express

Here is the official blog post talking about the transition to 2010 for 3.3: http://blog.python.org/2012/05/recent-windows-changes-in-python-33.html

Because previous versions gave a different error for vcvarsall.bat I would double check the version you are using with "pip -V"

C:\Users\B>pip -V
pip 6.0.8 from C:\Python34\lib\site-packages (python 3.4)

As a side note, I too tried using the latest version of VC++ (2013) first but it required installing 2010 express.

From that point forward it should work for anyone using the 32 bit version, if you are on the 64 bit version you will then get the ValueError: ['path'] message because VC++ 2010 doesn't have a 64 bit compuler. For that you have to get the Microsoft SDK 7.1. I can't hyperlink the instruction for 64 bit because I am limited to 2 links per post but its at

Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

How to listen for a WebView finishing loading a URL?

Just to show progress bar, "onPageStarted" and "onPageFinished" methods are enough; but if you want to have an "is_loading" flag (along with page redirects, ...), this methods may executed with non-sequencing, like "onPageStarted > onPageStarted > onPageFinished > onPageFinished" queue.

But with my short test (test it yourself.), "onProgressChanged" method values queue is "0-100 > 0-100 > 0-100 > ..."

private boolean is_loading = false;

webView.setWebChromeClient(new MyWebChromeClient(context));

private final class MyWebChromeClient extends WebChromeClient{
    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        if (newProgress == 0){
            is_loading = true;
        } else if (newProgress == 100){
            is_loading = false;
        }
        super.onProgressChanged(view, newProgress);
    }
}

Also set "is_loading = false" on activity close, if it is a static variable because activity can be finished before page finish.

Should each and every table have a primary key?

I always have a primary key, even if in the beginning I don't have a purpose in mind yet for it. There have been a few times when I eventually need a PK in a table that doesn't have one and it's always more trouble to put it in later. I think there is more of an upside to always including one.

enable or disable checkbox in html

I know this question is a little old but here is my solution.

 // HTML
 // <input type="checkbox" onClick="setcb1()"/>
 // <input type="checkbox" onClick="setcb2()"/>

 // cb1 = checkbox 1
 // cb2 = checkbox 2
  var cb1 = getId('cb1'), 
      cb2 = getId('cb2');

  function getId(id) {
    return document.getElementById(id);
  }

  function setcb1() {
    if(cb1.checked === true) {
      cb2.checked = false;
      cb2.disabled = "disabled"; // You have to disable the unselected checkbox
    } else if(cb1.checked === false) {
      cb2.disabled = ""; // Then enable it if there isn't one selected.  
    }
  }

  function setcb2() {
    if(cb2.checked === true) {
      cb1.checked = false;
      cb1.disabled = "disabled"
    } else if(cb2.checked === false) {
      cb1.disabled = ""
  }

Hope this helps!

Renaming files in a folder to sequential numbers

I spent 3-4 hours developing this solution for an article on this: https://www.cloudsavvyit.com/8254/how-to-bulk-rename-files-to-numeric-file-names-in-linux/

if [ ! -r _e -a ! -r _c ]; then echo 'pdf' > _e; echo 1 > _c ;find . -name "*.$(cat _e)" -print0 | xargs -0 -t -I{} bash -c 'mv -n "{}" $(cat _c).$(cat _e);echo $[ $(cat _c) + 1 ] > _c'; rm -f _e _c; fi

This works for any type of filename (spaces, special chars) by using correct \0 escaping by both find and xargs, and you can set a start file naming offset by increasing echo 1 to any other number if you like.

Set extension at start (pdf in example here). It will also not overwrite any existing files.

How to Generate unique file names in C#

  1. Create your timestamped filename following your normal process
  2. Check to see if filename exists
  3. False - save file
  4. True - Append additional character to file, perhaps a counter
  5. Go to step 2

http to https through .htaccess

I try all of above code but any code is not working for my website.then i try this code and This code is running perfect for my website. You can use the following Rule in htaccess :

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

//Redirect http to https
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

//Redirect non-www to www
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

</IfModule>

Change example.com with your domain name and sorry for my poor english.

`React/RCTBridgeModule.h` file not found

Latest releases of react-native libraries as explained in previous posts and here have breaking compatibility changes. If you do not plan to upgrade to react-native 0.40+ yet you can force install previous version of the library, for example with react-native-fs:

npm install --save -E [email protected]

How to install Cmake C compiler and CXX compiler

Those errors :

"CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage

CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage"

means you haven't installed mingw32-base.

Go to http://sourceforge.net/projects/mingw/files/latest/download?source=files

and then make sure you select "mingw32-base"

Make sure you set up environment variables correctly in PATH section. "C:\MinGW\bin"

After that open CMake and Select Installation --> Delete Cache.

And click configure button again. I solved the problem this way, hope you solve the problem.

Nodemailer with Gmail and NodeJS

For me is working this way, using port and security (I had issues to send emails from gmail using PHP without security settings)

I hope will help someone.

var sendEmail = function(somedata){
  var smtpConfig = {
    host: 'smtp.gmail.com',
    port: 465,
    secure: true, // use SSL, 
                  // you can try with TLS, but port is then 587
    auth: {
      user: '***@gmail.com', // Your email id
      pass: '****' // Your password
    }
  };

  var transporter = nodemailer.createTransport(smtpConfig);
  // replace hardcoded options with data passed (somedata)
  var mailOptions = {
    from: '[email protected]', // sender address
    to: '[email protected]', // list of receivers
    subject: 'Test email', // Subject line
    text: 'this is some text', //, // plaintext body
    html: '<b>Hello world ?</b>' // You can choose to send an HTML body instead
  }

  transporter.sendMail(mailOptions, function(error, info){
    if(error){
      return false;
    }else{
      console.log('Message sent: ' + info.response);
      return true;
    };
  });
}

exports.contact = function(req, res){
   // call sendEmail function and do something with it
   sendEmail(somedata);
}

all the config are listed here (including examples)

How to read file contents into a variable in a batch file?

You can read multiple variables from file like this:

for /f "delims== tokens=1,2" %%G in (param.txt) do set %%G=%%H

where param.txt:

PARAM1=value1
PARAM2=value2
...

How store a range from excel into a Range variable?

here is an example that allows for performing code on each line of the desired areas (pick either from top & bottom of selection, of from selection

Sub doROWSb()           'WORKS    for do selected rows     SEE FIX ROWS ABOVE  (small ver)
Dim E7 As String    'note:  workcell E7 shows:  BG381
E7 = RANGE("E7")    'see eg below
Dim r As Long       'NOTE: this example has a paste formula(s) down a column(s).  WILL REDUCE 10 HOUR DAYS OF PASTING COLUMNS, DOWN TO 3 MINUTES?
Dim c As Long
Dim rCell As RANGE
'Dim LastRow As Long
r = ActiveCell.row
c = ActiveCell.Column   'might not matter if your code affects whole line anyways, still leave as is

Dim FirstRow As Long    'not in use, Delete if only want last row, note: this code already allows for selection as start
Dim LastRow As Long


If 1 Then     'if you are unable to delete rows not needed, just change 2 lines from: If 1, to if 0 (to go from selection last row, to all rows down from selection)
With Selection
    'FirstRow = .Rows(1).row                 'not used here, Delete if only want last row
    LastRow = .Rows(.Rows.Count).row        'find last row in selection
End With
application.CutCopyMode = False             'if not doing any paste op below
Else
    LastRow = Cells(Rows.Count, 1).End(xlUp).row  'find last row used in sheet
End If
application.EnableEvents = True             'EVENTS  need this?
application.ScreenUpdating = False          'offset-cells(row, col)
'RANGE(E7).Select  'TOP ROW SELECT
RANGE("A1") = vbNullString                  'simple macros on-off switch, vb not here:  If RANGE("A1").Value > 0 Then


For Each rCell In RANGE(Cells(r, c), Cells(LastRow, c)) 'new
    rCell.Select    'make 3 macros for each paste macro below
'your code here:

If 1 Then     'to if 0, if want to paste formulas/formats/all down a column
    Selection.EntireRow.Calculate     'calcs all selected rows, even if just selecting 1 cell in each row (might only be doing 1 row aat here, as part of loop)
Else
'dorows() DO ROWS()
'eg's for paste cells down a column, can make 3 separate macros for each: sub alte() altf & altp
      Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False    'make sub alte ()    add thisworkbook:  application.OnKey "%{e}", "alte"
      'Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False     'make sub altf ()    add thisworkbook:  application.OnKey "%{f}", "altf"
      'Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=False         'amke sub altp ()    add thisworkbook:  application.OnKey "%{p}", "altp"
End If
Next rCell

'application.CutCopyMode = False            'finished - stop copy mode
'RANGE("A2").Select
goBEEPS (2), (0.25)       'beeps secs
application.EnableEvents = True             'EVENTS

'note:  workcell E7 has: SUBSTITUTE(SUBSTITUTE(CELL("address",$BG$369),"$",""),"","")
'other col eg (shows: BG:BG):  =SUBSTITUTE(SUBSTITUTE(CELL("address",$BG2),"$",""),ROW(),"")&":"& SUBSTITUTE(SUBSTITUTE(CELL("address",$BG2),"$",""),ROW(),"")
End Sub


'OTHER:
Sub goBEEPSx(b As Long, t As Double)   'beeps secs as:  goBEEPS (2), (0.25)  OR:  goBEEPS(2, 0.25)
  Dim dt  'as double    'worked wo as double
  Dim x
  For b = b To 1 Step -1
    Beep
    x = Timer
  Do
  DoEvents
  dt = Timer - x
  If dt < 0 Then dt = dt + 86400    '86400 no. seconds in a day, in case hit midnight & timer went down to 0
  Loop Until dt >= t
  Next
End Sub

Method has the same erasure as another method in type

It could be possible that the compiler translates Set(Integer) to Set(Object) in java byte code. If this is the case, Set(Integer) would be used only at compile phase for syntax checking.

Remove spaces from a string in VB.NET

2015: Newer LINQ & lambda.

  1. As this is an old Q (and Answer), just thought to update it with newer 2015 methods.
  2. The original "space" can refer to non-space whitespace (ie, tab, newline, paragraph separator, line feed, carriage return, etc, etc).
  3. Also, Trim() only remove the spaces from the front/back of the string, it does not remove spaces inside the string; eg: " Leading and Trailing Spaces " will become "Leading and Trailing Spaces", but the spaces inside are still present.

Function RemoveWhitespace(fullString As String) As String
    Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function

This will remove ALL (white)-space, leading, trailing and within the string.

MySQL - UPDATE multiple rows with different values in one query

UPDATE Table1 SET col1= col2 FROM (SELECT col2, col3 FROM Table2) as newTbl WHERE col4= col3

Here col4 & col1 are in Table1. col2 & col3 are in Table2
I Am trying to update each col1 where col4 = col3 different value for each row

"Error 404 Not Found" in Magento Admin Login Page

I have just copied and moved a Magento site to a local area so I could work on it offline and had the same problem.

But in the end I found out Magento was forcing a redirect from http to https and I didn't have a SSL setup. So this solved my problem http://www.magentocommerce.com/wiki/recover/ssl_access_with_phpmyadmin

It pretty much says set web/secure/use_in_adminhtml value from 1 to 0 in the core_config_data to allow non-secure access to the admin area

Make Frequency Histogram for Factor Variables

The reason you are getting the unexpected result is that hist(...) calculates the distribution from a numeric vector. In your code, table(animalFactor) behaves like a numeric vector with three elements: 1, 3, 7. So hist(...) plots the number of 1's (1), the number of 3's (1), and the number of 7's (1). @Roland's solution is the simplest.

Here's a way to do this using ggplot:

library(ggplot2)
ggp <- ggplot(data.frame(animals),aes(x=animals))
# counts
ggp + geom_histogram(fill="lightgreen")
# proportion
ggp + geom_histogram(fill="lightblue",aes(y=..count../sum(..count..)))

You would get precisely the same result using animalFactor instead of animals in the code above.

Is it worth using Python's re.compile?

This answer might be arriving late but is an interesting find. Using compile can really save you time if you are planning on using the regex multiple times (this is also mentioned in the docs). Below you can see that using a compiled regex is the fastest when the match method is directly called on it. passing a compiled regex to re.match makes it even slower and passing re.match with the patter string is somewhere in the middle.

>>> ipr = r'\D+((([0-2][0-5]?[0-5]?)\.){3}([0-2][0-5]?[0-5]?))\D+'
>>> average(*timeit.repeat("re.match(ipr, 'abcd100.10.255.255 ')", globals={'ipr': ipr, 're': re}))
1.5077415757028423
>>> ipr = re.compile(ipr)
>>> average(*timeit.repeat("re.match(ipr, 'abcd100.10.255.255 ')", globals={'ipr': ipr, 're': re}))
1.8324008992184038
>>> average(*timeit.repeat("ipr.match('abcd100.10.255.255 ')", globals={'ipr': ipr, 're': re}))
0.9187896518778871

How to automatically import data from uploaded CSV or XLS file into Google Sheets

You can get Google Drive to automatically convert csv files to Google Sheets by appending

?convert=true

to the end of the api url you are calling.

EDIT: Here is the documentation on available parameters: https://developers.google.com/drive/v2/reference/files/insert

Also, while searching for the above link, I found this question has already been answered here:

Upload CSV to Google Drive Spreadsheet using Drive v2 API

How to extract svg as file from web page

I just tried it on another website, in firefox. After trying to save the webpage, it gave me a save-file-as dropdown menu with an option called webpage, svg only.

Validation error: "No validator could be found for type: java.lang.Integer"

As the question is asked simply use @Min(1) instead of @size on integer fields and it will work.

Convert Mongoose docs to json

Late answer but you can also try this when defining your schema.

/**
 * toJSON implementation
 */
schema.options.toJSON = {
    transform: function(doc, ret, options) {
        ret.id = ret._id;
        delete ret._id;
        delete ret.__v;
        return ret;
    }
};

Note that ret is the JSON'ed object, and it's not an instance of the mongoose model. You'll operate on it right on object hashes, without getters/setters.

And then:

Model
    .findById(modelId)
    .exec(function (dbErr, modelDoc){
         if(dbErr) return handleErr(dbErr);

         return res.send(modelDoc.toJSON(), 200);
     });

Edit: Feb 2015

Because I didn't provide a solution to the missing toJSON (or toObject) method(s) I will explain the difference between my usage example and OP's usage example.

OP:

UserModel
    .find({}) // will get all users
    .exec(function(err, users) {
        // supposing that we don't have an error
        // and we had users in our collection,
        // the users variable here is an array
        // of mongoose instances;

        // wrong usage (from OP's example)
        // return res.end(users.toJSON()); // has no method toJSON

        // correct usage
        // to apply the toJSON transformation on instances, you have to
        // iterate through the users array

        var transformedUsers = users.map(function(user) {
            return user.toJSON();
        });

        // finish the request
        res.end(transformedUsers);
    });

My Example:

UserModel
    .findById(someId) // will get a single user
    .exec(function(err, user) {
        // handle the error, if any
        if(err) return handleError(err);

        if(null !== user) {
            // user might be null if no user matched
            // the given id (someId)

            // the toJSON method is available here,
            // since the user variable here is a 
            // mongoose model instance
            return res.end(user.toJSON());
        }
    });

Ignore mapping one property with Automapper

I'm perhaps a bit of a perfectionist; I don't really like the ForMember(..., x => x.Ignore()) syntax. It's a little thing, but it it matters to me. I wrote this extension method to make it a bit nicer:

public static IMappingExpression<TSource, TDestination> Ignore<TSource, TDestination>(
    this IMappingExpression<TSource, TDestination> map,
    Expression<Func<TDestination, object>> selector)
{
    map.ForMember(selector, config => config.Ignore());
    return map;
}

It can be used like so:

Mapper.CreateMap<JsonRecord, DatabaseRecord>()
        .Ignore(record => record.Field)
        .Ignore(record => record.AnotherField)
        .Ignore(record => record.Etc);

You could also rewrite it to work with params, but I don't like the look of a method with loads of lambdas.

Open local folder from link

you can use

<a href="\\computername\folder">Open folder</a>

in Internet Explorer

Loop code for each file in a directory

Use the glob function in a foreach loop to do whatever is an option. I also used the file_exists function in the example below to check if the directory exists before going any further.

$directory = 'my_directory/';
$extension = '.txt';

if ( file_exists($directory) ) {
   foreach ( glob($directory . '*' . $extension) as $file ) {
      echo $file;
   }
}
else {
   echo 'directory ' . $directory . ' doesn\'t exist!';
}

C library function to perform sort

I think you are looking for qsort.
qsort function is the implementation of quicksort algorithm found in stdlib.h in C/C++.

Here is the syntax to call qsort function:

void qsort(void *base, size_t nmemb, size_t size,int (*compar)(const void *, const void *));

List of arguments:

base: pointer to the first element or base address of the array
nmemb: number of elements in the array
size: size in bytes of each element
compar: a function that compares two elements

Here is a code example which uses qsort to sort an array:

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

int arr[] = { 33, 12, 6, 2, 76 };

// compare function, compares two elements
int compare (const void * num1, const void * num2) {
   if(*(int*)num1 > *(int*)num2)
    return 1;
   else
    return -1;
}

int main () {
   int i;

   printf("Before sorting the array: \n");
   for( i = 0 ; i < 5; i++ ) {
      printf("%d ", arr[i]);
   }
   // calling qsort
   qsort(arr, 5, sizeof(int), compare);

   printf("\nAfter sorting the array: \n");
   for( i = 0 ; i < 5; i++ ) {   
      printf("%d ", arr[i]);
   }
  
   return 0;
}

You can type man 3 qsort in Linux/Mac terminal to get a detailed info about qsort.
Link to qsort man page

How do I load a file from resource folder?

Try the next:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("test.csv");

If the above doesn't work, various projects have been added the following class: ClassLoaderUtil1 (code here).2

Here are some examples of how that class is used:

src\main\java\com\company\test\YourCallingClass.java
src\main\java\com\opensymphony\xwork2\util\ClassLoaderUtil.java
src\main\resources\test.csv
// java.net.URL
URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// java.io.InputStream
InputStream inputStream = ClassLoaderUtil.getResourceAsStream("test.csv", YourCallingClass.class);
InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader);
for (String line; (line = reader.readLine()) != null;) {
    // Process line
}

Notes

  1. See it in The Wayback Machine.
  2. Also in GitHub.

Python: Assign print output to a variable

To answer the question more generaly how to redirect standard output to a variable ?

do the following :

from io import StringIO
import sys

result = StringIO()
sys.stdout = result
result_string = result.getvalue()

If you need to do that only in some function do the following :

old_stdout = sys.stdout  

# your function containing the previous lines
my_function()

sys.stdout = old_stdout

Importing a function from a class in another file?

from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME

FILENAME is w/o the suffix

How to jQuery clone() and change id?

This works too

_x000D_
_x000D_
 var i = 1;_x000D_
 $('button').click(function() {_x000D_
     $('#red').clone().appendTo('#test').prop('id', 'red' + i);_x000D_
     i++; _x000D_
 });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>_x000D_
<div id="test">_x000D_
  <button>Clone</button>_x000D_
  <div class="red" id="red">_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<style>_x000D_
  .red {_x000D_
    width:20px;_x000D_
    height:20px;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
  }_x000D_
</style>
_x000D_
_x000D_
_x000D_

How can I call a function using a function pointer?

You can declare the function pointer as follows:

bool (funptr*)();

Which says we are declaring a function pointer to a function which does not take anything and return a bool.

Next assignment:

funptr = A;

To call the function using the function pointer:

funptr();

Can I open a dropdownlist using jQuery

One thing that this doesn't answer is what happens when you click on one of the options in the select list after you have done your size = n and made it absolute positioning.

Because the blur event makes it size = 1 and changes it back to how it looks, you should have something like this as well

$("option").click(function(){
    $(this).parent().blur();
});

Also, if you're having issues with the absolute positioned select list showing behind other elements, just put a

z-index: 100;

or something like that in the style of the select.

Convert ArrayList<String> to String[] array

The correct way to do this is:

String[] stockArr = stock_list.toArray(new String[stock_list.size()]);

I'd like to add to the other great answers here and explain how you could have used the Javadocs to answer your question.

The Javadoc for toArray() (no arguments) is here. As you can see, this method returns an Object[] and not String[] which is an array of the runtime type of your list:

public Object[] toArray()

Returns an array containing all of the elements in this collection. If the collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order. The returned array will be "safe" in that no references to it are maintained by the collection. (In other words, this method must allocate a new array even if the collection is backed by an Array). The caller is thus free to modify the returned array.

Right below that method, though, is the Javadoc for toArray(T[] a). As you can see, this method returns a T[] where T is the type of the array you pass in. At first this seems like what you're looking for, but it's unclear exactly why you're passing in an array (are you adding to it, using it for just the type, etc). The documentation makes it clear that the purpose of the passed array is essentially to define the type of array to return (which is exactly your use case):

public <T> T[] toArray(T[] a)

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection. If the collection fits in the specified array with room to spare (i.e., the array has more elements than the collection), the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the collection only if the caller knows that the collection does not contain any null elements.)

If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

This implementation checks if the array is large enough to contain the collection; if not, it allocates a new array of the correct size and type (using reflection). Then, it iterates over the collection, storing each object reference in the next consecutive element of the array, starting with element 0. If the array is larger than the collection, a null is stored in the first location after the end of the collection.

Of course, an understanding of generics (as described in the other answers) is required to really understand the difference between these two methods. Nevertheless, if you first go to the Javadocs, you will usually find your answer and then see for yourself what else you need to learn (if you really do).

Also note that reading the Javadocs here helps you to understand what the structure of the array you pass in should be. Though it may not really practically matter, you should not pass in an empty array like this:

String [] stockArr = stockList.toArray(new String[0]);  

Because, from the doc, this implementation checks if the array is large enough to contain the collection; if not, it allocates a new array of the correct size and type (using reflection). There's no need for the extra overhead in creating a new array when you could easily pass in the size.

As is usually the case, the Javadocs provide you with a wealth of information and direction.

Hey wait a minute, what's reflection?

In Android, how do I set margins in dp programmatically?

int sizeInDP = 16;

int marginInDp = (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, sizeInDP, getResources()
                    .getDisplayMetrics());

Then

layoutParams = myView.getLayoutParams()
layoutParams.setMargins(marginInDp, marginInDp, marginInDp, marginInDp);
myView.setLayoutParams(layoutParams);

Or

LayoutParams layoutParams = new LayoutParams...
layoutParams.setMargins(marginInDp, marginInDp, marginInDp, marginInDp);
myView.setLayoutParams(layoutParams);

Difference between MEAN.js and MEAN.io

I'm surprised nobody has mentioned the Yeoman generator angular-fullstack. It is the number one Yeoman community generator, with currently 1490 stars on the generator page vs Mean.js' 81 stars (admittedly not a fair comparison given how new MEANJS is). It is appears to be actively maintained and is in version 2.05 as I write this. Unlike MEANJS, it doesn't use Swig for templating. It can be scaffolded with passport built in.

Import CSV file as a pandas DataFrame

Try this

import pandas as pd
data=pd.read_csv('C:/Users/Downloads/winequality-red.csv')

Replace the file target location, with where your data set is found, refer this url https://medium.com/@kanchanardj/jargon-in-python-used-in-data-science-to-laymans-language-part-one-12ddfd31592f

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

The problem is the std namespace you are missing. cout is in the std namespace.
Add using namespace std; after the #include

jQuery get html of container including the container itself

Simple solution with an example :

<div id="id_div">
  <p>content<p>
</div>

Move this DIV to other DIV with id = "other_div_id"

$('#other_div_id').prepend( $('#id_div') );

Finish

Android Studio Rendering Problems : The following classes could not be found

Please see the following link - here is where I found a solution that worked for me.

Rendering problems in Android Studio v 1.1 / 1.2

Changing the Android Version when rendering layouts worked for me - I flipped it back to 21 and my "Hello World" app then rendered the basic activity_main.xml OK - at 22 I got this error. I borrowed the image from this posting to show you where to click in the Design tab of the XML preview. What is wierd is that when I flip back to 22 the problem is still gone :-).

enter image description here

CORS header 'Access-Control-Allow-Origin' missing

You must have got the idea why you are getting this problem after going through above answers.

self.send_header('Access-Control-Allow-Origin', '*')

You just have to add the above line in your server side.

How do I find all files containing specific text on Linux?

Kindly customize below command according to demand and find any string recursively from files.

grep -i hack $(find /etc/ -type f)

How to change default timezone for Active Record in Rails?

If you want to set the timezone to UTC globally, you can do the following in Rails 4:

# Inside config/application.rb
config.time_zone = "UTC"
config.active_record.default_timezone = :utc

Be sure to restart your application or you won't see the changes.

Decompile an APK, modify it and then recompile it

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

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

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

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

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

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

java.io.InvalidClassException: local class incompatible:

If you are using the Eclipse IDE, check your Debug/Run configuration. At Classpath tab, select the runner project and click Edit button. Only include exported entries must be checked.

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

.loc accept row and column selectors simultaneously (as do .ix/.iloc FYI) This is done in a single pass as well.

In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))

In [2]: df
Out[2]: 
          a         b         c         d         e
0  0.669701  0.780497  0.955690  0.451573  0.232194
1  0.952762  0.585579  0.890801  0.643251  0.556220
2  0.900713  0.790938  0.952628  0.505775  0.582365
3  0.994205  0.330560  0.286694  0.125061  0.575153

In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]: 
          a         d
0  0.669701  0.451573
1  0.952762  0.643251
2  0.900713  0.505775

And if you want the values (though this should pass directly to sklearn as is); frames support the array interface

In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]: 
array([[ 0.66970138,  0.45157274],
       [ 0.95276167,  0.64325143],
       [ 0.90071271,  0.50577509]])

How to check if a string contains only numbers?

You could use a regular expression like this

If Regex.IsMatch(number, "^[0-9 ]+$") Then

...

End If

How can I compare two lists in python and return matches

A quick performance test showing Lutz's solution is the best:

import time

def speed_test(func):
    def wrapper(*args, **kwargs):
        t1 = time.time()
        for x in xrange(5000):
            results = func(*args, **kwargs)
        t2 = time.time()
        print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0)
        return results
    return wrapper

@speed_test
def compare_bitwise(x, y):
    set_x = frozenset(x)
    set_y = frozenset(y)
    return set_x & set_y

@speed_test
def compare_listcomp(x, y):
    return [i for i, j in zip(x, y) if i == j]

@speed_test
def compare_intersect(x, y):
    return frozenset(x).intersection(y)

# Comparing short lists
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
compare_bitwise(a, b)
compare_listcomp(a, b)
compare_intersect(a, b)

# Comparing longer lists
import random
a = random.sample(xrange(100000), 10000)
b = random.sample(xrange(100000), 10000)
compare_bitwise(a, b)
compare_listcomp(a, b)
compare_intersect(a, b)

These are the results on my machine:

# Short list:
compare_bitwise took 10.145 ms
compare_listcomp took 11.157 ms
compare_intersect took 7.461 ms

# Long list:
compare_bitwise took 11203.709 ms
compare_listcomp took 17361.736 ms
compare_intersect took 6833.768 ms

Obviously, any artificial performance test should be taken with a grain of salt, but since the set().intersection() answer is at least as fast as the other solutions, and also the most readable, it should be the standard solution for this common problem.

How to have comments in IntelliSense for function in Visual Studio?

Do XML commenting , like this

/// <summary>
/// This does something that is awesome
/// </summary>
public void doesSomethingAwesome() {}

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

A lot of people are going to say this is a bad answer because it is not best practice but you can also convert it to a List before your where.

result = result.ToList().Where(p => date >= p.DOB);

Slauma's answer is better, but this would work as well. This cost more because ToList() will execute the Query against the database and move the results into memory.

Show space, tab, CRLF characters in editor of Visual Studio

My problem was hitting CTRL+F and space

This marked all spaces brown. Spent 10 minutes to "turn it off" :P

PHP Pass by reference in foreach

I found this example also tricky. Why that in the 2nd loop at the last iteration nothing happens ($v stays 'two'), is that $v points to $a[3] (and vice versa), so it cannot assign value to itself, so it keeps the previous assigned value :)

How to set conditional breakpoints in Visual Studio?

  1. Set a breakpoint as usual.
  2. Right-click on the breakpoint marker
  3. Click "Condition..."
  4. Write a condition, you may use variable names
  5. Select either "Is True" or "Has Changed"

From an array of objects, extract value of a property as array

It is better to use some sort of libraries like lodash or underscore for cross browser assurance.

In Lodash you can get values of a property in array by following method

_.map(objArray,"foo")

and in Underscore

_.pluck(objArray,"foo")

Both will return

[1, 2, 3]

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

I pasted this in the beginning of the script:

:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\icacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo args = "" >> "%temp%\getadmin.vbs"
    echo For Each strArg in WScript.Arguments >> "%temp%\getadmin.vbs"
    echo args = args ^& strArg ^& " "  >> "%temp%\getadmin.vbs"
    echo Next >> "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", args, "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs" %*
    exit /B

:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

Unlike standard arithmetic, which desires matching dimensions, dot products require that the dimensions are one of:

  • (X..., A, B) dot (Y..., B, C) -> (X..., Y..., A, C), where ... means "0 or more different values
  • (B,) dot (B, C) -> (C,)
  • (A, B) dot (B,) -> (A,)
  • (B,) dot (B,) -> ()

Your problem is that you are using np.matrix, which is totally unnecessary in your code - the main purpose of np.matrix is to translate a * b into np.dot(a, b). As a general rule, np.matrix is probably not a good choice.

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

You can have the @Transactional in the child class, but you have to override each of the methods and call the super method in order to get it to work.

Example:

@Transactional(readOnly = true)
public class Bob<SomeClass> {
   @Override
   public SomeClass getValue() {
       return super.getValue();
   }
}

This allows it to set it up for each of the methods it's needed for.

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

You have to catch the error just as you're already doing for your save() call and since you're handling multiple errors here, you can try multiple calls sequentially in a single do-catch block, like so:

func deleteAccountDetail() {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
            self.Context!.deleteObject(entity)
        }

        try self.Context!.save()
    } catch {
        print(error)
    }
}

Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws then try to call the method. For example:

func deleteAccountDetail() throws {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()

    request.entity = entityDescription

    let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]

    for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
    }

    try self.Context!.save()
}

How to convert a HTMLElement to a string

Suppose your element is entire [object HTMLDocument]. You can convert it to a String this way:

_x000D_
_x000D_
const htmlTemplate = `<!DOCTYPE html><html lang="en"><head></head><body></body></html>`;

const domparser = new DOMParser();
const doc = domparser.parseFromString(htmlTemplate, "text/html"); // [object HTMLDocument]

const doctype = '<!DOCTYPE html>';
const html = doc.documentElement.outerHTML;

console.log(doctype + html);
_x000D_
_x000D_
_x000D_

Force "portrait" orientation mode

I think android:screenOrientation="portrait" can be used for individual activities. So use that attribute in <activity> tag like :

<activity android:name=".<Activity Name>"
    android:label="@string/app_name" 
    android:screenOrientation="portrait">
   ...         
</activity>

nvm is not compatible with the npm config "prefix" option:

enter image description hereI had the same problem and it was really annoying each time with the terminal. I run the command to the terminal and it was fixed

For those try to remove nvm from brew

it may not be enough to just brew uninstall nvm

if you see npm prefix is still /usr/local, run this command

sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}

MySQL server has gone away - in exactly 60 seconds

There's a whole bunch of things that can cause this. I'd read through these and try each of them

http://dev.mysql.com/doc/refman/5.1/en/gone-away.html

I've worked for several web hosting companies over the years and generally when I see this, it is the wait_timeout on the server end though this doesn't appear to be the case here.

If you find the solution, I hope you post it. I'd like to know.

Git Clone - Repository not found

You should check if you have any other github account marked as "default". When trying to clone a new repo, the client (in my case BitBucket) will try to get the credentials that you have set "as default". Just mark your new credentials "as default" and it will allow you to clone the repo, it worked for me.

comparing 2 strings alphabetically for sorting purposes

"a".localeCompare("b") should actually return -1 since a sorts before b

http://www.w3schools.com/jsref/jsref_localecompare.asp

Clean out Eclipse workspace metadata

There is no easy way to remove the "outdated" stuff from an existing workspace. Using the "clean" parameter will not really help, as many of the files you refer to are "free form data", only known to the plugins that are no longer available.

Your best bet is to optimize the re-import, where I would like to point out the following:

  • When creating a new workspace, you can already choose to have some settings being copied from the current to the new workspace.
  • You can export the preferences of the current workspace (using the Export menu) and re-import them in the new workspace.
  • There are lots of recommendations on the Internet to just copy the ${old_workspace}/.metadata/.plugins/org.eclipse.core.runtime/.settings folder from the old to the new workspace. This is surely the fastest way, but it may lead to weird behaviour, because some of your plugins may depend on these settings and on some of the mentioned "free form data" stored elsewhere. (There are even people symlinking these folders over multiple workspaces, but this really requires to use the same plugins on all workspaces.)
  • You may want to consider using more project specific settings than workspace preferences in the future. So for instance all the Java compiler settings can either be set on the workspace level or on the project level. If set on the project level, you can put them under version control and are independent of the workspace.

Header set Access-Control-Allow-Origin in .htaccess doesn't work

Be careful on:

 Header add Access-Control-Allow-Origin "*"

This is not judicious at all to grant access to everybody. It's preferable to allow a list of know trusted host only...

Header add Access-Control-Allow-Origin "http://aaa.example"
Header add Access-Control-Allow-Origin "http://bbb.example"
Header add Access-Control-Allow-Origin "http://ccc.example"

Regards,

Generate random colors (RGB)

A neat way to generate RGB triplets within the 256 (aka 8-byte) range is

color = list(np.random.choice(range(256), size=3))

color is now a list of size 3 with values in the range 0-255. You can save it in a list to record if the color has been generated before or no.

Subclipse svn:ignore

This is quite frustrating, but it's a containment issue (the .svn folders keep track also of ignored files). Any item that needs to be ignored is to be added to the ignore list of the immediate parent folder.

So, I had a new sub-folder with a new file in it and wanted to ignore that file but I couldn't do it because the option was grayed out. I solved it by committing the new folder first, which I wanted to (it was a cache folder), and then adding that file to the ignore list (of the newly added folder ;-), having the chance to add a pattern instead of a single file.

How to install Guest addition in Mac OS as guest and Windows machine as host

Guest additions are not available for Mac OS X. You can get features like clipboard sync and shared folders by using VNC and SMB. Here's my answer on a similar question.

How to remove any URL within a string in Python

You could also look at it from the other way around...

from urlparse import urlparse
[el for el in ['text1', 'FTP://somewhere.com', 'text2', 'http://blah.com:8080/foo/bar#header'] if not urlparse(el).scheme]

How to execute a command prompt command from python

From Python you can do directly using below code

import subprocess
proc = subprocess.check_output('C:\Windows\System32\cmd.exe /k %windir%\System32\\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f' ,stderr=subprocess.STDOUT,shell=True)
    print(str(proc))

in first parameter just executed User Account setting you may customize with yours.

Mapping over values in a python dictionary

Just came accross this use case. I implemented gens's answer, adding a recursive approach for handling values that are also dicts:

def mutate_dict_in_place(f, d):
    for k, v in d.iteritems():
        if isinstance(v, dict):
            mutate_dict_in_place(f, v)
        else:
            d[k] = f(v)

# Exemple handy usage
def utf8_everywhere(d):
    mutate_dict_in_place((
        lambda value:
            value.decode('utf-8')
            if isinstance(value, bytes)
            else value
        ),
        d
    )

my_dict = {'a': b'byte1', 'b': {'c': b'byte2', 'd': b'byte3'}}
utf8_everywhere(my_dict)
print(my_dict)

This can be useful when dealing with json or yaml files that encode strings as bytes in Python 2

Polymorphism vs Overriding vs Overloading

Polymorphism simply means "Many Forms".

It does not REQUIRE inheritance to achieve...as interface implementation, which is not inheritance at all, serves polymorphic needs. Arguably, interface implementation serves polymorphic needs "Better" than inheritance.

For example, would you create a super-class to describe all things that can fly? I should think not. You would be be best served to create an interface that describes flight and leave it at that.

So, since interfaces describe behavior, and method names describe behavior (to the programmer), it is not too far of a stretch to consider method overloading as a lesser form of polymorphism.

Run PHP function on html button click

<?php
if (isset($_POST['str'])){
function printme($str){
echo $str;
}

printme("{$_POST['str']}");
}
?>
<form action="<?php $_PHP_SELF ?>" method="POST">
<input type="text" name="str" /> <input type="submit" value="Submit"/>
</form>

Ranges of floating point datatype in C?

It's a consequence of the size of the exponent part of the type, as in IEEE 754 for example. You can examine the sizes with FLT_MAX, FLT_MIN, DBL_MAX, DBL_MIN in float.h.

ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach)

The following worked for me (Windows 7):

oradim -shutdown -sid enter_sid_here
oradim -startup -sid enter_sid_here

(with enter_sid_here replaced by the SID)

ImportError: numpy.core.multiarray failed to import

After having a nightmare using the pip install -U numpy several months ago, I gave up. I went through installing CV2s and opencv without success.

I was using numpy ver 1.9.1 on python34 and the upgrade just kept stalling on on 1.9.

So I went to https://pypi.python.org/pypi/numpy and discovered the latest numpy version for my python3.4.

I downloaded the .whl file and copied it into the folder containing my python installation, C:\Python34, in my case.

I then ran pip intall on the file name and I can now import cv2 problem free.

Make sure you close down python before you start, obvious but essential

How do I add a new sourceset to Gradle?

If you're using

To get IntelliJ to recognize custom sourceset as test sources root:

plugin {
    idea
}

idea {
    module {
        testSourceDirs = testSourceDirs + sourceSets["intTest"].allJava.srcDirs
        testResourceDirs = testResourceDirs + sourceSets["intTest"].resources.srcDirs
    }
}

Appending values to dictionary in Python

It sounds as if you are trying to setup a list of lists as each value in the dictionary. Your initial value for each drug in the dict is []. So assuming that you have list1 that you want to append to the list for 'MORPHINE' you should do:

drug_dictionary['MORPHINE'].append(list1)

You can then access the various lists in the way that you want as drug_dictionary['MORPHINE'][0] etc.

To traverse the lists stored against key you would do:

for listx in drug_dictionary['MORPHINE'] :
  do stuff on listx

adding comment in .properties files

The property file task is for editing properties files. It contains all sorts of nice features that allow you to modify entries. For example:

<propertyfile file="build.properties">
    <entry key="build_number"
        type="int"
        operation="+"
        value="1"/>
</propertyfile>

I've incremented my build_number by one. I have no idea what the value was, but it's now one greater than what it was before.

  • Use the <echo> task to build a property file instead of <propertyfile>. You can easily layout the content and then use <propertyfile> to edit that content later on.

Example:

<echo file="build.properties">
# Default Configuration
source.dir=1
dir.publish=1
# Source Configuration
dir.publish.html=1
</echo>
  • Create separate properties files for each section. You're allowed a comment header for each type. Then, use to batch them together into one single file:

Example:

<propertyfile file="default.properties"
    comment="Default Configuration">
    <entry key="source.dir" value="1"/>
    <entry key="dir.publish" value="1"/>
<propertyfile>

<propertyfile file="source.properties"
    comment="Source Configuration">
    <entry key="dir.publish.html" value="1"/>
<propertyfile>
<concat destfile="build.properties">
    <fileset dir="${basedir}">
        <include name="default.properties"/>
        <include name="source.properties"/>
    </fileset>
</concat>

<delete>
    <fileset dir="${basedir}">
         <include name="default.properties"/>
        <include name="source.properties"/>
    </fileset>
</delete>