Programs & Examples On #Gen event

how to enable sqlite3 for php?

try this:

sudo apt-get --purge remove php5*
sudo apt-get install php5 php5-sqlite php5-mysql
sudo apt-get install php-pear php-apc php5-curl
sudo apt-get autoremove
sudo apt-get install php5-sqlite
sudo apt-get install libapache2-mod-fastcgi php5-fpm php5

Can't bind to 'ngModel' since it isn't a known property of 'input'

_x000D_
_x000D_
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [

    FormsModule
  ],

})
_x000D_
_x000D_
_x000D_

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

Get the difference between dates in terms of weeks, months, quarters, and years

All the existing answers are imperfect (IMO) and either make assumptions about the desired output or don't provide flexibility for the desired output.

Based on the examples from the OP, and the OP's stated expected answers, I think these are the answers you are looking for (plus some additional examples that make it easy to extrapolate).

(This only requires base R and doesn't require zoo or lubridate)

Convert to Datetime Objects

date_strings = c("14.01.2013", "26.03.2014")
datetimes = strptime(date_strings, format = "%d.%m.%Y") # convert to datetime objects

Difference in Days

You can use the diff in days to get some of our later answers

diff_in_days = difftime(datetimes[2], datetimes[1], units = "days") # days
diff_in_days
#Time difference of 435.9583 days

Difference in Weeks

Difference in weeks is a special case of units = "weeks" in difftime()

diff_in_weeks = difftime(datetimes[2], datetimes[1], units = "weeks") # weeks
diff_in_weeks
#Time difference of 62.27976 weeks

Note that this is the same as dividing our diff_in_days by 7 (7 days in a week)

as.double(diff_in_days)/7
#[1] 62.27976

Difference in Years

With similar logic, we can derive years from diff_in_days

diff_in_years = as.double(diff_in_days)/365 # absolute years
diff_in_years
#[1] 1.194406

You seem to be expecting the diff in years to be "1", so I assume you just want to count absolute calendar years or something, which you can easily do by using floor()

# get desired output, given your definition of 'years'
floor(diff_in_years)
#[1] 1

Difference in Quarters

# get desired output for quarters, given your definition of 'quarters'
floor(diff_in_years * 4)
#[1] 4

Difference in Months

Can calculate this as a conversion from diff_years

# months, defined as absolute calendar months (this might be what you want, given your question details)
months_diff = diff_in_years*12
floor(month_diff)
#[1] 14

I know this question is old, but given that I still had to solve this problem just now, I thought I would add my answers. Hope it helps.

What is python's site-packages directory?

site-packages is just the location where Python installs its modules.

No need to "find it", python knows where to find it by itself, this location is always part of the PYTHONPATH (sys.path).

Programmatically you can find it this way:

import sys
site_packages = next(p for p in sys.path if 'site-packages' in p)
print site_packages

'/Users/foo/.envs/env1/lib/python2.7/site-packages'

How do I check that multiple keys are in a dict in a single pass?

You don't have to wrap the left side in a set. You can just do this:

if {'foo', 'bar'} <= set(some_dict):
    pass

This also performs better than the all(k in d...) solution.

How to cast List<Object> to List<MyClass>

That's because although a Customer is an Object, a List of Customers is not a List of Objects. If it was, then you could put any object in a list of Customers.

Clear dropdown using jQuery Select2

This works for me:

 $remote.select2('data', {id: null, text: null})

It also works with jQuery validate when you clear it that way.

-- edit 2013-04-09

At the time of writing this response, it was the only way. With recent patches, a proper and better way is now available.

$remote.select2('data', null)

Passing Javascript variable to <a href >

If you use internationalization (i18n), and after switch to another language, something like ?locale=fror ?fr might be added at the end of the url. But when you go to another page on click event, translation switch wont be stable.

For this kind of cases a DOM click event handler function must be produced to handle all the a.href attributes by storing the switch state as a variable and add it to all a tags’ tail.

Show whitespace characters in Visual Studio Code

I'd like to offer this suggestion as a side note.
If you're looking to fix all the 'trailing whitespaces' warnings your linter throws at you.
You can have VSCode automatically trim whitespaces from an entire file using the keyboard chord.
CTRL+K / X (by default)

I was looking into showing whitespaces because my linter kept bugging me with whitespace warnings. So that's why I'm here.

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

I also ran into this problem. My situation was a little different. I was using 'working sets' to group my projects inside of eclipse. What I had done was attempt to delete a project and received errors while deleting. Ignoring the errors I removed the project from my working set and thus didn't see that I even had the project anymore. When I received my error I didn't think to look through my package explorer with 'projects', opposed to working sets, as my top view. After switching to a top level view of projects I found the project that was half deleted and was able to delete its contents from both my workspace and the hard drive.

I haven't had the error since.

What is the usefulness of PUT and DELETE HTTP request methods?

Using HTTP Request verb such as GET, POST, DELETE, PUT etc... enables you to build RESTful web applications. Read about it here: http://en.wikipedia.org/wiki/Representational_state_transfer

The easiest way to see benefits from this is to look at this example. Every MVC framework has a Router/Dispatcher that maps URL-s to actionControllers. So URL like this: /blog/article/1 would invoke blogController::articleAction($id); Now this Router is only aware of the URL or /blog/article/1/

But if that Router would be aware of whole HTTP Request object instead of just URL, he could have access HTTP Request verb (GET, POST, PUT, DELETE...), and many other useful stuff about current HTTP Request.

That would enable you to configure application so it can accept the same URL and map it to different actionControllers depending on the HTTP Request verb.

For example:

if you want to retrive article 1 you can do this:

GET /blog/article/1 HTTP/1.1

but if you want to delete article 1 you will do this:

DELETE /blog/article/1 HTTP/1.1

Notice that both HTTP Requests have the same URI, /blog/article/1, the only difference is the HTTP Request verb. And based on that verb your router can call different actionController. This enables you to build neat URL-s.

Read this two articles, they might help you:

Symfony 2 - HTTP Fundamentals

Symfony 2 - Routing

These articles are about Symfony 2 framework, but they can help you to figure out how does HTTP Requests and Responses work.

Hope this helps!

How do I test if a recordSet is empty? isNull?

If temp_rst1.BOF and temp_rst1.EOF then the recordset is empty. This will always be true for an empty recordset, linked or local.

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

Get data from php array - AJAX - jQuery

When you do echo $array;, PHP will simply echo 'Array' since it can't convert an array to a string. So The 'A' that you are actually getting is the first letter of Array, which is correct.

You might actually need

echo json_encode($array);

This should get you what you want.

EDIT : And obviously, you'd need to change your JS to work with JSON instead of just text (as pointed out by @genesis)

Can Console.Clear be used to only clear a line instead of whole console?

"ClearCurrentConsoleLine", "ClearLine" and the rest of the above functions should use Console.BufferWidth instead of Console.WindowWidth (you can see why when you try to make the window smaller). The window size of the console currently depends of its buffer and cannot be wider than it. Example (thanks goes to Dan Cornilescu):

public static void ClearLastLine()
{
    Console.SetCursorPosition(0, Console.CursorTop - 1);
    Console.Write(new string(' ', Console.BufferWidth));
    Console.SetCursorPosition(0, Console.CursorTop - 1);
}

Finding which process was killed by Linux OOM killer

Now dstat provides the feature to find out in your running system which process is candidate for getting killed by oom mechanism

dstat --top-oom
 --out-of-memory---
  kill score
 java           77
 java           77
 java           77

and as per man page

  --top-oom
          show process that will be killed by OOM the first

Sum rows in data.frame or matrix

The rowSums function (as Greg mentions) will do what you want, but you are mixing subsetting techniques in your answer, do not use "$" when using "[]", your code should look something more like:

data$new <- rowSums( data[,43:167] )

If you want to use a function other than sum, then look at ?apply for applying general functions accross rows or columns.

How to preventDefault on anchor tags?

Try this option which I can see is not yet listed above :

<a href="" ng-click="do()">Click</a>

codeigniter model error: Undefined property

function user() { 

       parent::Model(); 

} 

=> class name is User, construct name is User.

function User() { 

       parent::Model(); 

} 

CORS: credentials mode is 'include'

If you are using CORS middleware and you want to send withCredentials boolean true, you can configure CORS like this:

_x000D_
_x000D_
var cors = require('cors');    _x000D_
app.use(cors({credentials: true, origin: 'http://localhost:5000'}));
_x000D_
_x000D_
_x000D_

`

Found conflicts between different versions of the same dependent assembly that could not be resolved

If you made any changes to packages -- reopen the sln. This worked for me!

How to create a connection string in asp.net c#

string connectionstring="DataSource=severname;InitialCatlog=databasename;Uid=; password=;"
SqlConnection con=new SqlConnection(connectionstring)

Easiest way to copy a table from one database to another?

it's worked good for me

CREATE TABLE dbto.table_name like dbfrom.table_name;
insert into  dbto.table_name select * from dbfrom.table_name;

How to convert String to DOM Document object in java?

Either escape the double quotes with \

String xmlString = "<element attribname=\"value\" attribname1=\"value1\"> pcdata</element>"

or use single quotes instead

String xmlString = "<element attribname='value' attribname1='value1'> pcdata</element>"

Any way to exit bash script, but not quitting the terminal

Also make sure to return with expected return value. Else if you use exit when you will encounter an exit it will exit from your base shell since source does not create another process (instance).

The difference between the Runnable and Callable interfaces in Java

Purpose of these interfaces from oracle documentation :

Runnable interface should be implemented by any class whose instances are intended to be executed by a Thread. The class must define a method of no arguments called run.

Callable: A task that returns a result and may throw an exception. Implementors define a single method with no arguments called call. The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.

Other differences:

  1. You can pass Runnable to create a Thread. But you can't create new Thread by passing Callable as parameter. You can pass Callable only to ExecutorService instances.

    Example:

    public class HelloRunnable implements Runnable {
    
        public void run() {
            System.out.println("Hello from a thread!");
        }   
    
        public static void main(String args[]) {
            (new Thread(new HelloRunnable())).start();
        }
    
    }
    
  2. Use Runnable for fire and forget calls. Use Callable to verify the result.

  3. Callable can be passed to invokeAll method unlike Runnable. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete

  4. Trivial difference : method name to be implemented => run() for Runnable and call() for Callable.

How do I watch a file for changes?

Check my answer to a similar question. You could try the same loop in Python. This page suggests:

import time

while 1:
    where = file.tell()
    line = file.readline()
    if not line:
        time.sleep(1)
        file.seek(where)
    else:
        print line, # already has newline

Also see the question tail() a file with Python.

Colspan all columns

Maybe I'm a straight thinker but I'm a bit puzzled, don't you know the column number of your table?

By the way IE6 doesn't honor the colspan="0", with or without a colgroup defined. I tried also to use thead and th to generate the groups of columns but the browser doesn't recognlise the form colspan="0".

I've tried with Firefox 3.0 on windows and linux and it works only with a strict doctype.

You can check a test on several bowser at

http://browsershots.org/http://hsivonen.iki.fi/test/wa10/tables/colspan-0.html

I found the test page here http://hsivonen.iki.fi/test/wa10/tables/colspan-0.html

Edit: Please copy and paste the link, the formatting won't accept the double protocol parts in the link (or I am not so smart to correctly format it).

Bash loop ping successful

If you use the -o option, Mac OS X’s ping will exit after receiving one reply packet.

Further reading: http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man8/ping.8.html

EDIT: paxdiablo makes a very good point about using ping’s exit status to your advantage. I would do something like:

#!/usr/bin/env bash
echo 'Begin ping'
if ping -oc 100000 8.8.8.8 > /dev/null; then
    echo $(say 'timeout')
else
    echo $(say 'the Internet is back up')
fi

ping will send up to 100,000 packets and then exit with a failure status—unless it receives one reply packet, in which case it exits with a success status. The if will then execute the appropriate statement.

Python update a key in dict if it doesn't exist

Use dict.setdefault():

>>> d = {1: 'one'}
>>> d.setdefault(1, '1')
'one'
>>> d    # d has not changed because the key already existed
{1: 'one'}
>>> d.setdefault(2, 'two')
'two'
>>> d
{1: 'one', 2: 'two'}

Centering a background image, using CSS

simply replace

background-image:url(../images/images2.jpg) no-repeat;

with

background:url(../images/images2.jpg)  center;

Counting the number of True Booleans in a Python List

It is safer to run through bool first. This is easily done:

>>> sum(map(bool,[True, True, False, False, False, True]))
3

Then you will catch everything that Python considers True or False into the appropriate bucket:

>>> allTrue=[True, not False, True+1,'0', ' ', 1, [0], {0:0}, set([0])]
>>> list(map(bool,allTrue))
[True, True, True, True, True, True, True, True, True]

If you prefer, you can use a comprehension:

>>> allFalse=['',[],{},False,0,set(),(), not True, True-1]
>>> [bool(i) for i in allFalse]
[False, False, False, False, False, False, False, False, False]

Is there a command line command for verifying what version of .NET is installed

you can check installed c# compilers and the printed version of the .net:

@echo off

for /r "%SystemRoot%\Microsoft.NET\Framework\" %%# in ("*csc.exe") do (
    set "l="
    for /f "skip=1 tokens=2 delims=k" %%$ in ('"%%# #"') do (
        if not defined l (
            echo Installed: %%$
            set l=%%$
        )
    )
)

echo latest installed .NET %l%

the csc.exe does not have a -version switch but it prints the .net version in its logo. You can also try with msbuild.exe but .net framework 1.* does not have msbuild.

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Let's fit the model:

> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)

Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)

Residuals:
    Min      1Q  Median      3Q     Max 
-245.74 -113.99  -32.05  104.96  484.81 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 811.2267    76.9755  10.539 2.29e-13 ***
body.weight   7.0595     0.9776   7.221 7.03e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 
F-statistic: 52.15 on 1 and 42 DF,  p-value: 7.025e-09 

The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).

This can be computed using confint:

> confint(fit, 'body.weight', level=0.95)
               2.5 % 97.5 %
body.weight 5.086656 9.0324

Correct use of transactions in SQL Server

At the beginning of stored procedure one should put SET XACT_ABORT ON to instruct Sql Server to automatically rollback transaction in case of error. If ommited or set to OFF one needs to test @@ERROR after each statement or use TRY ... CATCH rollback block.

Internet Explorer 11 detection

Edit 18 Nov 2016

This code also work (for those who prefer another solution , without using ActiveX)

var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
  // true on IE11
  // false on Edge and other IEs/browsers.

Original Answer

In order to check Ie11 , you can use this : ( tested)

(or run this)

!(window.ActiveXObject) && "ActiveXObject" in window

I have all VMS of IE :

enter image description here

enter image description here

enter image description here

enter image description here

Notice : this wont work for IE11 :

as you can see here , it returns true :

enter image description here

So what can we do :

Apparently , they added the machine bit space :

ie11 :

"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"

ie12 :

"Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko"

so we can do:

/x64|x32/ig.test(window.navigator.userAgent)

this will return true only for ie11.

Change File Extension Using C#

try this.

filename = Path.ChangeExtension(".blah") 

in you Case:

myfile= c:/my documents/my images/cars/a.jpg;
string extension = Path.GetExtension(myffile);
filename = Path.ChangeExtension(myfile,".blah") 

You should look this post too:

http://msdn.microsoft.com/en-us/library/system.io.path.changeextension.aspx

How to read data from excel file using c#

CSharpJExcel for reading Excel 97-2003 files (XLS), ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, XLSX), and ExcelDataReader that seems to have the ability to handle both formats

Good luck!

Find first element by predicate

No, filter does not scan the whole stream. It's an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply do the following test:

List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);
int a = list.stream()
            .peek(num -> System.out.println("will filter " + num))
            .filter(x -> x > 5)
            .findFirst()
            .get();
System.out.println(a);

Which outputs:

will filter 1
will filter 10
10

You see that only the two first elements of the stream are actually processed.

So you can go with your approach which is perfectly fine.

MySQL compare now() (only date, not time) with a datetime field

Use DATE(NOW()) to compare dates

DATE(NOW()) will give you the date part of current date and DATE(duedate) will give you the date part of the due date. then you can easily compare the dates

So you can compare it like

DATE(NOW()) = DATE(duedate)

OR

DATE(duedate) = CURDATE() 

See here

Import Excel spreadsheet columns into SQL Server database

First of all, try the 32 Bit Version of the Import Wizard. This shows a lot more supported import formats.

Background: All depends on your Office (Runtimes Engines) installation.

If you dont't have Office 2007 or greater installed, the Import Wizard (32 Bit) only allows you to import Excel 97-2003 (.xls) files.

If you have the Office 2010 and geater (comes also in 64 Bit, not recommended) installed, the Import Wizard also supports Excel 2007+ (.xlsx) files.

To get an overview on the runtimes see 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

Script Tag - async & defer

Rendering engine goes several steps till it paints anything on the screen.

it looks like this:

  1. Converting HTML bytes to characters depending on encoding we set to the document;
  2. Tokens are created according to characters. Tokens mean analyze characters and specify opening tangs and nested tags;
  3. From tokens separated nodes are created. they are objects and according to information delivered from tokenization process, engine creates objects which includes all necessary information about each node;
  4. after that DOM is created. DOM is tree data structure and represents whole hierarchy and information about relationship and specification of tags;

The same process goes to CSS. for CSS rendering engine creates different/separated data structure for CSS but it's called CSSOM (CSS Object Model)

Browser works only with Object models so it needs to know all information about DOM and CSSDOM.

The next step is combining somehow DOM and CSSOM. because without CSSOM browser do not know how to style each element during rendering process.

All information above means that, anything you provide in your html (javascript, css ) browser will pause DOM construction process. If you are familiar with event loop, there is simple rule how event loop executes tasks:

  1. Execute macro tasks;
  2. execute micro tasks;
  3. Rendering;

So when you provide Javascript file, browser do not know what JS code is going to do and stops all DOM construction process and Javascript interptreter starts parsing and executing Javascript code.

Even you provide Javascript in the end of body tag, Browser will proceed all above steps to HTML and CSS but except rendering. it will find out Script tag and will stop until JS is done.

But HTML provided two additional options for script tag: async and defer.

Async - means execute code when it is downloaded and do not block DOM construction during downloading process.

Defer - means execute code after it's downloaded and browser finished DOM construction and rendering process.

Why can't I do <img src="C:/localfile.jpg">?

what about having the image be something selected by the user? Use a input:file tag and then after they select the image, show it on the clientside webpage? That is doable for most things. Right now i am trying to get it working for IE, but as with all microsoft products, it is a cluster fork().

Update multiple columns in SQL

The "tiresome way" is standard SQL and how mainstream RDBMS do it.

With a 100+ columns, you mostly likely have a design problem... also, there are mitigating methods in client tools (eg generation UPDATE statements) or by using ORMs

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Here is an official answer to this:

If Git prompts you for a username and password every time you try to interact with GitHub, you're probably using the HTTPS clone URL for your repository.

Using an HTTPS remote URL has some advantages: it's easier to set up than SSH, and usually works through strict firewalls and proxies. However, it also prompts you to enter your GitHub credentials every time you pull or push a repository.

You can configure Git to store your password for you. If you'd like to set that up, read all about setting up password caching.

Replace Default Null Values Returned From Left Outer Join

That's as easy as

IsNull(FieldName, 0)

Or more completely:

SELECT iar.Description, 
  ISNULL(iai.Quantity,0) as Quantity, 
  ISNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
  iar.Compliance 
FROM InventoryAdjustmentReason iar
LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

Run this code It will open google print service popup.

function openPrint(x) {

   if (x > 0) { 
       openPrint(--x); print(x); openPrint(--x);
   }

}

Try it on console where x is integer .

openPrint(1);   // Will open Chrome Print Popup Once
openPrint(2);   // Will open Chrome Print Popup Twice after 1st close and so on

Thanks

Difference between == and === in JavaScript

Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html

The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.

0 == false   // true
0 === false  // false, because they are of a different type
1 == "1"     // true, automatic type conversion for value only
1 === "1"    // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false

Load image from url

add Internet permission in manifest

<uses-permission android:name="android.permission.INTERNET" />

than create methode as below,

 public static Bitmap getBitmapFromURL(String src) {
    try {
        Log.e("src", src);
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        Log.e("Bitmap", "returned");
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("Exception", e.getMessage());
        return null;
    }
}

now add this in your onCreate method,

 ImageView img_add = (ImageView) findViewById(R.id.img_add);


img_add.setImageBitmap(getBitmapFromURL("http://www.deepanelango.me/wpcontent/uploads/2017/06/noyyal1.jpg"));

this is works for me.

MySQL Like multiple values

Like @Alexis Dufrenoy proposed, the query could be:

SELECT * FROM `table` WHERE find_in_set('sports', interests)>0 OR find_in_set('pub', interests)>0

More information in the manual.

Serializing to JSON in jQuery

I've been using jquery-json for 6 months and it works great. It's very simple to use:

var myObj = {foo: "bar", "baz": "wockaflockafliz"};
$.toJSON(myObj);

// Result: {"foo":"bar","baz":"wockaflockafliz"}

How to extract hours and minutes from a datetime.datetime object?

It's easier to use the timestamp for this things since Tweepy gets both

import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))

SQL Server - Return value after INSERT

You can append a select statement to your insert statement. Integer myInt = Insert into table1 (FName) values('Fred'); Select Scope_Identity(); This will return a value of the identity when executed scaler.

Listview Scroll to the end of the list after updating the list

I use

setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);

to add entries at the bottom, and older entries scroll off the top, like a chat transcript

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

In order to dynamically generate View Id form API 17 use

generateViewId()

Which will generate a value suitable for use in setId(int). This value will not collide with ID values generated at build time by aapt for R.id.

Adding a collaborator to my free GitHub account?

Yes the set of instructions above are outdated. For the new GitHub the Settings button must be clicked.

Also the person you try to add as a collaborator must have an existing GitHub account. In other words he should have signed up on GitHub first because it is not possible to send collaboration requests merely by typing in the email address of the collaborator.

Confused by python file mode "w+"

Here is a list of the different modes of opening a file:

  • r

    Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

  • rb

    Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

  • r+

    Opens a file for both reading and writing. The file pointer will be at the beginning of the file.

  • rb+

    Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.

  • w

    Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • wb

    Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • w+

    Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • wb+

    Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • a

    Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

  • ab

    Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

  • a+

    Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

  • ab+

    Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

No Exception while type casting with a null in java

This language feature is convenient in this situation.

public String getName() {
  return (String) memberHashMap.get("Name");
}

If memberHashMap.get("Name") returns null, you'd still want the method above to return null without throwing an exception. No matter what the class is, null is null.

Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }

You can fix the errors by validating your input, which is something you should do regardless of course.

The following typechecks correctly, via type guarding validations

const DNATranscriber = {
    G: 'C',
    C: 'G',
    T: 'A',
    A: 'U'
};

export default class Transcriptor {
    toRna(dna: string) {
        const codons = [...dna];
        if (!isValidSequence(codons)) {
            throw Error('invalid sequence');
        }
        const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
        return transcribedRNA;
    }
}

function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> {
    return values.every(isValidCodon);
}
function isValidCodon(value: string): value is keyof typeof DNATranscriber {
    return value in DNATranscriber;
}

It is worth mentioning that you seem to be under the misapprehention that converting JavaScript to TypeScript involves using classes.

In the following, more idiomatic version, we leverage TypeScript to improve clarity and gain stronger typing of base pair mappings without changing the implementation. We use a function, just like the original, because it makes sense. This is important! Converting JavaScript to TypeScript has nothing to do with classes, it has to do with static types.

const DNATranscriber = {
    G = 'C',
    C = 'G',
    T = 'A',
    A = 'U'
};

export default function toRna(dna: string) {
    const codons = [...dna];
    if (!isValidSequence(codons)) {
        throw Error('invalid sequence');
    }
    const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
    return transcribedRNA;
}

function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> {
    return values.every(isValidCodon);
}
function isValidCodon(value: string): value is keyof typeof DNATranscriber {
    return value in DNATranscriber;
}

Update:

Since TypeScript 3.7, we can write this more expressively, formalizing the correspondence between input validation and its type implication using assertion signatures.

const DNATranscriber = {
    G = 'C',
    C = 'G',
    T = 'A',
    A = 'U'
} as const;

type DNACodon = keyof typeof DNATranscriber;
type RNACodon = typeof DNATranscriber[DNACodon];

export default function toRna(dna: string): RNACodon[] {
    const codons = [...dna];
    validateSequence(codons);
    const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
    return transcribedRNA;
}

function validateSequence(values: string[]): asserts values is DNACodon[] {
    if (!values.every(isValidCodon)) {
        throw Error('invalid sequence');    
    }
}
function isValidCodon(value: string): value is DNACodon {
    return value in DNATranscriber;
}

You can read more about assertion signatures in the TypeScript 3.7 release notes.

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

I have some problem when there are two lists and second one is inside DIV Second list should start at 1. not 2.1

<ol>
    <li>lorem</li>
    <li>lorem ipsum</li>
</ol>

<div>
    <ol>
        <li>lorem (should be 1.)</li>
        <li>lorem ipsum ( should be 2.)</li>
    </ol>
</div>

http://jsfiddle.net/3J4Bu/364/

EDIT: I solved the problem by this http://jsfiddle.net/hy5f6161/

How to launch another aspx web page upon button click?

If you'd like to use Code Behind, may I suggest the following solution for an asp:button -

ASPX Page

<asp:Button ID="btnRecover" runat="server" Text="Recover" OnClick="btnRecover_Click" />

Code Behind

    protected void btnRecover_Click(object sender, EventArgs e)
    {
        var recoveryId = Guid.Parse(lbRecovery.SelectedValue);
        var url = string.Format("{0}?RecoveryId={1}", @"../Recovery.aspx", vehicleId);

        // Response.Redirect(url); // Old way

        Response.Write("<script> window.open( '" + url + "','_blank' ); </script>");
        Response.End();
    }

Restoring database from .mdf and .ldf files of SQL Server 2008

I have an answer for you Yes, It is possible.

Go to

SQL Server Management Studio > select Database > click on attach

Then select and add .mdf and .ldf file. Click on OK.

Android toolbar center title and custom font

Here is title text dependant approach to find TextView instance from Toolbar.

  public static TextView getToolbarTitleView(ActionBarActivity activity, Toolbar toolbar){
    ActionBar actionBar = activity.getSupportActionBar();
    CharSequence actionbarTitle = null;
    if(actionBar != null)
        actionbarTitle = actionBar.getTitle();
    actionbarTitle = TextUtils.isEmpty(actionbarTitle) ? toolbar.getTitle() : actionbarTitle;
    if(TextUtils.isEmpty(actionbarTitle)) return null;
    // can't find if title not set
    for(int i= 0; i < toolbar.getChildCount(); i++){
        View v = toolbar.getChildAt(i);
        if(v != null && v instanceof TextView){
            TextView t = (TextView) v;
            CharSequence title = t.getText();
            if(!TextUtils.isEmpty(title) && actionbarTitle.equals(title) && t.getId() == View.NO_ID){
                //Toolbar does not assign id to views with layout params SYSTEM, hence getId() == View.NO_ID
                //in same manner subtitle TextView can be obtained.
                return t;
            }
        }
    }
    return null;
}

Change image size with JavaScript

//  This one has print statement so you can see the result at every stage if     you would like.  They are not needed

function crop(image, width, height)
{
    image.width = width;
    image.height = height;
    //print ("in function", image, image.getWidth(), image.getHeight());
    return image;
}

var image = new SimpleImage("name of your image here");
//print ("original", image, image.getWidth(), image.getHeight());
//crop(image,200,300);
print ("final", image, image.getWidth(), image.getHeight());

How to monitor network calls made from iOS Simulator

Xcode provides CFNetwork Diagnostic Logging. Apple doc

To enable it, add CFNETWORK_DIAGNOSTICS=3 in the Environment Variable section:

enter image description here

This will show requests from the App with its headers & body. Note that OS_ACTIVITY_MODE must be set to enable as shown. Otherwise no output will be shown on the Console.

pip install - locale.Error: unsupported locale setting

While you can set the locale exporting an env variable, you will have to do that every time you start a session. Setting a locale this way will solve the problem permanently:

sudo apt-get install locales
sudo locale-gen en_US.UTF-8
sudo echo "LANG=en_US.UTF-8" > /etc/default/locale

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

You can use PHP to add a stylesheet for IE 10

Like:

if (stripos($_SERVER['HTTP_USER_AGENT'], 'MSIE 10')) {
    <link rel="stylesheet" type="text/css" href="../ie10.css" />
}

How to create and add users to a group in Jenkins for authentication?

According to this posting by the lead Jenkins developer, Kohsuke Kawaguchi, in 2009, there is no group support for the built-in Jenkins user database. Group support is only usable when integrating Jenkins with LDAP or Active Directory. This appears to be the same in 2012.

However, as Vadim wrote in his answer, you don't need group support for the built-in Jenkins user database, thanks to the Role strategy plug-in.

Skip the headers when editing a csv file using Python

Your reader variable is an iterable, by looping over it you retrieve the rows.

To make it skip one item before your loop, simply call next(reader, None) and ignore the return value.

You can also simplify your code a little; use the opened files as context managers to have them closed automatically:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   reader = csv.reader(infile)
   next(reader, None)  # skip the headers
   writer = csv.writer(outfile)
   for row in reader:
       # process each row
       writer.writerow(row)

# no need to close, the files are closed automatically when you get to this point.

If you wanted to write the header to the output file unprocessed, that's easy too, pass the output of next() to writer.writerow():

headers = next(reader, None)  # returns the headers or `None` if the input is empty
if headers:
    writer.writerow(headers)

Remove all special characters except space from a string using JavaScript

You can do it specifying the characters you want to remove:

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g, '');

How to create a popup window (PopupWindow) in Android

Button endDataSendButton = (Button)findViewById(R.id.end_data_send_button);

Similarly you can get the text view by adding a id to it.

Why do you create a View in a database?

There is more than one reason to do this. Sometimes makes common join queries easy as one can just query a table name instead of doing all the joins.

Another reason is to limit the data to different users. So for instance:

Table1: Colums - USER_ID;USERNAME;SSN

Admin users can have privs on the actual table, but users that you don't want to have access to say the SSN, you create a view as

CREATE VIEW USERNAMES AS SELECT user_id, username FROM Table1;

Then give them privs to access the view and not the table.

Subclipse svn:ignore

It seems Subclipse only allows you to add a top-level folder to ignore list and not any sub folders under it. Not sure why it works this way. However, I found out by trial and error that if you directly add a sub-folder to version control, then it will allow you to add another folder at the same level to the ignore list.

alt text

For example, refer fig above, when I wanted to ignore the webapp folder without adding src, subclipse was not allowing me to do so. But when I added the java folder to version control, the "add to svn:ignore..." was enabled for webapp.

How to use the start command in a batch file?

An extra pair of rabbits' ears should do the trick.

start "" "C:\Program...

START regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START switches.

Visual Studio 2012 Web Publish doesn't copy files

This action was successful for me:

Kill Publish Profiles in "Properties>PublishProfiles>xxxx.pubxml" and re-setting again.

Convert base-2 binary number string to int

Another way to do this is by using the bitstring module:

>>> from bitstring import BitArray
>>> b = BitArray(bin='11111111')
>>> b.uint
255

Note that the unsigned integer is different from the signed integer:

>>> b.int
-1

The bitstring module isn't a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.

Razor View throwing "The name 'model' does not exist in the current context"

In my case, I recently updated from MVC 4 to MVC 5, which screws up the web.config pretty badly. This article helped tremendously.

http://www.asp.net/mvc/overview/releases/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

The bottom line is that you need to check all your version number references in your web.config and Views/web.config to make sure that they are referencing the correct upgraded versions associated with MVC 5.

How do ports work with IPv6?

I would say the best reference is Format for Literal IPv6 Addresses in URL's where usage of [] is defined.

Also, if it is for programming and code, specifically Java, I would suggest this readsClass for Inet6Address java/net/URL definition where usage of Inet4 address in Inet6 connotation and other cases are presented in details. For my case, IPv4-mapped address Of the form::ffff:w.x.y.z, for IPv6 address is used to represent an IPv4 address also solved my problem. It allows the native program to use the same address data structure and also the same socket when communicating with both IPv4 and IPv6 nodes. This is the case on Amazon cloud Linux boxes default setup.

python: sys is not defined

I'm guessing your code failed BEFORE import sys, so it can't find it when you handle the exception.

Also, you should indent the your code whithin the try block.

try:

import sys
# .. other safe imports
try:
    import numpy as np
    # other unsafe imports
except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()

How to find out if an installed Eclipse is 32 or 64 bit version?

Go to the Eclipse base folder ? open eclipse.ini ? you will find the below line at line no 4:

plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20150204-1316 plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120913-144807

As you can see, line 1 is of 64-bit Eclipse. It contains x86_64 and line 2 is of 32-bit Eclipse. It contains x_86.

For 32-bit Eclipse only x86 will be present and for 64-bit Eclipse x86_64 will be present.

How to use Apple's new San Francisco font on a webpage

Apple is abstracting the system fonts going forward. This facility uses new generic family name -apple-system. So something like below should get you what you want.

body 
{
  font-family: -apple-system, "Helvetica Neue", "Lucida Grande";
}

How to download file in swift?

A simple, robust and elegant download manager supporting simultaneous downloads with closure syntax for progress and completion tracking. Written in Swift with Here

And Use like it

func downloadGIF(url: String) {
    let filename = url
    let range: Range<String.Index> = filename.range(of:"media/")!
    let lastrange: Range<String.Index> = filename.range(of:"/200w_d")!
    let finalPath = String(filename[range.lowerBound..<lastrange.lowerBound])
    filename[range.lowerBound..<lastrange.lowerBound]
    let replaceFirstWords = finalPath.replace(string: "media/", replacement: "SocialStatus_GIF_")
    let destinationUrl = "\(replaceFirstWords).gif"

    let request = URLRequest(url: URL(string: imageData.bg_image)!)
    viewProgress.isHidden = false
    self.btnDownload.isHidden = true
    setSharingButtonFalse()
    let downloadKey = self.downloadManager.downloadFile(withRequest: request,
                                                        withName: destinationUrl,
                                                        shouldDownloadInBackground: true,
                                                        onProgress:  { [weak self] (progress) in
                                                            self?.viewProgress.progress = CGFloat(progress)
                                                            let val = progress * 100
                                                            print("val 1 == \(val)")
                                                            DispatchQueue.main.async {
                                                                self?.viewProgress.setProgressText("\(Int(val))")
                                                            }

    }) { [weak self] (error, url) in
        if let error = error {
            print("Error = \(error as NSError)")
            self!.isDownloaded = false
            self!.viewProgress.isHidden = true
            self!.setSharingButtonTrue()
            self?.viewProgress.setProgressText("\(0)")
            print("handle error since couldn't save GIF")
        } else {
            if let url = url {
                self!.isDownloaded = true
                self!.saveGIFDownloaded()
                self!.viewProgress.isHidden = true
                self!.setSharingButtonTrue()
                self!.createAlbum()
                self!.saveGIF(url: url.absoluteURL)

            }
        }
    }

}

Inheritance with base class constructor with parameters

The problem is that the base class foo has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:

public bar(int a, int b) : base(a, b)
{
    c = a * b;
}

How to query a CLOB column in Oracle

To add to the answer.

declare
v_result clob;
begin
---- some operation on v_result
dbms_lob.substr( v_result, 4000 ,length(v_result) - 3999 );

end;
/

In dbms_lob.substr

first parameter is clob which you want to extract .

Second parameter is how much length of clob you want to extract.

Third parameter is from which word you want to extract .

In above example i know my clob size is more than 50000 , so i want last 4000 character .

Apply CSS style attribute dynamically in Angular JS

On a generic note, you can use a combination of ng-if and ng-style incorporate conditional changes with change in background image.

<span ng-if="selectedItem==item.id"
      ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_active.png)',
                'background-size':'52px 57px',
                'padding-top':'70px',
                'background-repeat':'no-repeat',
                'background-position': 'center'}">
 </span>
 <span ng-if="selectedItem!=item.id"
       ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_deactivated.png)',
                'background-size':'52px 57px',
                'padding-top':'70px',
                'background-repeat':'no-repeat',
                'background-position': 'center'}">
 </span>

Can I use a min-height for table, tr or td?

Simply use the css entry of min-height to one of the cells of your table row. Works on old browsers too.

.rowNumberColumn {
    background-color: #e6e6e6;
    min-height: 22;
}

<table width="100%" cellspacing="0" class="htmlgrid-table">
    <tr id="tr_0">
            <td width="3%" align="center" class="readOnlyCell rowNumberColumn">1</td>
            <td align="left" width="40%" id="td_0_0" class="readOnlyCell gContentSection">411978430-Intimate:Ruby:Small</td>

How to run eclipse in clean mode? what happens if we do so?

This will clean the caches used to store bundle dependency resolution and eclipse extension registry data. Using this option will force eclipse to reinitialize these caches.

  1. Open command prompt (cmd)
  2. Go to eclipse application location (D:\eclipse)
  3. Run command eclipse -clean

How to convert Blob to File in JavaScript

You can use the File constructor:

var file = new File([myBlob], "name");

As per the w3 specification this will append the bytes that the blob contains to the bytes for the new File object, and create the file with the specified name http://www.w3.org/TR/FileAPI/#dfn-file

How do I get an animated gif to work in WPF?

I modified Mike Eshva's code,And I made it work better.You can use it with either 1frame jpg png bmp or mutil-frame gif.If you want bind a uri to the control,bind the UriSource properties or you want bind any in-memory stream that you bind the Source propertie which is a BitmapImage.

    /// <summary> 
/// ??????? ?????????? "???????????", ?????????????? ????????????? GIF. 
/// </summary> 
public class AnimatedImage : Image
{
    static AnimatedImage()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(AnimatedImage), new FrameworkPropertyMetadata(typeof(AnimatedImage)));
    }

    #region Public properties

    /// <summary> 
    /// ????????/????????????? ????? ???????? ?????. 
    /// </summary> 
    public int FrameIndex
    {
        get { return (int)GetValue(FrameIndexProperty); }
        set { SetValue(FrameIndexProperty, value); }
    }

    /// <summary>
    /// Get the BitmapFrame List.
    /// </summary>
    public List<BitmapFrame> Frames { get; private set; }

    /// <summary>
    /// Get or set the repeatBehavior of the animation when source is gif formart.This is a dependency object.
    /// </summary>
    public RepeatBehavior AnimationRepeatBehavior
    {
        get { return (RepeatBehavior)GetValue(AnimationRepeatBehaviorProperty); }
        set { SetValue(AnimationRepeatBehaviorProperty, value); }
    }

    public new BitmapImage Source
    {
        get { return (BitmapImage)GetValue(SourceProperty); }
        set { SetValue(SourceProperty, value); }
    }

    public Uri UriSource
    {
        get { return (Uri)GetValue(UriSourceProperty); }
        set { SetValue(UriSourceProperty, value); }
    }

    #endregion

    #region Protected interface

    /// <summary> 
    /// Provides derived classes an opportunity to handle changes to the Source property. 
    /// </summary> 
    protected virtual void OnSourceChanged(DependencyPropertyChangedEventArgs e)
    {
        ClearAnimation();
        BitmapImage source;
        if (e.NewValue is Uri)
        {
            source = new BitmapImage();
            source.BeginInit();
            source.UriSource = e.NewValue as Uri;
            source.CacheOption = BitmapCacheOption.OnLoad;
            source.EndInit();
        }
        else if (e.NewValue is BitmapImage)
        {
            source = e.NewValue as BitmapImage;
        }
        else
        {
            return;
        }
        BitmapDecoder decoder;
        if (source.StreamSource != null)
        {
            decoder = BitmapDecoder.Create(source.StreamSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);
        }
        else if (source.UriSource != null)
        {
            decoder = BitmapDecoder.Create(source.UriSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);
        }
        else
        {
            return;
        }
        if (decoder.Frames.Count == 1)
        {
            base.Source = decoder.Frames[0];
            return;
        }

        this.Frames = decoder.Frames.ToList();

        PrepareAnimation();
    }

    #endregion

    #region Private properties

    private Int32Animation Animation { get; set; }
    private bool IsAnimationWorking { get; set; }

    #endregion

    #region Private methods

    private void ClearAnimation()
    {
        if (Animation != null)
        {
            BeginAnimation(FrameIndexProperty, null);
        }

        IsAnimationWorking = false;
        Animation = null;
        this.Frames = null;
    }

    private void PrepareAnimation()
    {
        Animation =
            new Int32Animation(
                0,
                this.Frames.Count - 1,
                new Duration(
                    new TimeSpan(
                        0,
                        0,
                        0,
                        this.Frames.Count / 10,
                        (int)((this.Frames.Count / 10.0 - this.Frames.Count / 10) * 1000))))
            {
                RepeatBehavior = RepeatBehavior.Forever
            };

        base.Source = this.Frames[0];
        BeginAnimation(FrameIndexProperty, Animation);
        IsAnimationWorking = true;
    }

    private static void ChangingFrameIndex
        (DependencyObject dp, DependencyPropertyChangedEventArgs e)
    {
        AnimatedImage animatedImage = dp as AnimatedImage;

        if (animatedImage == null || !animatedImage.IsAnimationWorking)
        {
            return;
        }

        int frameIndex = (int)e.NewValue;
        ((Image)animatedImage).Source = animatedImage.Frames[frameIndex];
        animatedImage.InvalidateVisual();
    }

    /// <summary> 
    /// Handles changes to the Source property. 
    /// </summary> 
    private static void OnSourceChanged
        (DependencyObject dp, DependencyPropertyChangedEventArgs e)
    {
        ((AnimatedImage)dp).OnSourceChanged(e);
    }

    #endregion

    #region Dependency Properties

    /// <summary> 
    /// FrameIndex Dependency Property 
    /// </summary> 
    public static readonly DependencyProperty FrameIndexProperty =
        DependencyProperty.Register(
            "FrameIndex",
            typeof(int),
            typeof(AnimatedImage),
            new UIPropertyMetadata(0, ChangingFrameIndex));

    /// <summary> 
    /// Source Dependency Property 
    /// </summary> 
    public new static readonly DependencyProperty SourceProperty =
        DependencyProperty.Register(
            "Source",
            typeof(BitmapImage),
            typeof(AnimatedImage),
            new FrameworkPropertyMetadata(
                null,
                FrameworkPropertyMetadataOptions.AffectsRender |
                FrameworkPropertyMetadataOptions.AffectsMeasure,
                OnSourceChanged));

    /// <summary>
    /// AnimationRepeatBehavior Dependency Property
    /// </summary>
    public static readonly DependencyProperty AnimationRepeatBehaviorProperty =
        DependencyProperty.Register(
        "AnimationRepeatBehavior",
        typeof(RepeatBehavior),
        typeof(AnimatedImage),
        new PropertyMetadata(null));

    public static readonly DependencyProperty UriSourceProperty =
        DependencyProperty.Register(
        "UriSource",
        typeof(Uri),
        typeof(AnimatedImage),
                new FrameworkPropertyMetadata(
                null,
                FrameworkPropertyMetadataOptions.AffectsRender |
                FrameworkPropertyMetadataOptions.AffectsMeasure,
                OnSourceChanged));

    #endregion
}

This is a custom control. You need to create it in WPF App Project,and delete the Template override in style.

Change Twitter Bootstrap Tooltip content on click

Thanks this code was very helpful for me, i found it effective on my projects

$(element).attr('title', 'message').tooltip('fixTitle').tooltip('show');

Detect if HTML5 Video element is playing

It seems to me like you could just check for !stream.paused.

How to set cornerRadius for only top-left and top-right corner of a UIView?

I am not sure why your solution did not work but the following code is working for me. Create a bezier mask and apply it to your view. In my code below I was rounding the bottom corners of the _backgroundView with a radius of 3 pixels. self is a custom UITableViewCell:

UIBezierPath *maskPath = [UIBezierPath
    bezierPathWithRoundedRect:self.backgroundImageView.bounds
    byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight)
    cornerRadii:CGSizeMake(20, 20)
];

CAShapeLayer *maskLayer = [CAShapeLayer layer];

maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;

self.backgroundImageView.layer.mask = maskLayer;

Swift version with some improvements:

let path = UIBezierPath(roundedRect:viewToRound.bounds, byRoundingCorners:[.TopRight, .BottomLeft], cornerRadii: CGSizeMake(20, 20))
let maskLayer = CAShapeLayer()

maskLayer.path = path.CGPath
viewToRound.layer.mask = maskLayer

Swift 3.0 version:

let path = UIBezierPath(roundedRect:viewToRound.bounds,
                        byRoundingCorners:[.topRight, .bottomLeft],
                        cornerRadii: CGSize(width: 20, height:  20))

let maskLayer = CAShapeLayer()

maskLayer.path = path.cgPath
viewToRound.layer.mask = maskLayer

Swift extension here

How to fetch Java version using single line command in Linux

Getting only the "major" build #:

java -version 2>&1 | head -n 1 | awk -F'["_.]' '{print $3}'

Go to particular revision

One way would be to create all commits ever made to patches. checkout the initial commit and then apply the patches in order after reading.

use git format-patch <initial revision> and then git checkout <initial revision>. you should get a pile of files in your director starting with four digits which are the patches.

when you are done reading your revision just do git apply <filename> which should look like git apply 0001-* and count.

But I really wonder why you wouldn't just want to read the patches itself instead? Please post this in your comments because I'm curious.

the git manual also gives me this:

git show next~10:Documentation/README

Shows the contents of the file Documentation/README as they were current in the 10th last commit of the branch next.

you could also have a look at git blame filename which gives you a listing where each line is associated with a commit hash + author.

Hibernate: Automatically creating/updating the db tables based on entity classes

In applicationContext.xml file:

<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <!-- This makes /META-INF/persistence.xml is no longer necessary -->
      <property name="packagesToScan" value="com.howtodoinjava.demo.model" />
      <!-- JpaVendorAdapter implementation for Hibernate EntityManager.
           Exposes Hibernate's persistence provider and EntityManager extension interface -->
      <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      </property>
      <property name="jpaProperties">
         <props>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
         </props>
      </property>
   </bean>

How do I get the domain originating the request in express.js?

Instead of:

var host = req.get('host');
var origin = req.get('origin');

you can also use:

var host = req.headers.host;
var origin = req.headers.origin;

Android Studio says "cannot resolve symbol" but project compiles

Invalidate Caches didn't work for me (this time). For me it was enough changing the gradle and syncing again. Or https://stackoverflow.com/a/29565362/2000162

Multiple separate IF conditions in SQL Server

Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.

As a beginner in SQL I find that when using a BEGIN and END SSMS usually adds a squiggly line with incorrect syntax near 'END' to END, simply because there's no content in between yet. If you're just setting up BEGIN and END to get started and add the actual query later, then simply add a bogus PRINT statement so SSMS stops bothering you.

For example:

IF (1=1)
BEGIN
  PRINT 'BOGUS'
END

The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:

IF (1=1)
BEGIN
END

Cloning an Object in Node.js

There is no built-in way to do a real clone (deep copy) of an object in node.js. There are some tricky edge cases so you should definitely use a library for this. I wrote such a function for my simpleoo library. You can use the deepCopy function without using anything else from the library (which is quite small) if you don't need it. This function supports cloning multiple data types, including arrays, dates, and regular expressions, it supports recursive references, and it also works with objects whose constructor functions have required parameters.

Here is the code:

//If Object.create isn't already defined, we just do the simple shim, without the second argument,
//since that's all we need here
var object_create = Object.create;
if (typeof object_create !== 'function') {
    object_create = function(o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

/**
 * Deep copy an object (make copies of all its object properties, sub-properties, etc.)
 * An improved version of http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone
 * that doesn't break if the constructor has required parameters
 * 
 * It also borrows some code from http://stackoverflow.com/a/11621004/560114
 */ 
function deepCopy = function deepCopy(src, /* INTERNAL */ _visited) {
    if(src == null || typeof(src) !== 'object'){
        return src;
    }

    // Initialize the visited objects array if needed
    // This is used to detect cyclic references
    if (_visited == undefined){
        _visited = [];
    }
    // Ensure src has not already been visited
    else {
        var i, len = _visited.length;
        for (i = 0; i < len; i++) {
            // If src was already visited, don't try to copy it, just return the reference
            if (src === _visited[i]) {
                return src;
            }
        }
    }

    // Add this object to the visited array
    _visited.push(src);

    //Honor native/custom clone methods
    if(typeof src.clone == 'function'){
        return src.clone(true);
    }

    //Special cases:
    //Array
    if (Object.prototype.toString.call(src) == '[object Array]') {
        //[].slice(0) would soft clone
        ret = src.slice();
        var i = ret.length;
        while (i--){
            ret[i] = deepCopy(ret[i], _visited);
        }
        return ret;
    }
    //Date
    if (src instanceof Date) {
        return new Date(src.getTime());
    }
    //RegExp
    if (src instanceof RegExp) {
        return new RegExp(src);
    }
    //DOM Element
    if (src.nodeType && typeof src.cloneNode == 'function') {
        return src.cloneNode(true);
    }

    //If we've reached here, we have a regular object, array, or function

    //make sure the returned object has the same prototype as the original
    var proto = (Object.getPrototypeOf ? Object.getPrototypeOf(src): src.__proto__);
    if (!proto) {
        proto = src.constructor.prototype; //this line would probably only be reached by very old browsers 
    }
    var ret = object_create(proto);

    for(var key in src){
        //Note: this does NOT preserve ES5 property attributes like 'writable', 'enumerable', etc.
        //For an example of how this could be modified to do so, see the singleMixin() function
        ret[key] = deepCopy(src[key], _visited);
    }
    return ret;
};

Ternary operator in PowerShell

Powershell 7 has it. https://toastit.dev/2019/09/25/ternary-operator-powershell-7/

PS C:\Users\js> 0 ? 'yes' : 'no'
no
PS C:\Users\js> 1 ? 'yes' : 'no'
yes

Controller not a function, got undefined, while defining controllers globally

These errors occurred, in my case, preceeded by syntax errors at list.find() fuction; 'find' method of a list not recognized by IE11, so has to replace by Filter method, which works for both IE11 and chrome. refer https://github.com/flrs/visavail/issues/19

The backend version is not supported to design database diagrams or tables

I was having the same problem, although I solved out by creating the table using a script query instead of doing it graphically. See the snipped below:

USE [Database_Name]
GO

CREATE TABLE [dbo].[Table_Name](
[tableID] [int] IDENTITY(1,1) NOT NULL,
[column_2] [datatype] NOT NULL,
[column_3] [datatype] NOT NULL,

CONSTRAINT [PK_Table_Name] PRIMARY KEY CLUSTERED 
(
[tableID] ASC
)
)

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

From the book VS 2015 succintly

Shared Projects allows sharing code, assets, and resources across multiple project types. More specifically, the following project types can reference and consume shared projects:

  • Console, Windows Forms, and Windows Presentation Foundation.
  • Windows Store 8.1 apps and Windows Phone 8.1 apps.
  • Windows Phone 8.0/8.1 Silverlight apps.
  • Portable Class Libraries.

Note:- Both shared projects and portable class libraries (PCL) allow sharing code, XAML resources, and assets, but of course there are some differences that might be summarized as follows.

  • A shared project does not produce a reusable assembly, so it can only be consumed from within the solution.
  • A shared project has support for platform-specific code, because it supports environment variables such as WINDOWS_PHONE_APP and WINDOWS_APP that you can use to detect which platform your code is running on.
  • Finally, shared projects cannot have dependencies on third-party libraries.
  • By comparison, a PCL produces a reusable .dll library and can have dependencies on third-party libraries, but it does not support platform environment variables

Multiple FROMs - what it means

As of May 2017, multiple FROMs can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.

The general syntax involves adding FROM additional times within your Dockerfile - whichever is the last FROM statement is the final base image. To copy artifacts and outputs from intermediate images use COPY --from=<base_image_number>.

FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go    .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app    .
CMD ["./app"]  

The result would be two images, one for building, one with just the resulting app (much, much smaller)

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

multi               latest              bcbbf69a9b59        6 minutes ago       10.3MB  
golang              1.7.3               ef15416724f6        4 months ago        672MB  

what is a base image?

A set of files, plus EXPOSE'd ports, ENTRYPOINT and CMD.
You can add files and build a new image based on that base image, with a new Dockerfile starting with a FROM directive: the image mentioned after FROM is "the base image" for your new image.

does it mean that if I declare neo4j/neo4j in a FROM directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?

Only if you don't overwrite CMD and ENTRYPOINT.
But the image in itself is enough: you would use a FROM neo4j/neo4j if you had to add files related to neo4j for your particular usage of neo4j.

height: 100% for <div> inside <div> with display: table-cell

This is exactly what you want:

HTML

<div class="table">

    <div class="cell">
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
        <p>Text</p>
    </div>
    <div class="cell">
        <div class="container">Text</div>
    </div>
</div>

CSS

.table {
    display: table;
    height:auto;
}

.cell {
    border: 2px solid black; 
    display:table-cell;
    vertical-align:top;
}

.container {
    height: 100%;
    overflow:auto;
    border: 2px solid green;
    -moz-box-sizing: border-box;
}

How to enable multidexing with the new Android Multidex support library

With androidx, the classic support libraries no longer work.

Simple solution is to use following code

In your build.gradle file

android{
  ...
  ...
  defaultConfig {
     ...
     ...
     multiDexEnabled true
  }
  ...
}

dependencies {
  ...
  ...
  implementation 'androidx.multidex:multidex:2.0.1'
}

And in your manifest just add name attribute to the application tag

<manifest ...>
    <application
        android:name="androidx.multidex.MultiDexApplication"
     ...
     ...>
         ...
         ...
    </application>
</manifest>

If your application is targeting API 21 or above multidex is enables by default.

Now if you want to get rid of many of the issues you face trying to support multidex - first try using code shrinking by setting minifyEnabled true.

How to sort by two fields in Java?

You need to implement your own Comparator, and then use it: for example

Arrays.sort(persons, new PersonComparator());

Your Comparator could look a bit like this:

public class PersonComparator implements Comparator<? extends Person> {

  public int compare(Person p1, Person p2) {
     int nameCompare = p1.name.compareToIgnoreCase(p2.name);
     if (nameCompare != 0) {
        return nameCompare;
     } else {
       return Integer.valueOf(p1.age).compareTo(Integer.valueOf(p2.age));
     }
  }
}

The comparator first compares the names, if they are not equals it returns the result from comparing them, else it returns the compare result when comparing the ages of both persons.

This code is only a draft: because the class is immutable you could think of building an singleton of it, instead creating a new instance for each sorting.

element not interactable exception in selenium web automation

In my case the element that generated the Exception was a button belonging to a form. I replaced

WebElement btnLogin = driver.findElement(By.cssSelector("button"));
btnLogin.click();

with

btnLogin.submit();

My environment was chromedriver windows 10

Remove a CLASS for all child elements

This should work:

$("#table-filters>ul>li.active").removeClass("active");
//Find all `li`s with class `active`, children of `ul`s, children of `table-filters`

Access to file download dialog in Firefox

Dont know, but you could perhaps check the source of one of the Firefox download addons.

Here is the source for one that I use Download Statusbar.

Can I change the scroll speed using css or jQuery?

The scroll speed CAN be changed, adjusted, reversed, all of the above - via javascript (or a js library such as jQuery).

WHY would you want to do this? Parallax is just one of the reasons. I have no idea why anyone would argue against doing so -- the same negative arguments can be made against hiding DIVs, sliding elements up/down, etc. Websites are always a combination of technical functionality and UX design -- a good designer can use almost any technical capability to improve UX. That is what makes him/her good.

Toni Almeida of Portugal created a brilliant demo, reproduced below:

jsFiddle Demo

HTML:

<div id="myDiv">
    Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. <span class="boldit">Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. </span>
</div>

javascript/jQuery:

  function wheel(event) {
      var delta = 0;
      if (event.wheelDelta) {(delta = event.wheelDelta / 120);}
      else if (event.detail) {(delta = -event.detail / 3);}

      handle(delta);
      if (event.preventDefault) {(event.preventDefault());}
      event.returnValue = false;
  }

  function handle(delta) {
      var time = 1000;
      var distance = 300;

      $('html, body').stop().animate({
          scrollTop: $(window).scrollTop() - (distance * delta)
      }, time );
  }

  if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);}
    window.onmousewheel = document.onmousewheel = wheel;

Source:

How to change default scrollspeed,scrollamount,scrollinertia of a webpage

Recommended add-ons/plugins for Microsoft Visual Studio

Resharper. It's the best productivity tool for any software engineer! TestDriven.Net is pretty good too. and GhostDoc.

github markdown colspan

Compromise minimum solution:

| One    | Two | Three | Four    | Five  | Six 
| -
| Span <td colspan=3>triple  <td colspan=2>double

So you can omit closing </td> for speed, ?r can leave for consistency.

Result from http://markdown-here.com/livedemo.html : markdown table with colspan

Works in Jupyter Markdown.

Update:

As of 2019 year all pipes in the second line are compulsory in Jupyter Markdown.

| One    | Two | Three | Four    | Five  | Six
|-|-|-|-|-|-
| Span <td colspan=3>triple  <td colspan=2>double

minimally:

One    | Two | Three | Four    | Five  | Six
-|||||-
Span <td colspan=3>triple  <td colspan=2>double

Change name of folder when cloning from GitHub?

Here is one more answer from @Marged in comments

  1. Create a folder with the name you want
  2. Run the command below from the folder you created

    git clone <path to your online repo> .
    

What is the difference between dynamic programming and greedy approach?

I would like to cite a paragraph which describes the major difference between greedy algorithms and dynamic programming algorithms stated in the book Introduction to Algorithms (3rd edition) by Cormen, Chapter 15.3, page 381:

One major difference between greedy algorithms and dynamic programming is that instead of first finding optimal solutions to subproblems and then making an informed choice, greedy algorithms first make a greedy choice, the choice that looks best at the time, and then solve a resulting subproblem, without bothering to solve all possible related smaller subproblems.

Define an alias in fish shell

This is how I define a new function foo, run it, and save it persistently.

sthorne@pearl~> function foo
                    echo 'foo was here'
                end
sthorne@pearl~> foo
foo was here
sthorne@pearl~> funcsave foo

Converting an integer to binary in C

void intToBin(int digit) {
    int b;
    int k = 0;
    char *bits;

    bits= (char *) malloc(sizeof(char));
    printf("intToBin\n");
    while (digit) {
        b = digit % 2;
        digit = digit / 2;
        bits[k] = b;
        k++;

        printf("%d", b);
    }
    printf("\n");
    for (int i = k - 1; i >= 0; i--) {
        printf("%d", bits[i]);

    }

}

"psql: could not connect to server: Connection refused" Error when connecting to remote database

Check the port defined in postgresql.conf. My installation of postgres 9.4 uses port 5433 instead of 5432

How to read a CSV file into a .NET Datatable

 Public Function ReadCsvFileToDataTable(strFilePath As String) As DataTable
    Dim dtCsv As DataTable = New DataTable()
    Dim Fulltext As String
    Using sr As StreamReader = New StreamReader(strFilePath)
        While Not sr.EndOfStream
            Fulltext = sr.ReadToEnd().ToString()
            Dim rows As String() = Fulltext.Split(vbLf)
            For i As Integer = 0 To rows.Count() - 1 - 1
                Dim rowValues As String() = rows(i).Split(","c)
                If True Then
                    If i = 0 Then
                        For j As Integer = 0 To rowValues.Count() - 1
                            dtCsv.Columns.Add(rowValues(j))
                        Next
                    Else
                        Dim dr As DataRow = dtCsv.NewRow()
                        For k As Integer = 0 To rowValues.Count() - 1
                            dr(k) = rowValues(k).ToString()
                        Next
                        dtCsv.Rows.Add(dr)
                    End If
                End If
            Next
        End While
    End Using
    Return dtCsv
End Function

Including non-Python files with setup.py

It is 2019, and here is what is working - despite advice here and there, what I found on the internet halfway documented is using setuptools_scm, passed as options to setuptools.setup. This will include any data files that are versioned on your VCS, be it git or any other, to the wheel package, and will make "pip install" from the git repository to bring those files along.

So, I just added these two lines to the setup call on "setup.py". No extra installs or import required:

    setup_requires=['setuptools_scm'],
    include_package_data=True,

No need to manually list package_data, or in a MANIFEST.in file - if it is versioned, it is included in the package. The docs on "setuptools_scm" put emphasis on creating a version number from the commit position, and disregard the really important part of adding the data files. (I can't care less if my intermediate wheel file is named "*0.2.2.dev45+g3495a1f" or will use the hardcoded version number "0.3.0dev0" I've typed in - but leaving crucial files for the program to work behind is somewhat important)

How to get all options in a drop-down list by Selenium WebDriver using C#?

 WebElement element = driver.findElement(By.id("inst_state"));
        Select s = new Select(element);
        List <WebElement> elementcount = s.getOptions();

        System.out.println(elementcount.size());
        for(int i=0 ;i<elementcount.size();i++)
        {
            String value = elementcount.get(i).getText();
            System.out.println(value);

        }

MySQL CREATE FUNCTION Syntax

You have to override your ; delimiter with something like $$ to avoid this kind of error.

After your function definition, you can set the delimiter back to ;.

This should work:

DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal) 
RETURNS decimal
DETERMINISTIC
BEGIN 
  DECLARE dist decimal;
  SET dist = SQRT(x1 - y1);
  RETURN dist;
END$$
DELIMITER ;

How do you serialize a model instance in Django?

If you're dealing with a list of model instances the best you can do is using serializers.serialize(), it gonna fit your need perfectly.

However, you are to face an issue with trying to serialize a single object, not a list of objects. That way, in order to get rid of different hacks, just use Django's model_to_dict (if I'm not mistaken, serializers.serialize() relies on it, too):

from django.forms.models import model_to_dict

# assuming obj is your model instance
dict_obj = model_to_dict( obj )

You now just need one straight json.dumps call to serialize it to json:

import json
serialized = json.dumps(dict_obj)

That's it! :)

Render partial from different folder (not shared)

Just include the path to the view, with the file extension.

Razor:

@Html.Partial("~/Views/AnotherFolder/Messages.cshtml", ViewData.Model.Successes)

ASP.NET engine:

<% Html.RenderPartial("~/Views/AnotherFolder/Messages.ascx", ViewData.Model.Successes); %>

If that isn't your issue, could you please include your code that used to work with the RenderUserControl?

SQL Server Service not available in service list after installation of SQL Server Management Studio

You need to start the SQL Server manually. Press

windows + R

type

sqlservermanager12.msc

right click ->Start

Service configuration does not display SQL Server?

How to list files in an android directory?

Try this:

public class GetAllFilesInDirectory {

public static void main(String[] args) throws IOException {

    File dir = new File("dir");

    System.out.println("Getting all files in " + dir.getCanonicalPath() + " including those in subdirectories");
    List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
    for (File file : files) {
        System.out.println("file: " + file.getCanonicalPath());
    }

}

}

How to make rpm auto install dependencies

In the case of openSUSE Leap 15, I'm receiving similar error:

> sudo rpm -i opera-stable_53.0.2907.68_amd64.rpm 
[sudo] password for root: 
warning: opera-stable_53.0.2907.68_amd64.rpm: Header V4 RSA/SHA512 Signature, key ID a5c7ff72: NOKEY
error: Failed dependencies:
    at is needed by opera-stable-53.0.2907.68-0.x86_64

I run this command to figure out what are the dependencies:

> sudo zypper install opera-stable_53.0.2907.68_amd64.rpm 
Loading repository data...
Reading installed packages...
Resolving package dependencies...

The following 4 NEW packages are going to be installed:
  at libfl2 libHX28 opera-stable

4 new packages to install.
Overall download size: 50.3 MiB. Already cached: 0 B. After the operation, additional 176.9 MiB will be used.
Continue? [y/n/...? shows all options] (y): n

Then I run this command to install dependencies:

> sudo zypper in at
Loading repository data...
Reading installed packages...
Resolving package dependencies...

The following 3 NEW packages are going to be installed:
  at libfl2 libHX28

3 new packages to install.
Overall download size: 208.6 KiB. Already cached: 0 B. After the operation, additional 600.4 KiB will be used.
Continue? [y/n/...? shows all options] (y): y

Then I run this to install the rpm file:

> sudo rpm -i opera-stable_53.0.2907.68_amd64.rpm

I'm not sure if it is the best practice, however it solved my issue.

How to find cube root using Python?

def cube(x):
    if 0<=x: return x**(1./3.)
    return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))

Here is the full answer for both negative and positive numbers.

>>> 
2.0
-2.0
>>> 

Or here is a one-liner;

root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)

How do I parallelize a simple Python loop?

Have a look at this;

http://docs.python.org/library/queue.html

This might not be the right way to do it, but I'd do something like;

Actual code;

from multiprocessing import Process, JoinableQueue as Queue 

class CustomWorker(Process):
    def __init__(self,workQueue, out1,out2,out3):
        Process.__init__(self)
        self.input=workQueue
        self.out1=out1
        self.out2=out2
        self.out3=out3
    def run(self):
            while True:
                try:
                    value = self.input.get()
                    #value modifier
                    temp1,temp2,temp3 = self.calc_stuff(value)
                    self.out1.put(temp1)
                    self.out2.put(temp2)
                    self.out3.put(temp3)
                    self.input.task_done()
                except Queue.Empty:
                    return
                   #Catch things better here
    def calc_stuff(self,param):
        out1 = param * 2
        out2 = param * 4
        out3 = param * 8
        return out1,out2,out3
def Main():
    inputQueue = Queue()
    for i in range(10):
        inputQueue.put(i)
    out1 = Queue()
    out2 = Queue()
    out3 = Queue()
    processes = []
    for x in range(2):
          p = CustomWorker(inputQueue,out1,out2,out3)
          p.daemon = True
          p.start()
          processes.append(p)
    inputQueue.join()
    while(not out1.empty()):
        print out1.get()
        print out2.get()
        print out3.get()
if __name__ == '__main__':
    Main()

Hope that helps.

Use the auto keyword in C++ STL

It's additional information, and isn't an answer.

In C++11 you can write:

for (auto& it : s) {
    cout << it << endl;
}

instead of

for (auto it = s.begin(); it != s.end(); it++) {
    cout << *it << endl;
}

It has the same meaning.

Update: See the @Alnitak's comment also.

How can I delete all of my Git stashes at once?

if you want to remove the latest stash or at any particular index -

git stash drop type_your_index

> git stash list

  stash@{0}: abc
  stash@{1}: xyz
  stash@{1}: pqr

> git stash drop 0

  Dropped refs/stash@{0}

> git stash list

  stash@{0}: xyz
  stash@{1}: pqr

if you want to remove all the stash at once -

> git stash clear
>

> git stash list
>

Warning : Once done you can not revert back your stash

Python division

You need to change it to a float BEFORE you do the division. That is:

float(20 - 10) / (100 - 10)

How do I create a comma-separated list using a SQL query?

From next version of SQL Server you will be able to do

SELECT r.name,
       STRING_AGG(a.name, ',')
FROM   RESOURCES r
       JOIN APPLICATIONSRESOURCES ar
         ON ar.resource_id = r.id
       JOIN APPLICATIONS a
         ON a.id = ar.app_id
GROUP  BY r.name 

For previous versions of the product there are quite a wide variety of different approaches to this problem. An excellent review of them is in the article: Concatenating Row Values in Transact-SQL.

  • Concatenating values when the number of items are not known

    • Recursive CTE method
    • The blackbox XML methods
    • Using Common Language Runtime
    • Scalar UDF with recursion
    • Table valued UDF with a WHILE loop
    • Dynamic SQL
    • The Cursor approach
      .
  • Non-reliable approaches

    • Scalar UDF with t-SQL update extension
    • Scalar UDF with variable concatenation in SELECT

Dismissing a Presented View Controller

I think Apple are covering their backs a little here for a potentially kludgy piece of API.

  [self dismissViewControllerAnimated:NO completion:nil]

Is actually a bit of a fiddle. Although you can - legitimately - call this on the presented view controller, all it does is forward the message on to the presenting view controller. If you want to do anything over and above just dismissing the VC, you will need to know this, and you need to treat it much the same way as a delegate method - as that's pretty much what it is, a baked-in somewhat inflexible delegate method.

Perhaps they've come across loads of bad code by people not really understanding how this is put together, hence their caution.

But of course, if all you need to do is dismiss the thing, go ahead.

My own approach is a compromise, at least it reminds me what is going on:

  [[self presentingViewController] dismissViewControllerAnimated:NO completion:nil]

[Swift]

  self.presentingViewController?.dismiss(animated: false, completion:nil)

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

How do I get an empty array of any size in python?

You can't do exactly what you want in Python (if I read you correctly). You need to put values in for each element of the list (or as you called it, array).

But, try this:

a = [0 for x in range(N)]  # N = size of list you want
a[i] = 5  # as long as i < N, you're okay

For lists of other types, use something besides 0. None is often a good choice as well.

How to set default value for form field in Symfony2?

If you're using a FormBuilder in symfony 2.7 to generate the form, you can also pass the initial data to the createFormBuilder method of the Controler

$values = array(
    'name' => "Bob"
);

$formBuilder = $this->createFormBuilder($values);
$formBuilder->add('name', 'text');

How might I extract the property values of a JavaScript object into an array?

With jQuery, you can do it like this -

var dataArray = $.map(dataObject,function(v){
     return v;
});

Demo

What is the better API to Reading Excel sheets in java - JXL or Apache POI

I have used POI.

If you use that, keep on eye those cell formatters: create one and use it several times instead of creating each time for cell, it isa huge memory consumption difference or large data.

how to declare global variable in SQL Server..?

I like the approach of using a table with a column for each global variable. This way you get autocomplete to aid in coding the retrieval of the variable. The table can be restricted to a single row as outlined here: SQL Server: how to constrain a table to contain a single row?

Getting an Embedded YouTube Video to Auto Play and Loop

Here is the full list of YouTube embedded player parameters.

Relevant info:

autoplay (supported players: AS3, AS2, HTML5) Values: 0 or 1. Default is 0. Sets whether or not the initial video will autoplay when the player loads.

loop (supported players: AS3, HTML5) Values: 0 or 1. Default is 0. In the case of a single video player, a setting of 1 will cause the player to play the initial video again and again. In the case of a playlist player (or custom player), the player will play the entire playlist and then start again at the first video.

Note: This parameter has limited support in the AS3 player and in IFrame embeds, which could load either the AS3 or HTML5 player. Currently, the loop parameter only works in the AS3 player when used in conjunction with the playlist parameter. To loop a single video, set the loop parameter value to 1 and set the playlist parameter value to the same video ID already specified in the Player API URL:

http://www.youtube.com/v/VIDEO_ID?version=3&loop=1&playlist=VIDEO_ID

Use the URL above in your embed code (append other parameters too).

Why is there still a row limit in Microsoft Excel?

In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.

List of ANSI color escape sequences

For these who don't get proper results other than mentioned languages, if you're using C# to print a text into console(terminal) window you should replace "\033" with "\x1b". In Visual Basic it would be Chrw(27).

How can I extract audio from video with ffmpeg?

Use -b:a instead of -ab as -ab is outdated now, also make sure your input file path is correct.

To extract audio from a video I have used below command and its working fine.

String[] complexCommand = {"-y", "-i", inputFileAbsolutePath, "-vn", "-ar", "44100", "-ac", "2", "-b:a", "256k", "-f", "mp3", outputFileAbsolutePath};

Here,

  • -y - Overwrite output files without asking.
  • -i - FFmpeg reads from an arbitrary number of input “files” specified by the -i option
  • -vn - Disable video recording
  • -ar - sets the sampling rate for audio streams if encoded
  • -ac - Set the number of audio channels.
  • -b:a - Set the audio bitrate
  • -f - format

Check out this for my complete sample FFmpeg android project on GitHub.

Commit history on remote repository

git log remotename/branchname

Will display the log of a given remote branch in that repository, but only the logs that you have "fetched" from their repository to your personal "copy" of the remote repository.

Remember that your clone of the repository will update its state of any remote branches only by doing git fetch. You can't connect directly to the server to check the log there, what you do is download the state of the server with git fetch and then locally see the log of the remote branches.

Perhaps another useful command could be:

git log HEAD..remote/branch

which will show you the commits that are in the remote branch, but not in your current branch (HEAD).

Event listener for when element becomes visible?

Going forward, the new HTML Intersection Observer API is the thing you're looking for. It allows you to configure a callback that is called whenever one element, called the target, intersects either the device viewport or a specified element. It's available in latest versions of Chrome, Firefox and Edge. See https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API for more info.

Simple code example for observing display:none switching:

// Start observing visbility of element. On change, the
//   the callback is called with Boolean visibility as
//   argument:

function respondToVisibility(element, callback) {
  var options = {
    root: document.documentElement,
  };

  var observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      callback(entry.intersectionRatio > 0);
    });
  }, options);

  observer.observe(element);
}

In action: https://jsfiddle.net/elmarj/u35tez5n/5/

Split pandas dataframe in two if it has more than 10 rows

You can use the DataFrame head and tail methods as syntactic sugar instead of slicing/loc here. I use a split size of 3; for your example use headSize=10

def split(df, headSize) :
    hd = df.head(headSize)
    tl = df.tail(len(df)-headSize)
    return hd, tl

df = pd.DataFrame({    'A':[2,4,6,8,10,2,4,6,8,10],
                       'B':[10,-10,0,20,-10,10,-10,0,20,-10],
                       'C':[4,12,8,0,0,4,12,8,0,0],
                      'D':[9,10,0,1,3,np.nan,np.nan,np.nan,np.nan,np.nan]})

# Split dataframe into top 3 rows (first) and the rest (second)
first, second = split(df, 3)

Parsing JSON from URL

A simple alternative solution:

  • Paste the URL into a json to csv converter

  • Open the CSV file in either Excel or Open Office

  • Use the spreadsheet tools to parse the data

Maximum concurrent connections to MySQL

You might have 10,000 users total, but that's not the same as concurrent users. In this context, concurrent scripts being run.

For example, if your visitor visits index.php, and it makes a database query to get some user details, that request might live for 250ms. You can limit how long those MySQL connections live even further by opening and closing them only when you are querying, instead of leaving it open for the duration of the script.

While it is hard to make any type of formula to predict how many connections would be open at a time, I'd venture the following:

You probably won't have more than 500 active users at any given time with a user base of 10,000 users. Of those 500 concurrent users, there will probably at most be 10-20 concurrent requests being made at a time.

That means, you are really only establishing about 10-20 concurrent requests.

As others mentioned, you have nothing to worry about in that department.

How to get the path of the batch script in Windows?

%~dp0 may be a relative path. To convert it to a full path, try something like this:

pushd %~dp0
set script_dir=%CD%
popd

Changing file permission in Python

Simply include permissions integer in octal (works for both python 2 and python3):

os.chmod(path, 0o444)

How to Return partial view of another controller by controller?

The control searches for a view in the following order:

  • First in shared folder
  • Then in the folder matching the current controller (in your case it's Views/DEF)

As you do not have xxx.cshtml in those locations, it returns a "view not found" error.

Solution: You can use the complete path of your view:

Like

 PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

How to display HTML tags as plain text

Use htmlentities() to convert characters that would otherwise be displayed as HTML.

Activate tabpage of TabControl

You can use the method SelectTab.

There are 3 versions:

public void SelectTab(int index);
public void SelectTab(string tabPageName);
public void SelectTab(TabPage tabPage);

Among $_REQUEST, $_GET and $_POST which one is the fastest?

I would use the second method as it is more explicit. Otherwise you don't know where the variables are coming from.

Why do you need to check both GET and POST anyway? Surely using one or the other only makes more sense.

Check if page gets reloaded or refreshed in JavaScript

if

event.currentTarget.performance.navigation.type

returns

0 => user just typed in an Url
1 => page reloaded
2 => back button clicked.

Get UserDetails object from Security Context in Spring MVC controller

if you are using spring security then you can get the current logged in user by

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
     String name = auth.getName(); //get logged in username

What's the best free C++ profiler for Windows?

CodeXL has now superseded the End Of Line'd AMD Code Analyst and both are free, but not as advanced as VTune.

There's also Sleepy, which is very simple, but does the job in many cases.

Note: All three of the tools above are unmaintained since several years.

Calculating a directory's size using Python?

def recursive_dir_size(path):
    size = 0

    for x in os.listdir(path):
        if not os.path.isdir(os.path.join(path,x)):
            size += os.stat(os.path.join(path,x)).st_size
        else:
            size += recursive_dir_size(os.path.join(path,x))

    return size

I wrote this function which gives me accurate overall size of a directory, i tried other for loop solutions with os.walk but i don't know why the end result was always less than the actual size (on ubuntu 18 env). I must have done something wrong but who cares wrote this one works perfectly fine.

How can I replace text with CSS?

Try using :before and :after. One inserts text after HTML is rendered, and the other inserts before HTML is rendered. If you want to replace text, leave button content empty.

This example sets the button text according to the size of the screen width.

<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
  button:before {
    content: 'small screen';
  }
  @media screen and (min-width: 480px) {
    button:before {
      content: 'big screen';
    }
  }
</style>
<body>
  <button type="button">xxx</button>
  <button type="button"></button>
</body>

Button text:

  1. With :before

    big screenxxx

    big screen

  2. With :after

    xxxbig screen

    big screen

equivalent of rm and mv in windows .cmd

If you want to see a more detailed discussion of differences for the commands, see the Details about Differences section, below.

From the LeMoDa.net website1 (archived), specifically the Windows and Unix command line equivalents page (archived), I found the following2. There's a better/more complete table in the next edit.

Windows command     Unix command
rmdir               rmdir
rmdir /s            rm -r
move                mv

I'm interested to hear from @Dave and @javadba to hear how equivalent the commands are - how the "behavior and capabilities" compare, whether quite similar or "woefully NOT equivalent".

All I found out was that when I used it to try and recursively remove a directory and its constituent files and subdirectories, e.g.

(Windows cmd)>rmdir /s C:\my\dirwithsubdirs\

gave me a standard Windows-knows-better-than-you-do-are-you-sure message and prompt

dirwithsubdirs, Are you sure (Y/N)?

and that when I typed Y, the result was that my top directory and its constituent files and subdirectories went away.


Edit

I'm looking back at this after finding this answer. I retried each of the commands, and I'd change the table a little bit.

Windows command     Unix command
rmdir               rmdir
rmdir /s /q         rm -r
rmdir /s /q         rm -rf
rmdir /s            rm -ri
move                mv
del <file>          rm <file>

If you want the equivalent for

rm -rf

you can use

rmdir /s /q

or, as the author of the answer I sourced described,

But there is another "old school" way to do it that was used back in the day when commands did not have options to suppress confirmation messages. Simply ECHO the needed response and pipe the value into the command.

echo y | rmdir /s


Details about Differences

I tested each of the commands using Windows CMD and Cygwin (with its bash).

Before each test, I made the following setup.

Windows CMD

>mkdir this_directory
>echo some text stuff > this_directory/some.txt
>mkdir this_empty_directory

Cygwin bash

$ mkdir this_directory
$ echo "some text stuff" > this_directory/some.txt
$ mkdir this_empty_directory

That resulted in the following file structure for both.

base
|-- this_directory
|   `-- some.txt
`-- this_empty_directory

Here are the results. Note that I'll not mark each as CMD or bash; the CMD will have a > in front, and the bash will have a $ in front.

RMDIR

>rmdir this_directory
The directory is not empty.

>tree /a /f .
Folder PATH listing for volume Windows
Volume serial number is ¦¦¦¦¦¦¦¦ ¦¦¦¦:¦¦¦¦
base
+---this_directory
|       some.txt
|
\---this_empty_directory

> rmdir this_empty_directory

>tree /a /f .
base
\---this_directory
        some.txt
$ rmdir this_directory
rmdir: failed to remove 'this_directory': Directory not empty

$ tree --charset=ascii
base
|-- this_directory
|   `-- some.txt
`-- this_empty_directory

2 directories, 1 file

$ rmdir this_empty_directory

$ tree --charset=ascii
base
`-- this_directory
    `-- some.txt

RMDIR /S /Q and RM -R ; RM -RF

>rmdir /s /q this_directory

>tree /a /f
base
\---this_empty_directory

>rmdir /s /q this_empty_directory

>tree /a /f
base
No subfolders exist
$ rm -r this_directory

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -r this_empty_directory

$ tree --charset=ascii
base
0 directories, 0 files
$ rm -rf this_directory

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -rf this_empty_directory

$ tree --charset=ascii
base
0 directories, 0 files

RMDIR /S AND RM -RI Here, we have a bit of a difference, but they're pretty close.

>rmdir /s this_directory
this_directory, Are you sure (Y/N)? y

>tree /a /f
base
\---this_empty_directory

>rmdir /s this_empty_directory
this_empty_directory, Are you sure (Y/N)? y

>tree /a /f
base
No subfolders exist
$ rm -ri this_directory
rm: descend into directory 'this_directory'? y
rm: remove regular file 'this_directory/some.txt'? y
rm: remove directory 'this_directory'? y

$ tree --charset=ascii
base
`-- this_empty_directory

$ rm -ri this_empty_directory
rm: remove directory 'this_empty_directory'? y

$ tree --charset=ascii
base
0 directories, 0 files

I'M HOPING TO GET A MORE THOROUGH MOVE AND MV TEST


Notes

  1. I know almost nothing about the LeMoDa website, other than the fact that the info is

Copyright © Ben Bullock 2009-2018. All rights reserved.

(archived copyright notice)

and that there seem to be a bunch of useful programming tips along with some humour (yes, the British spelling) and information on how to fix Japanese toilets. I also found some stuff talking about the "Ibaraki Report", but I don't know if that is the website.

I think I shall go there more often; it's quite useful. Props to Ben Bullock, whose email is on his page. If he wants me to remove this info, I will.

I will include the disclaimer (archived) from the site:

Disclaimer Please read the following disclaimer before using any of the computer program code on this site.

There Is No Warranty For The Program, To The Extent Permitted By Applicable Law. Except When Otherwise Stated In Writing The Copyright Holders And/Or Other Parties Provide The Program “As Is” Without Warranty Of Any Kind, Either Expressed Or Implied, Including, But Not Limited To, The Implied Warranties Of Merchantability And Fitness For A Particular Purpose. The Entire Risk As To The Quality And Performance Of The Program Is With You. Should The Program Prove Defective, You Assume The Cost Of All Necessary Servicing, Repair Or Correction.

In No Event Unless Required By Applicable Law Or Agreed To In Writing Will Any Copyright Holder, Or Any Other Party Who Modifies And/Or Conveys The Program As Permitted Above, Be Liable To You For Damages, Including Any General, Special, Incidental Or Consequential Damages Arising Out Of The Use Or Inability To Use The Program (Including But Not Limited To Loss Of Data Or Data Being Rendered Inaccurate Or Losses Sustained By You Or Third Parties Or A Failure Of The Program To Operate With Any Other Programs), Even If Such Holder Or Other Party Has Been Advised Of The Possibility Of Such Damages.


  1. Actually, I found the information with a Google search for "cmd equivalent of rm"

https://www.google.com/search?q=cmd+equivalent+of+rm

The information I'm sharing came up first.

How to remove package using Angular CLI?

With the cli I don't know if it's a remove command but you can remove it from package.json and stop using it in your code.If you reinstall the packages you wilk not have it any more

Opacity of div's background without affecting contained element in IE 8?

Maybe there's a more simple answer, try to add any background color you like to the code, like background-color: #fff;

#alpha {
 background-color: #fff;
 opacity: 0.8;
 filter: alpha(opacity=80);
}

How to center a subview of UIView

You can use

yourView.center = CGPointMake(CGRectGetMidX(superview.bounds), CGRectGetMidY(superview.bounds))

And In Swift 3.0

yourView.center = CGPoint(x: superview.bounds.midX, y: superview.bounds.midY)

How to delete cookies on an ASP.NET website

I just want to point out that the Session ID cookie is not removed when using Session.Abandon as others said.

When you abandon a session, the session ID cookie is not removed from the browser of the user. Therefore, as soon as the session has been abandoned, any new requests to the same application will use the same session ID but will have a new session state instance. At the same time, if the user opens another application within the same DNS domain, the user will not lose their session state after the Abandon method is called from one application.

Sometimes, you may not want to reuse the session ID. If you do and if you understand the ramifications of not reusing the session ID, use the following code example to abandon a session and to clear the session ID cookie:

Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));

This code example clears the session state from the server and sets the session state cookie to null. The null value effectively clears the cookie from the browser.

http://support.microsoft.com/kb/899918

How to get current date & time in MySQL?

Even though there are many accepted answers, I think this way is also possible:

Create your 'servers' table as following :

CREATE TABLE `servers`
(
      id int(11) NOT NULL PRIMARY KEY auto_increment,
      server_name varchar(45) NOT NULL,
      online_status varchar(45) NOT NULL,
      _exchange varchar(45) NOT NULL, 
      disk_space varchar(45) NOT NULL,
      network_shares varchar(45) NOT NULL,
      date_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
);

And your INSERT statement should be :

INSERT INTO servers (server_name, online_status, _exchange, disk_space, network_shares)
VALUES('m1', 'ONLINE', 'ONLINE', '100GB', 'ONLINE');

My Environment:

Core i3 Windows Laptop with 4GB RAM, and I did the above example on MySQL Workbench 6.2 (Version 6.2.5.0 Build 397 64 Bits)

How to get html table td cell value by JavaScript?

Don't use in-line JavaScript, separate your behaviour from your data and it gets much easier to handle. I'd suggest the following:

var table = document.getElementById('tableID'),
    cells = table.getElementsByTagName('td');

for (var i=0,len=cells.length; i<len; i++){
    cells[i].onclick = function(){
        console.log(this.innerHTML);
        /* if you know it's going to be numeric:
        console.log(parseInt(this.innerHTML),10);
        */
    }
}

_x000D_
_x000D_
var table = document.getElementById('tableID'),_x000D_
  cells = table.getElementsByTagName('td');_x000D_
_x000D_
for (var i = 0, len = cells.length; i < len; i++) {_x000D_
  cells[i].onclick = function() {_x000D_
    console.log(this.innerHTML);_x000D_
  };_x000D_
}
_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  padding: 0.2em 0.3em 0.1em 0.3em;_x000D_
}
_x000D_
<table id="tableID">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column heading 1</th>_x000D_
      <th>Column heading 2</th>_x000D_
      <th>Column heading 3</th>_x000D_
      <th>Column heading 4</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>43</td>_x000D_
      <td>23</td>_x000D_
      <td>89</td>_x000D_
      <td>5</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>3</td>_x000D_
      <td>0</td>_x000D_
      <td>98</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>10</td>_x000D_
      <td>32</td>_x000D_
      <td>7</td>_x000D_
      <td>2</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS Fiddle proof-of-concept.

A revised approach, in response to the comment (below):

You're missing a semicolon. Also, don't make functions within a loop.

This revision binds a (single) named function as the click event-handler of the multiple <td> elements, and avoids the unnecessary overhead of creating multiple anonymous functions within a loop (which is poor practice due to repetition and the impact on performance, due to memory usage):

function logText() {
  // 'this' is automatically passed to the named
  // function via the use of addEventListener()
  // (later):
  console.log(this.textContent);
}

// using a CSS Selector, with document.querySelectorAll()
// to get a NodeList of <td> elements within the #tableID element:
var cells = document.querySelectorAll('#tableID td');

// iterating over the array-like NodeList, using
// Array.prototype.forEach() and Function.prototype.call():
Array.prototype.forEach.call(cells, function(td) {
  // the first argument of the anonymous function (here: 'td')
  // is the element of the array over which we're iterating.

  // adding an event-handler (the function logText) to handle
  // the click events on the <td> elements:
  td.addEventListener('click', logText);
});

_x000D_
_x000D_
function logText() {_x000D_
  console.log(this.textContent);_x000D_
}_x000D_
_x000D_
var cells = document.querySelectorAll('#tableID td');_x000D_
_x000D_
Array.prototype.forEach.call(cells, function(td) {_x000D_
  td.addEventListener('click', logText);_x000D_
});
_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #000;_x000D_
  padding: 0.2em 0.3em 0.1em 0.3em;_x000D_
}
_x000D_
<table id="tableID">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column heading 1</th>_x000D_
      <th>Column heading 2</th>_x000D_
      <th>Column heading 3</th>_x000D_
      <th>Column heading 4</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>43</td>_x000D_
      <td>23</td>_x000D_
      <td>89</td>_x000D_
      <td>5</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>3</td>_x000D_
      <td>0</td>_x000D_
      <td>98</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>10</td>_x000D_
      <td>32</td>_x000D_
      <td>7</td>_x000D_
      <td>2</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS Fiddle proof-of-concept.

References:

Solutions for INSERT OR UPDATE on SQL Server

In SQL Server 2008 you can use the MERGE statement

Can't install any packages in Node.js using "npm install"

I found the there is a certificate expired issue with:

npm set registry https://registry.npmjs.org/

So I made it http, not https :-

npm set registry http://registry.npmjs.org/

And have no problems so far.

How to find a value in an array of objects in JavaScript?

I had to search a nested sitemap structure for the first leaf item that machtes a given path. I came up with the following code just using .map() .filter() and .reduce. Returns the last item found that matches the path /c.

var sitemap = {
  nodes: [
    {
      items: [{ path: "/a" }, { path: "/b" }]
    },
    {
      items: [{ path: "/c" }, { path: "/d" }]
    },
    {
      items: [{ path: "/c" }, { path: "/d" }]
    }
  ]
};

const item = sitemap.nodes
  .map(n => n.items.filter(i => i.path === "/c"))
  .reduce((last, now) => last.concat(now))
  .reduce((last, now) => now);

Edit 4n4904z07

Eclipse: Enable autocomplete / content assist

For anyone having this problem with newer versions of Eclipse, head over to Window->Preferences->Java->Editor->Content assist->Advanced and mark Java Proposals and Chain Template Proposals as active.

Initializing C dynamic arrays

You cannot use the syntax you have suggested. If you have a C99 compiler, though, you can do this:

int *p;

p = malloc(3 * sizeof p[0]);
memcpy(p, (int []){ 0, 1, 2 }, 3 * sizeof p[0]);

If your compiler does not support C99 compound literals, you need to use a named template to copy from:

int *p;

p = malloc(3 * sizeof p[0]);
{
    static const int p_init[] = { 0, 1, 2 };
    memcpy(p, p_init, 3 * sizeof p[0]);
}

How do I find which transaction is causing a "Waiting for table metadata lock" state?

mysql 5.7 exposes metadata lock information through the performance_schema.metadata_locks table.

Documentation here

jquery - is not a function error

In my case, the same error had a much easier fix. Basically my function was in a .js file that was not included in the current aspx that was showing. All I needed was the include line.

Random number c++ in some range

int range = max - min + 1;
int num = rand() % range + min;

jquery disable form submit on enter

Usually form is submitted on Enter when you have focus on input elements.

We can disable Enter key (code 13) on input elements within a form:

$('form input').on('keypress', function(e) {
    return e.which !== 13;
});

DEMO: http://jsfiddle.net/bnx96/325/

What's the easiest way to escape HTML in Python?

In Python 3.2 a new html module was introduced, which is used for escaping reserved characters from HTML markup.

It has one function escape():

>>> import html
>>> html.escape('x > 2 && x < 7 single quote: \' double quote: "')
'x &gt; 2 &amp;&amp; x &lt; 7 single quote: &#x27; double quote: &quot;'

How to exit from Python without traceback?

# Pygame Example  

import pygame, sys  
from pygame.locals import *

pygame.init()  
DISPLAYSURF = pygame.display.set_mode((400, 300))  
pygame.display.set_caption('IBM Emulator')

BLACK = (0, 0, 0)  
GREEN = (0, 255, 0)

fontObj = pygame.font.Font('freesansbold.ttf', 32)  
textSurfaceObj = fontObj.render('IBM PC Emulator', True, GREEN,BLACK)  
textRectObj = textSurfaceObj.get_rect()  
textRectObj = (10, 10)

try:  
    while True: # main loop  
        DISPLAYSURF.fill(BLACK)  
        DISPLAYSURF.blit(textSurfaceObj, textRectObj)  
        for event in pygame.event.get():  
            if event.type == QUIT:  
                pygame.quit()  
                sys.exit()  
        pygame.display.update()  
except SystemExit:  
    pass

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do it using group by:

c_maxes = df.groupby(['A', 'B']).C.transform(max)
df = df.loc[df.C == c_maxes]

c_maxes is a Series of the maximum values of C in each group but which is of the same length and with the same index as df. If you haven't used .transform then printing c_maxes might be a good idea to see how it works.

Another approach using drop_duplicates would be

df.sort('C').drop_duplicates(subset=['A', 'B'], take_last=True)

Not sure which is more efficient but I guess the first approach as it doesn't involve sorting.

EDIT: From pandas 0.18 up the second solution would be

df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')

or, alternatively,

df.sort_values('C', ascending=False).drop_duplicates(subset=['A', 'B'])

In any case, the groupby solution seems to be significantly more performing:

%timeit -n 10 df.loc[df.groupby(['A', 'B']).C.max == df.C]
10 loops, best of 3: 25.7 ms per loop

%timeit -n 10 df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')
10 loops, best of 3: 101 ms per loop

Java JSON serialization - best practice

Are you tied to this library? Google Gson is very popular. I have myself not used it with Generics but their front page says Gson considers support for Generics very important.

How to round the corners of a button

Pushing to the limits corner radius up to get a circle:

    self.btnFoldButton.layer.cornerRadius = self.btnFoldButton.frame.height/2.0;

enter image description here

If button frame is an square it does not matter frame.height or frame.width. Otherwise use the largest of both ones.

Is there a way to do repetitive tasks at intervals?

If you do not care about tick shifting (depending on how long did it took previously on each execution) and you do not want to use channels, it's possible to use native range function.

i.e.

package main

import "fmt"
import "time"

func main() {
    go heartBeat()
    time.Sleep(time.Second * 5)
}

func heartBeat() {
    for range time.Tick(time.Second * 1) {
        fmt.Println("Foo")
    }
}

Playground

Unicode character as bullet for list-item in CSS

ul {
    list-style-type: none;    
}

ul li:before {
    content:'*'; /* Change this to unicode as needed*/
    width: 1em !important;
    margin-left: -1em;
    display: inline-block;
}

Using {% url ??? %} in django templates

Make sure (django 1.5 and beyond) that you put the url name in quotes, and if your url takes parameters they should be outside of the quotes (I spent hours figuring out this mistake!).

{% url 'namespace:view_name' arg1=value1 arg2=value2 as the_url %}
<a href="{{ the_url }}"> link_name </a>

What is the difference between "long", "long long", "long int", and "long long int" in C++?

While in Java a long is always 64 bits, in C++ this depends on computer architecture and operating system. For example, a long is 64 bits on Linux and 32 bits on Windows (this was done to keep backwards-compatability, allowing 32-bit programs to compile on 64-bit Windows without any changes).

It is considered good C++ style to avoid short int long ... and instead use:

std::int8_t   # exactly  8 bits
std::int16_t  # exactly 16 bits
std::int32_t  # exactly 32 bits
std::int64_t  # exactly 64 bits

std::size_t   # can hold all possible object sizes, used for indexing

These (int*_t) can be used after including the <cstdint> header. size_t is in <stdlib.h>.

How can we stop a running java process through Windows cmd?

Normally I don't have that many Java processes open so

taskkill /im javaw.exe

or

taskkill /im java.exe

should suffice. This will kill all instances of Java, though.

New lines inside paragraph in README.md

Interpreting newlines as <br /> used to be a feature of Github-flavored markdown, but the most recent help document no longer lists this feature.

Fortunately, you can do it manually. The easiest way is to ensure that each line ends with two spaces. So, change

a
b
c

into

a__
b__
c

(where _ is a blank space).

Or, you can add explicit <br /> tags.

a <br />
b <br />
c

how to draw a rectangle in HTML or CSS?

I do the following in my eBay listings:

<p style="border:solid thick darkblue; border-radius: 1em; 
          border-width:3px; padding-left:9px; padding-top:6px; 
          padding-bottom:6px; margin:2px; width:980px;">

This produces a box border with rounded corners.You can play with the variables.

C99 stdint.h header and MS Visual Studio

Boost contains cstdint.hpp header file with the types you are looking for: http://www.boost.org/doc/libs/1_36_0/boost/cstdint.hpp

Filtering a list based on a list of booleans

You're looking for itertools.compress:

>>> from itertools import compress
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> list(compress(list_a, fil))
[1, 4]

Timing comparisons(py3.x):

>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> %timeit list(compress(list_a, fil))
100000 loops, best of 3: 2.58 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]  #winner
100000 loops, best of 3: 1.98 us per loop

>>> list_a = [1, 2, 4, 6]*100
>>> fil = [True, False, True, False]*100
>>> %timeit list(compress(list_a, fil))              #winner
10000 loops, best of 3: 24.3 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
10000 loops, best of 3: 82 us per loop

>>> list_a = [1, 2, 4, 6]*10000
>>> fil = [True, False, True, False]*10000
>>> %timeit list(compress(list_a, fil))              #winner
1000 loops, best of 3: 1.66 ms per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v] 
100 loops, best of 3: 7.65 ms per loop

Don't use filter as a variable name, it is a built-in function.

Using context in a fragment

In kotlin just use activity instead of getActivity()

How to get the row number from a datatable?

If you need the index of the item you're working with then using a foreach loop is the wrong method of iterating over the collection. Change the way you're looping so you have the index:

for(int i = 0; i < dt.Rows.Count; i++)
{
    // your index is in i
    var row = dt.Rows[i];
}

glm rotate usage in Opengl

I noticed that you can also get errors if you don't specify the angles correctly, even when using glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)) you still might run into problems. The fix I found for this was specifying the type as glm::rotate(Model, (glm::mediump_float)90, glm::vec3(x, y, z)) instead of just saying glm::rotate(Model, 90, glm::vec3(x, y, z))

Or just write the second argument, the angle in radians (previously in degrees), as a float with no cast needed such as in:

glm::mat4 rotationMatrix = glm::rotate(glm::mat4(1.0f), 3.14f, glm::vec3(1.0));

You can add glm::radians() if you want to keep using degrees. And add the includes:

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"

How to change package name of Android Project in Eclipse?

I had big trouble with this too.

I renamed the project and the package via refactoring, but it rendered the app useless. I renamed it back to the original and used the Android tools to rename the package and this worked, but my package folder and classes had the old name.

I then refactored the package folder. Now the app wouldn't run. My manifest was a mess. It doubled up my launcher name for example, com.ronguilmet.app/com.ronguilmet.com.class. I fixed that, and I had to manually edit all activities.

How do I get an OAuth 2.0 authentication token in C#

https://github.com/IdentityModel/IdentityModel adds extensions to HttpClient to acquire tokens using different flows and the documentation is great too. It's very handy because you don't have to think how to implement it yourself. I'm not aware if any official MS implementation exists.