Programs & Examples On #Hierarchicaldatatemplate

A `HierarchicalDataTemplate` is a subclass of `DataTemplate` that allows you to bind directly to a hierarchy of objects

Do a "git export" (like "svn export")?

It appears that this is less of an issue with Git than SVN. Git only puts a .git folder in the repository root, whereas SVN puts a .svn folder in every subdirectory. So "svn export" avoids recursive command-line magic, whereas with Git recursion is not necessary.

How can I determine whether a 2D Point is within a Polygon?

This seems to work in R (apologies for ugliness, would like to see better version!).

pnpoly <- function(nvert,vertx,verty,testx,testy){
          c <- FALSE
          j <- nvert 
          for (i in 1:nvert){
              if( ((verty[i]>testy) != (verty[j]>testy)) && 
   (testx < (vertx[j]-vertx[i])*(testy-verty[i])/(verty[j]-verty[i])+vertx[i]))
            {c <- !c}
             j <- i}
   return(c)}

stop all instances of node.js server

Linux

To impress your friends

ps aux | grep -i node | awk '{print $2}' | xargs  kill -9

But this is the one you will remember

killall node

How to terminate a window in tmux?

Lot's of different ways to do this, but my favorite is simply typing 'exit' on the bash prompt.

Browse and display files in a git repo without cloning

While you have to checkout a repository, you can skip checking out any files with --no-checkout and --depth 1:

$ time git clone --no-checkout --depth 1 https://github.com/torvalds/linux .
Cloning into '.'...
remote: Enumerating objects: 75646, done.
remote: Counting objects: 100% (75646/75646), done.
remote: Compressing objects: 100% (71197/71197), done.
remote: Total 75646 (delta 6176), reused 22237 (delta 3672), pack-reused 0
Receiving objects: 100% (75646/75646), 201.46 MiB | 7.27 MiB/s, done.
Resolving deltas: 100% (6176/6176), done.

real    0m46.117s
user    0m13.412s
sys     0m19.641s

And while there is only a .git directory:

$ ls -al
total 0
drwxr-xr-x   3 root  staff    96 Dec 26 23:57 .
drwxr-xr-x+ 71 root  staff  2272 Dec 27 00:03 ..
drwxr-xr-x  12 root  staff   384 Dec 26 23:58 .git

you can get a directory listing via:

$ git ls-tree --full-name --name-only -r HEAD | head
.clang-format
.cocciconfig
.get_maintainer.ignore
.gitattributes
.gitignore
.mailmap
COPYING
CREDITS
Documentation/.gitignore
Documentation/ABI/README

or get the number of files via:

$ git ls-tree -r HEAD | wc -l
   71259

or get the total file size via:

$ git ls-tree -l -r HEAD | awk '/^[^-]/ {s+=$4} END {print s}'
1006679487

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

How to access site running apache server over lan without internet connection

if you did change the httpd.conf file located under conf_files folder, don't use windows notepad, you need a unix text editor, try TED pad, after making any changes to your httpd.conf file save it. ps: if you use a dos/windows editor you will end up with an "Error in Apache file changed" message. so do be careful.... Salam

Avoid trailing zeroes in printf()

To get rid of the trailing zeros, you should use the "%g" format:

float num = 1.33;
printf("%g", num); //output: 1.33

After the question was clarified a bit, that suppressing zeros is not the only thing that was asked, but limiting the output to three decimal places was required as well. I think that can't be done with sprintf format strings alone. As Pax Diablo pointed out, string manipulation would be required.

Why boolean in Java takes only true or false? Why not 1 or 0 also?

Because the people who created Java wanted boolean to mean unambiguously true or false, not 1 or 0.

There's no consensus among languages about how 1 and 0 convert to booleans. C uses any nonzero value to mean true and 0 to mean false, but some UNIX shells do the opposite. Using ints weakens type-checking, because the compiler can't guard against cases where the int value passed in isn't something that should be used in a boolean context.

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

How do operator.itemgetter() and sort() work?

Answer for Python beginners

In simpler words:

  1. The key= parameter of sort requires a key function (to be applied to be objects to be sorted) rather than a single key value and
  2. that is just what operator.itemgetter(1) will give you: A function that grabs the first item from a list-like object.

(More precisely those are callables, not functions, but that is a difference that can often be ignored.)

How to calculate a time difference in C++

In Windows: use GetTickCount

//GetTickCount defintition
#include <windows.h>
int main()
{

    DWORD dw1 = GetTickCount();

    //Do something 

    DWORD dw2 = GetTickCount();

    cout<<"Time difference is "<<(dw2-dw1)<<" milliSeconds"<<endl;

}

Node.js/Express.js App Only Works on Port 3000

Try this

$ PORT=8080 node app.js

Is there a regular expression to detect a valid regular expression?

No, if you use standard regular expressions.

The reason is that you cannot satisfy the pumping lemma for regular languages. The pumping lemma states that a string belonging to language "L" is regular if there exists a number "N" such that, after dividing the string into three substrings x, y, z, such that |x|>=1 && |xy|<=N, you can repeat y as many times as you want and the entire string will still belong to L.

A consequence of the pumping lemma is that you cannot have regular strings in the form a^Nb^Mc^N, that is, two substrings having the same length separated by another string. In any way you split such strings in x, y and z, you cannot "pump" y without obtaining a string with a different number of "a" and "c", thus leaving the original language. That's the case, for example, with parentheses in regular expressions.

How to remove text before | character in notepad++

To replace anything that starts with "text" until the last character:

text.+(.*)$

Example

text             hsjh sdjh sd          jhsjhsdjhsdj hsd
                                                      ^
                                                      last character


To replace anything that starts with "text" until "123"

text.+(\ 123)

Example

text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e
^                                   ^
From here                     To here

ajax jquery simple get request

var dataString = "flag=fetchmediaaudio&id="+id;

$.ajax
({
  type: "POST",
  url: "ajax.php",
  data: dataString,
  success: function(html)
  {
     alert(html);
  }
});

Spark: Add column to dataframe conditionally

How about something like this?

val newDF = df.filter($"B" === "").take(1) match {
  case Array() => df
  case _ => df.withColumn("D", $"B" === "")
}

Using take(1) should have a minimal hit

Spring Data JPA Update @Query not updating?

I finally understood what was going on.

When creating an integration test on a statement saving an object, it is recommended to flush the entity manager so as to avoid any false negative, that is, to avoid a test running fine but whose operation would fail when run in production. Indeed, the test may run fine simply because the first level cache is not flushed and no writing hits the database. To avoid this false negative integration test use an explicit flush in the test body. Note that the production code should never need to use any explicit flush as it is the role of the ORM to decide when to flush.

When creating an integration test on an update statement, it may be necessary to clear the entity manager so as to reload the first level cache. Indeed, an update statement completely bypasses the first level cache and writes directly to the database. The first level cache is then out of sync and reflects the old value of the updated object. To avoid this stale state of the object, use an explicit clear in the test body. Note that the production code should never need to use any explicit clear as it is the role of the ORM to decide when to clear.

My test now works just fine.

Django DoesNotExist

The solution that i believe is best and optimized is:

try:
   #your code
except "ModelName".DoesNotExist:
   #your code

How to add one day to a date?

To make it a touch less java specific, the basic principle would be to convert to some linear date format, julian days, modified julian days, seconds since some epoch, etc, add your day, and convert back.

The reason for doing this is that you farm out the "get the leap day, leap second, etc right' problem to someone who has, with some luck, not mucked this problem up.

I will caution you that getting these conversion routines right can be difficult. There are an amazing number of different ways that people mess up time, the most recent high profile example was MS's Zune. Dont' poke too much fun at MS though, it's easy to mess up. It doesn't help that there are multiple different time formats, say, TAI vs TT.

Getting Chrome to accept self-signed localhost certificate

I fixed this problem for myself without changing the settings on any browsers with proper SSL certifications. I use a mac so it required a keychain update to my ssl certifications. I had to add subject alt names to the ssl certification for chrome to accept it. As of today, this is for Chrome version number: 62.0.3202.94

My example are easy to use commands and config files:

add these files and this example is all in one root directory

ssl.conf

[ req ]
default_bits       = 4096
distinguished_name = req_distinguished_name
req_extensions     = req_ext

[ req_distinguished_name ]
countryName                 = Country Name (2 letter code)
stateOrProvinceName         = State or Province Name (full name)
localityName                = Locality Name (eg, city)
organizationName            = Organization Name (eg, company)
commonName                  = Common Name (e.g. server FQDN or YOUR name)
commonName_max              = 64

[ req_ext ]
subjectAltName = @alt_names

[alt_names]
DNS.1   = localhost

Run command to create certification:

openssl req -newkey rsa:4096 -nodes -keyout key.pem -x509 -days 3650 -out certificate.pem -extensions req_ext -config ssl.conf -subj '/CN=localhost/O=Stackflow/C=US/L=Los Angeles/OU=StackflowTech'

For macs only to add trusted certification (required):

sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ./certificate.pem

For windows you will have to find how to verify our ssl certs locally independently. I don't use Windows. Sorry windows guys and gals.

I am using a node.js server with express.js with only requires my key and certification with something like this:

app.js

const https = require('https');
const Express = require('express');
const fs = require('fs');
const app = new Express();
const server = https.createServer({
    key: fs.readFileSync('./key.pem'),
    cert: fs.readFileSync('./certificate.pem'),
}, app);
server.listen(3000);

I may be doing this for other backend frames in the future, so I can update example this for others in the future. But this was my fix in Node.js for that issue. Clear browser cache and run your app on https://

Here's an example of running https://localhost on a Node.js server for Mac users:

https://github.com/laynefaler/Stack-Overflow-running-HTTPS-localhost

Happy Coding!

What's the whole point of "localhost", hosts and ports at all?

Well, others have given a good definition of 'localhost'.

It is kind of a defacto for the text representation of the local IP 127.0.0.1.

You can have 'betterhost', 'otherhost', 'someotherhost' if you use a DNS server that can translate it to working IP addresses, OR by modifying the host file. But that's another topic for another day or better day. :P

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

Deep copy, shallow copy, clone

Unfortunately, "shallow copy", "deep copy" and "clone" are all rather ill-defined terms.


In the Java context, we first need to make a distinction between "copying a value" and "copying an object".

int a = 1;
int b = a;     // copying a value
int[] s = new int[]{42};
int[] t = s;   // copying a value (the object reference for the array above)

StringBuffer sb = new StringBuffer("Hi mom");
               // copying an object.
StringBuffer sb2 = new StringBuffer(sb);

In short, an assignment of a reference to a variable whose type is a reference type is "copying a value" where the value is the object reference. To copy an object, something needs to use new, either explicitly or under the hood.


Now for "shallow" versus "deep" copying of objects. Shallow copying generally means copying only one level of an object, while deep copying generally means copying more than one level. The problem is in deciding what we mean by a level. Consider this:

public class Example {
    public int foo;
    public int[] bar;
    public Example() { };
    public Example(int foo, int[] bar) { this.foo = foo; this.bar = bar; };
}

Example eg1 = new Example(1, new int[]{1, 2});
Example eg2 = ... 

The normal interpretation is that a "shallow" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to the same array as in the original; e.g.

Example eg2 = new Example(eg1.foo, eg1.bar);

The normal interpretation of a "deep" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to a copy of the original array; e.g.

Example eg2 = new Example(eg1.foo, Arrays.copy(eg1.bar));

(People coming from a C / C++ background might say that a reference assignment produces a shallow copy. However, that's not what we normally mean by shallow copying in the Java context ...)

Two more questions / areas of uncertainty exist:

  • How deep is deep? Does it stop at two levels? Three levels? Does it mean the whole graph of connected objects?

  • What about encapsulated data types; e.g. a String? A String is actually not just one object. In fact, it is an "object" with some scalar fields, and a reference to an array of characters. However, the array of characters is completely hidden by the API. So, when we talk about copying a String, does it make sense to call it a "shallow" copy or a "deep" copy? Or should we just call it a copy?


Finally, clone. Clone is a method that exists on all classes (and arrays) that is generally thought to produce a copy of the target object. However:

  • The specification of this method deliberately does not say whether this is a shallow or deep copy (assuming that is a meaningful distinction).

  • In fact, the specification does not even specifically state that clone produces a new object.

Here's what the javadoc says:

"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression x.clone() != x will be true, and that the expression x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements. While it is typically the case that x.clone().equals(x) will be true, this is not an absolute requirement."

Note, that this is saying that at one extreme the clone might be the target object, and at the other extreme the clone might not equal the original. And this assumes that clone is even supported.

In short, clone potentially means something different for every Java class.


Some people argue (as @supercat does in comments) that the Java clone() method is broken. But I think the correct conclusion is that the concept of clone is broken in the context of OO. AFAIK, it is impossible to develop a unified model of cloning that is consistent and usable across all object types.

Is Python faster and lighter than C++?

I think those stats show that Python is much slower and uses more memory for those benchmarks - are you sure you're reading them the right way up?

In my experience, which is mostly with writing network- and file-system-bound programs in Python, Python isn't significantly slower in any way that matters. For that kind of work, its benefits outweigh its costs.

What are database constraints?

Constraints can be used to enforce specific properties of data. A simple example is to limit an int column to values [0-100000]. This introduction looks good.

Mercurial: how to amend the last commit?

I'm tuning into what krtek has written. More specifically solution 1:

Assumptions:

  • you've committed one (!) changeset but have not pushed it yet
  • you want to modify this changeset (e.g. add, remove or change files and/or the commit message)

Solution:

  • use hg rollback to undo the last commit
  • commit again with the new changes in place

The rollback really undoes the last operation. Its way of working is quite simple: normal operations in HG will only append to files; this includes a commit. Mercurial keeps track of the file lengths of the last transaction and can therefore completely undo one step by truncating the files back to their old lengths.

Any good, visual HTML5 Editor or IDE?

Since HTML5 is still in the works and doesn't have consistant support across any browsers yet, my guess is that it's going to be quite a while before you get a WYSIWYG HTML5 Editor.

In the mean time, get used to editting your markup by hand in a good text editor like Notepad++ or TextEdit.

How to round up integer division and have int result in Java?

Another one-liner that is not too complicated:

private int countNumberOfPages(int numberOfObjects, int pageSize) {
    return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}

Could use long instead of int; just change the parameter types and return type.

cout is not a member of std

add #include <iostream> to the start of io.cpp too.

Why should hash functions use a prime number modulus?

tl;dr

index[hash(input)%2] would result in a collision for half of all possible hashes and a range of values. index[hash(input)%prime] results in a collision of <2 of all possible hashes. Fixing the divisor to the table size also ensures that the number cannot be greater than the table.

How to round up with excel VBA round()?

I am introducing Two custom library functions to be used in vba, which will serve the purpose of rounding the double value instead of using WorkSheetFunction.RoundDown and WorkSheetFunction.RoundUp

Function RDown(Amount As Double, digits As Integer) As Double
    RDown = Int((Amount + (1 / (10 ^ (digits + 1)))) * (10 ^ digits)) / (10 ^ digits)
End Function

Function RUp(Amount As Double, digits As Integer) As Double
    RUp = RDown(Amount + (5 / (10 ^ (digits + 1))), digits)
End Function

Thus function Rdown(2878.75 * 31.1,2) will return 899529.12 and function RUp(2878.75 * 31.1,2) will return 899529.13 Whereas The function Rdown(2878.75 * 31.1,-3) will return 89000 and function RUp(2878.75 * 31.1,-3) will return 90000

Save base64 string as PDF at client side with JavaScript

you can use this function to download file from base64.

function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();}

This code will made an anchor tag with href and download file. if you want to use button then you can call click method on your button click.

i hope this will help of you thanks

How to create hyperlink to call phone number on mobile devices?

- doesnt make matter but + sign is important when mobile user is in roaming
this is the standard format

<a href="tel:+4917640206387">+49 (0)176 - 402 063 87</a>

You can read more about it in the spec, see Make Telephone Numbers "Click-to-Call".

Android EditText Hint

To complete Sunit's answer, you can use a selector, not to the text string but to the textColorHint. You must add this attribute on your editText:

android:textColorHint="@color/text_hint_selector"

And your text_hint_selector should be:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:color="@android:color/transparent" />
    <item android:color="@color/hint_color" />
</selector>

Append String in Swift

In Swift, appending strings is as easy as:

let stringA = "this is a string"
let stringB = "this is also a string"
let stringC = stringA + stringB

Or you can use string interpolation.

let stringC = "\(stringA) \(stringB)"

Notice there will now be whitespace between them.

Note: I see the other answers are using var a lot. The strings aren't changing and therefore should be declared using let. I know this is a small exercise, but it's good to get into the habit of best practices. Especially because that's a big feature of Swift.

How to get request url in a jQuery $.get/ajax request

Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context option, as stated in the documentation:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

So you would use

$.ajax('http://www.example.org', {
  dataType: 'xml',
  data: {'a':1,'b':2,'c':3},
  context: {
    url: 'http://www.example.org'
  }
}).done(function(xml) {alert(this.url});

SQL Server NOLOCK and joins

I won't address the READ UNCOMMITTED argument, just your original question.

Yes, you need WITH(NOLOCK) on each table of the join. No, your queries are not the same.

Try this exercise. Begin a transaction and insert a row into table1 and table2. Don't commit or rollback the transaction yet. At this point your first query will return successfully and include the uncommitted rows; your second query won't return because table2 doesn't have the WITH(NOLOCK) hint on it.

How to invoke a Linux shell command from Java

exec does not execute a command in your shell

try

Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});

instead.

EDIT:: I don't have csh on my system so I used bash instead. The following worked for me

Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});

Can I run a 64-bit VMware image on a 32-bit machine?

If your hardware is 32-bit only, then no. If you have 64 bit hardware and a 32-bit operating system, then maybe. See Hardware and Firmware Requirements for 64-Bit Guest Operating Systems for details. It has nothing to do with one vs. multiple processors.

Does the Java &= operator apply & or &&?

i came across a similar situation using booleans where I wanted to avoid calling b() if a was already false.

This worked for me:

a &= a && b()

Undefined symbols for architecture armv7

In my case, I'd added a framework that must be using Objective C++. I found this post:

XCode .m vs. .mm

that explained how the main.m needed to be renamed to main.mm so that the Objective-C++ classes could be compiled, too.

That fixed it for me.

How to check if spark dataframe is empty?

On PySpark, you can also use this bool(df.head(1)) to obtain a True of False value

It returns False if the dataframe contains no rows

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

The standard Web Storage, does not say anything about the restoring any of these. So there won't be any standard way to do it. You have to go through the way the browsers implement these, or find a way to backup these before you delete them.

Should I use Java's String.format() if performance is important?

To expand/correct on the first answer above, it's not translation that String.format would help with, actually.
What String.format will help with is when you're printing a date/time (or a numeric format, etc), where there are localization(l10n) differences (ie, some countries will print 04Feb2009 and others will print Feb042009).
With translation, you're just talking about moving any externalizable strings (like error messages and what-not) into a property bundle so that you can use the right bundle for the right language, using ResourceBundle and MessageFormat.

Looking at all the above, I'd say that performance-wise, String.format vs. plain concatenation comes down to what you prefer. If you prefer looking at calls to .format over concatenation, then by all means, go with that.
After all, code is read a lot more than it's written.

Android Studio - Emulator - eglSurfaceAttrib not implemented

I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)

In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!

How do I parse a string with a decimal point to a double?

Double.Parse("3,5".Replace(',', '.'), CultureInfo.InvariantCulture)

Replace the comma with a point before parsing. Useful in countries with a comma as decimal separator. Think about limiting user input (if necessary) to one comma or point.

How can I write to the console in PHP?

For Ajax calls or XML / JSON responses, where you don't want to mess with the body, you need to send logs via HTTP headers, then add them to the console with a web extension. This is how FirePHP (no longer available) and QuantumPHP (a fork of ChromePHP) do it in Firefox.

If you have the patience, x-debug is a better option - you get deeper insight into PHP, with the ability to pause your script, see what is going on, then resume the script.

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

What about this?

java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0");

What is the current choice for doing RPC in Python?

maybe ZSI which implements SOAP. I used the stub generator and It worked properly. The only problem I encountered is about doing SOAP throught HTTPS.

Best way to store data locally in .NET (C#)

The first thing I'd look at is a database. However, serialization is an option. If you go for binary serialization, then I would avoid BinaryFormatter - it has a tendency to get angry between versions if you change fields etc. Xml via XmlSerialzier would be fine, and can be side-by-side compatible (i.e. with the same class definitions) with protobuf-net if you want to try contract-based binary serialization (giving you a flat file serializer without any effort).

How to get a URL parameter in Express?

You can do something like req.param('tagId')

Manually Triggering Form Validation using jQuery

Html Code:

<form class="validateDontSubmit">
....
<button style="dislay:none">submit</button>
</form>
<button class="outside"></button>

javascript( using Jquery):

<script type="text/javascript">

$(document).on('submit','.validateDontSubmit',function (e) {
    //prevent the form from doing a submit
    e.preventDefault();
    return false;
})

$(document).ready(function(){
// using button outside trigger click
    $('.outside').click(function() {
        $('.validateDontSubmit button').trigger('click');
    });
});
</script>

Hope this will help you

One command to create a directory and file inside it linux command

You could create a function that parses argument with sed;

atouch() {
  mkdir -p $(sed 's/\(.*\)\/.*/\1/' <<< $1) && touch $1
}

and then, execute it with one argument:

atouch B/C/D/myfile.txt

How to get EditText value and display it on screen through TextView?

First get the value from edit text in a String variable

String value = edttxt.getText().toString();

Then set that value to textView

txtview.setText(value);

Where edttxt refers to edit text field in XML file and txtview refers to textfield in XML file to show the value

Display image at 50% of its "native" size

Maybe one of the easiest solutions would be to use the x descriptor of the srcset attribute as such:

_x000D_
_x000D_
<!-- Original image -->
<img src="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png" />

<!-- With a 80% size reduction (1/0.8=1.25) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 1.25x" />

<!-- With a 50% size reduction (1/0.5=2) -->
<img srcset="https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png 2x" />
_x000D_
_x000D_
_x000D_

Currently supported by all browsers except IE. (caniuse)

MDN documentation

BULK INSERT with identity (auto-increment) column

You have to do bulk insert with format file:

   BULK INSERT Employee FROM 'path\tempFile.csv ' 
   WITH (FORMATFILE = 'path\tempFile.fmt');

where format file (tempFile.fmt) looks like this:

11.0
2
1 SQLCHAR 0 50 "\t"  2  Name   SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 50 "\r\n" 3  Address  SQL_Latin1_General_CP1_CI_AS

more details here - http://msdn.microsoft.com/en-us/library/ms179250.aspx

How to write a full path in a batch file having a folder name with space?

start "" AcroRd32.exe /A "page=207" "C:\Users\abc\Desktop\abc xyz def\abc def xyz 2015.pdf"

You may try this, I did it finally, it works!

How to use Collections.sort() in Java?

Create a comparator which accepts the compare mode in its constructor and pass different modes for different scenarios based on your requirement

public class RecipeComparator implements Comparator<Recipe> {

public static final int COMPARE_BY_ID = 0;
public static final int COMPARE_BY_NAME = 1;

private int compare_mode = COMPARE_BY_NAME;

public RecipeComparator() {
}

public RecipeComparator(int compare_mode) {
    this.compare_mode = compare_mode;
}

@Override
public int compare(Recipe o1, Recipe o2) {
    switch (compare_mode) {
    case COMPARE_BY_ID:
        return o1.getId().compareTo(o2.getId());
    default:
        return o1.getInputRecipeName().compareTo(o2.getInputRecipeName());
    }
}

}

Actually for numbers you need to handle them separately check below

public static void main(String[] args) {
    String string1 = "1";
    String string2 = "2";
    String string11 = "11";

    System.out.println(string1.compareTo(string2)); 
    System.out.println(string2.compareTo(string11));// expected -1 returns 1
   // to compare numbers you actually need to do something like this

    int number2 = Integer.valueOf(string1);
    int number11 = Integer.valueOf(string11);

    int compareTo = number2 > number11 ? 1 : (number2 < number11 ? -1 : 0) ;
    System.out.println(compareTo);// prints -1
}

Call JavaScript function on DropDownList SelectedIndexChanged Event:

You can use the ScriptManager.RegisterStartupScript(); to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();, you can do this:

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
 //----or alternatively and to be more proper
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}

To be exact for you, do this...

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}

SQL Current month/ year question

This should work for SQL Server:

SELECT * FROM myTable
WHERE month = DATEPART(m, GETDATE()) AND
year = DATEPART(yyyy, GETDATE())

Finding rows that don't contain numeric data in Oracle

After doing some testing, building upon the suggestions in the previous answers, there seem to be two usable solutions.

Method 1 is fastest, but less powerful in terms of matching more complex patterns.
Method 2 is more flexible, but slower.

Method 1 - fastest
I've tested this method on a table with 1 million rows.
It seems to be 3.8 times faster than the regex solutions.
The 0-replacement solves the issue that 0 is mapped to a space, and does not seem to slow down the query.

SELECT *
FROM <table>
WHERE TRANSLATE(replace(<char_column>,'0',''),'0123456789',' ') IS NOT NULL;

Method 2 - slower, but more flexible
I've compared the speed of putting the negation inside or outside the regex statement. Both are equally slower than the translate-solution. As a result, @ciuly's approach seems most sensible when using regex.

SELECT *
FROM <table>
WHERE NOT REGEXP_LIKE(<char_column>, '^[0-9]+$');

How to update Ruby to 1.9.x on Mac?

As previously mentioned, the bundler version may be too high for your version of rails.

I ran into the same problem using Rails 3.0.1 which requires Bundler v1.0.0 - v1.0.22

Check your bundler version using: gem list bundler

If your bundler version is not within the appropriate range, I found this solution to work: rvm @global do gem uninstall bundler

Note: rvm is required for this solution... another case for why you should be using rvm in the first place.

How to get the index of an item in a list in a single step?

How about the List.FindIndex Method:

int index = myList.FindIndex(a => a.Prop == oProp);

This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

If the item is not found, it will return -1

How do I modify the URL without reloading the page?

Any changes of the loction (either window.location or document.location) will cause a request on that new URL, if you’re not just changing the URL fragment. If you change the URL, you change the URL.

Use server-side URL rewrite techniques like Apache’s mod_rewrite if you don’t like the URLs you are currently using.

How can I make sticky headers in RecyclerView? (Without external lib)

I've made my own variation of Sevastyan's solution above

class HeaderItemDecoration(recyclerView: RecyclerView, private val listener: StickyHeaderInterface) : RecyclerView.ItemDecoration() {

private val headerContainer = FrameLayout(recyclerView.context)
private var stickyHeaderHeight: Int = 0
private var currentHeader: View? = null
private var currentHeaderPosition = 0

init {
    val layout = RelativeLayout(recyclerView.context)
    val params = recyclerView.layoutParams
    val parent = recyclerView.parent as ViewGroup
    val index = parent.indexOfChild(recyclerView)
    parent.addView(layout, index, params)
    parent.removeView(recyclerView)
    layout.addView(recyclerView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
    layout.addView(headerContainer, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
}

override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
    super.onDrawOver(c, parent, state)

    val topChild = parent.getChildAt(0) ?: return

    val topChildPosition = parent.getChildAdapterPosition(topChild)
    if (topChildPosition == RecyclerView.NO_POSITION) {
        return
    }

    val currentHeader = getHeaderViewForItem(topChildPosition, parent)
    fixLayoutSize(parent, currentHeader)
    val contactPoint = currentHeader.bottom
    val childInContact = getChildInContact(parent, contactPoint) ?: return

    val nextPosition = parent.getChildAdapterPosition(childInContact)
    if (listener.isHeader(nextPosition)) {
        moveHeader(currentHeader, childInContact, topChildPosition, nextPosition)
        return
    }

    drawHeader(currentHeader, topChildPosition)
}

private fun getHeaderViewForItem(itemPosition: Int, parent: RecyclerView): View {
    val headerPosition = listener.getHeaderPositionForItem(itemPosition)
    val layoutResId = listener.getHeaderLayout(headerPosition)
    val header = LayoutInflater.from(parent.context).inflate(layoutResId, parent, false)
    listener.bindHeaderData(header, headerPosition)
    return header
}

private fun drawHeader(header: View, position: Int) {
    headerContainer.layoutParams.height = stickyHeaderHeight
    setCurrentHeader(header, position)
}

private fun moveHeader(currentHead: View, nextHead: View, currentPos: Int, nextPos: Int) {
    val marginTop = nextHead.top - currentHead.height
    if (currentHeaderPosition == nextPos && currentPos != nextPos) setCurrentHeader(currentHead, currentPos)

    val params = currentHeader?.layoutParams as? MarginLayoutParams ?: return
    params.setMargins(0, marginTop, 0, 0)
    currentHeader?.layoutParams = params

    headerContainer.layoutParams.height = stickyHeaderHeight + marginTop
}

private fun setCurrentHeader(header: View, position: Int) {
    currentHeader = header
    currentHeaderPosition = position
    headerContainer.removeAllViews()
    headerContainer.addView(currentHeader)
}

private fun getChildInContact(parent: RecyclerView, contactPoint: Int): View? =
        (0 until parent.childCount)
            .map { parent.getChildAt(it) }
            .firstOrNull { it.bottom > contactPoint && it.top <= contactPoint }

private fun fixLayoutSize(parent: ViewGroup, view: View) {

    val widthSpec = View.MeasureSpec.makeMeasureSpec(parent.width, View.MeasureSpec.EXACTLY)
    val heightSpec = View.MeasureSpec.makeMeasureSpec(parent.height, View.MeasureSpec.UNSPECIFIED)

    val childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
            parent.paddingLeft + parent.paddingRight,
            view.layoutParams.width)
    val childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
            parent.paddingTop + parent.paddingBottom,
            view.layoutParams.height)

    view.measure(childWidthSpec, childHeightSpec)

    stickyHeaderHeight = view.measuredHeight
    view.layout(0, 0, view.measuredWidth, stickyHeaderHeight)
}

interface StickyHeaderInterface {

    fun getHeaderPositionForItem(itemPosition: Int): Int

    fun getHeaderLayout(headerPosition: Int): Int

    fun bindHeaderData(header: View, headerPosition: Int)

    fun isHeader(itemPosition: Int): Boolean
}
}

... and here is implementation of StickyHeaderInterface (I did it directly in recycler adapter):

override fun getHeaderPositionForItem(itemPosition: Int): Int =
    (itemPosition downTo 0)
        .map { Pair(isHeader(it), it) }
        .firstOrNull { it.first }?.second ?: RecyclerView.NO_POSITION

override fun getHeaderLayout(headerPosition: Int): Int {
    /* ... 
      return something like R.layout.view_header
      or add conditions if you have different headers on different positions
    ... */
}

override fun bindHeaderData(header: View, headerPosition: Int) {
    if (headerPosition == RecyclerView.NO_POSITION) header.layoutParams.height = 0
    else /* ...
      here you get your header and can change some data on it
    ... */
}

override fun isHeader(itemPosition: Int): Boolean {
    /* ...
      here have to be condition for checking - is item on this position header
    ... */
}

So, in this case header is not just drawing on canvas, but view with selector or ripple, clicklistener, etc.

How to download all files (but not HTML) from a website using wget?

wget -m -A * -pk -e robots=off www.mysite.com/

this will download all type of files locally and point to them from the html file and it will ignore robots file

List file names based on a filename pattern and file content?

find /folder -type f -mtime -90 | grep -E "(.txt|.php|.inc|.root|.gif)" | xargs ls -l > WWWlastActivity.log

How to set image for bar button with swift?

An easy solution may be the following

barButtonItem.image = UIImage(named: "image")

then go to your Assets.xcassets select the image and go to the Attribute Inspector and select "Original Image" in Reder as option.

Build Step Progress Bar (css and jquery)

I have searched for a solution that will visualize process steps in my web application. I have found the following excellent write-up by Stephen A Thomas:

Tracking Progress in Pure CSS (Original Link now dead)

In his approach Thomas even gets away with just using CSS - no Javascript! In an essence the following CSS code from his article does the trick for me:

    <style>

    <!-- Progress with steps -->

    ol.progtrckr {
        margin: 0;
        padding: 0;
        list-style-type: none;
    }

    ol.progtrckr li {
        display: inline-block;
        text-align: center;
        line-height: 3em;
    }

    ol.progtrckr[data-progtrckr-steps="2"] li { width: 49%; }
    ol.progtrckr[data-progtrckr-steps="3"] li { width: 33%; }
    ol.progtrckr[data-progtrckr-steps="4"] li { width: 24%; }
    ol.progtrckr[data-progtrckr-steps="5"] li { width: 19%; }
    ol.progtrckr[data-progtrckr-steps="6"] li { width: 16%; }
    ol.progtrckr[data-progtrckr-steps="7"] li { width: 14%; }
    ol.progtrckr[data-progtrckr-steps="8"] li { width: 12%; }
    ol.progtrckr[data-progtrckr-steps="9"] li { width: 11%; }

    ol.progtrckr li.progtrckr-done {
        color: black;
        border-bottom: 4px solid yellowgreen;
    }
    ol.progtrckr li.progtrckr-todo {
        color: silver; 
        border-bottom: 4px solid silver;
    }

    ol.progtrckr li:after {
        content: "\00a0\00a0";
    }
    ol.progtrckr li:before {
        position: relative;
        bottom: -2.5em;
        float: left;
        left: 50%;
        line-height: 1em;
    }
    ol.progtrckr li.progtrckr-done:before {
        content: "\2713";
        color: white;
        background-color: yellowgreen;
        height: 1.2em;
        width: 1.2em;
        line-height: 1.2em;
        border: none;
        border-radius: 1.2em;
    }
    ol.progtrckr li.progtrckr-todo:before {
        content: "\039F";
        color: silver;
        background-color: white;
        font-size: 1.5em;
        bottom: -1.6em;
    }

</style>

As well as HTML tags from his example (I use Grails GSP pages to generate tags and 'done/todo' class dynamically):

<ol class="progtrckr" data-progtrckr-steps="5">
    <li class="progtrckr-done">Order Processing</li>
    <li class="progtrckr-done">Pre-Production</li>
    <li class="progtrckr-done">In Production</li>
    <li class="progtrckr-done">Shipped</li>
    <li class="progtrckr-todo">Delivered</li>
</ol>

Hope it helps. Works pretty well for me.


UPDATE: The following (shortened) version also works well.

    ol.progtrckr {
        display: table;
        list-style-type: none;
        margin: 0;
        padding: 0;
        table-layout: fixed;
        width: 100%;
    }
    ol.progtrckr li {
        display: table-cell;
        text-align: center;
        line-height: 3em;
    }
    ... and the rest of the CSS ...

    <ol class="progtrckr">
        ...
    </ol>

display: table; table-layout: fixed; width: 100% ensure that the list items are automatically sized equally as long as the content does not overflow. There is no need to use data-progtrckr-steps and its associated CSS.

if arguments is equal to this string, define a variable like this string

It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:

http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/

I added the snippet below as a tl;dr

#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         t)
             TEST=$OPTARG
             ;;
         r)
             SERVER=$OPTARG
             ;;
         p)
             PASSWD=$OPTARG
             ;;
         v)
             VERBOSE=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
     usage
     exit 1
fi

./script.sh -t test -r server -p password -v

is it possible to update UIButton title/text programmatically?

As of Swift 4:

    button.setTitle("Click", for: .normal)

Most efficient way to append arrays in C#?

I recommend the answer found here: How do I concatenate two arrays in C#?

e.g.

var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

The equivalent is:

python3 -m http.server

Rename Files and Directories (Add Prefix)

Here is a simple script that you can use. I like using the non-standard module File::chdir to handle managing cd operations, so to use this script as-is you will need to install it (sudo cpan File::chdir).

#!/usr/bin/perl

use strict;
use warnings;

use File::Copy;
use File::chdir; # allows cd-ing by use of $CWD, much easier but needs CPAN module

die "Usage: $0 dir prefix" unless (@ARGV >= 2);
my ($dir, $pre) = @ARGV;

opendir(my $dir_handle, $dir) or die "Cannot open directory $dir";
my @files = readdir($dir_handle);
close($dir_handle);

$CWD = $dir; # cd to the directory, needs File::chdir

foreach my $file (@files) {
  next if ($file =~ /^\.+$/); # avoid folders . and ..
  next if ($0 =~ /$file/); # avoid moving this script if it is in the directory

  move($file, $pre . $file) or warn "Cannot rename file $file: $!";
}

Removing rounded corners from a <select> element in Chrome/Webkit

This works for me (styles the first appearance not the dropdown list):

select {
  -webkit-appearance: none;
  -webkit-border-radius: 0px;
}

http://jsfiddle.net/fMuPt/

What should every programmer know about security?

I suggest reviewing CWE/SANS TOP 25 Most Dangerous Programming Errors. It was updated for 2010 with the promise of regular updates in the future. The 2009 revision is available as well.

From http://cwe.mitre.org/top25/index.html

The 2010 CWE/SANS Top 25 Most Dangerous Programming Errors is a list of the most widespread and critical programming errors that can lead to serious software vulnerabilities. They are often easy to find, and easy to exploit. They are dangerous because they will frequently allow attackers to completely take over the software, steal data, or prevent the software from working at all.

The Top 25 list is a tool for education and awareness to help programmers to prevent the kinds of vulnerabilities that plague the software industry, by identifying and avoiding all-too-common mistakes that occur before software is even shipped. Software customers can use the same list to help them to ask for more secure software. Researchers in software security can use the Top 25 to focus on a narrow but important subset of all known security weaknesses. Finally, software managers and CIOs can use the Top 25 list as a measuring stick of progress in their efforts to secure their software.

Sorting string array in C#

This code snippet is working properly enter image description here

forEach is not a function error with JavaScript array

parent.children is a HTMLCollection which is array-like object. First, you have to convert it to a real Array to use Array.prototype methods.

const parent = this.el.parentElement
console.log(parent.children)
[].slice.call(parent.children).forEach(child => {
  console.log(child)
})

How to use the CSV MIME-type?

You are not specifying a language or framework, but the following header is used for file downloads:

"Content-Disposition: attachment; filename=abc.csv"

bootstrap jquery show.bs.modal event won't fire

This happens when code might been executed before and it's not showing up so you can add timeout() for it tp fire.

$(document).on('shown.bs.modal', function (event) {
      setTimeout(function(){
        alert("Hi");
      },1000); 
    });

How can I query for null values in entity framework?

Pointing out that all of the Entity Framework < 6.0 suggestions generate some awkward SQL. See second example for "clean" fix.

Ridiculous Workaround

// comparing against this...
Foo item = ...

return DataModel.Foos.FirstOrDefault(o =>
    o.ProductID == item.ProductID
    // ridiculous < EF 4.5 nullable comparison workaround http://stackoverflow.com/a/2541042/1037948
    && item.ProductStyleID.HasValue ? o.ProductStyleID == item.ProductStyleID : o.ProductStyleID == null
    && item.MountingID.HasValue ? o.MountingID == item.MountingID : o.MountingID == null
    && item.FrameID.HasValue ? o.FrameID == item.FrameID : o.FrameID == null
    && o.Width == w
    && o.Height == h
    );

results in SQL like:

SELECT TOP (1) [Extent1].[ID]                 AS [ID],
       [Extent1].[Name]               AS [Name],
       [Extent1].[DisplayName]        AS [DisplayName],
       [Extent1].[ProductID]          AS [ProductID],
       [Extent1].[ProductStyleID]     AS [ProductStyleID],
       [Extent1].[MountingID]         AS [MountingID],
       [Extent1].[Width]              AS [Width],
       [Extent1].[Height]             AS [Height],
       [Extent1].[FrameID]            AS [FrameID],
FROM   [dbo].[Foos] AS [Extent1]
WHERE  (CASE
  WHEN (([Extent1].[ProductID] = 1 /* @p__linq__0 */)
        AND (NULL /* @p__linq__1 */ IS NOT NULL)) THEN
    CASE
      WHEN ([Extent1].[ProductStyleID] = NULL /* @p__linq__2 */) THEN cast(1 as bit)
      WHEN ([Extent1].[ProductStyleID] <> NULL /* @p__linq__2 */) THEN cast(0 as bit)
    END
  WHEN (([Extent1].[ProductStyleID] IS NULL)
        AND (2 /* @p__linq__3 */ IS NOT NULL)) THEN
    CASE
      WHEN ([Extent1].[MountingID] = 2 /* @p__linq__4 */) THEN cast(1 as bit)
      WHEN ([Extent1].[MountingID] <> 2 /* @p__linq__4 */) THEN cast(0 as bit)
    END
  WHEN (([Extent1].[MountingID] IS NULL)
        AND (NULL /* @p__linq__5 */ IS NOT NULL)) THEN
    CASE
      WHEN ([Extent1].[FrameID] = NULL /* @p__linq__6 */) THEN cast(1 as bit)
      WHEN ([Extent1].[FrameID] <> NULL /* @p__linq__6 */) THEN cast(0 as bit)
    END
  WHEN (([Extent1].[FrameID] IS NULL)
        AND ([Extent1].[Width] = 20 /* @p__linq__7 */)
        AND ([Extent1].[Height] = 16 /* @p__linq__8 */)) THEN cast(1 as bit)
  WHEN (NOT (([Extent1].[FrameID] IS NULL)
             AND ([Extent1].[Width] = 20 /* @p__linq__7 */)
             AND ([Extent1].[Height] = 16 /* @p__linq__8 */))) THEN cast(0 as bit)
END) = 1

Outrageous Workaround

If you want to generate cleaner SQL, something like:

// outrageous < EF 4.5 nullable comparison workaround http://stackoverflow.com/a/2541042/1037948
Expression<Func<Foo, bool>> filterProductStyle, filterMounting, filterFrame;
if(item.ProductStyleID.HasValue) filterProductStyle = o => o.ProductStyleID == item.ProductStyleID;
else filterProductStyle = o => o.ProductStyleID == null;

if (item.MountingID.HasValue) filterMounting = o => o.MountingID == item.MountingID;
else filterMounting = o => o.MountingID == null;

if (item.FrameID.HasValue) filterFrame = o => o.FrameID == item.FrameID;
else filterFrame = o => o.FrameID == null;

return DataModel.Foos.Where(o =>
    o.ProductID == item.ProductID
    && o.Width == w
    && o.Height == h
    )
    // continue the outrageous workaround for proper sql
    .Where(filterProductStyle)
    .Where(filterMounting)
    .Where(filterFrame)
    .FirstOrDefault()
    ;

results in what you wanted in the first place:

SELECT TOP (1) [Extent1].[ID]                 AS [ID],
           [Extent1].[Name]               AS [Name],
           [Extent1].[DisplayName]        AS [DisplayName],
           [Extent1].[ProductID]          AS [ProductID],
           [Extent1].[ProductStyleID]     AS [ProductStyleID],
           [Extent1].[MountingID]         AS [MountingID],
           [Extent1].[Width]              AS [Width],
           [Extent1].[Height]             AS [Height],
           [Extent1].[FrameID]            AS [FrameID],
FROM   [dbo].[Foos] AS [Extent1]
WHERE  ([Extent1].[ProductID] = 1 /* @p__linq__0 */)
   AND ([Extent1].[Width] = 16 /* @p__linq__1 */)
   AND ([Extent1].[Height] = 20 /* @p__linq__2 */)
   AND ([Extent1].[ProductStyleID] IS NULL)
   AND ([Extent1].[MountingID] = 2 /* @p__linq__3 */)
   AND ([Extent1].[FrameID] IS NULL)

Add attribute 'checked' on click jquery

$( this ).attr( 'checked', 'checked' )

just attr( 'checked' ) will return the value of $( this )'s checked attribute. To set it, you need that second argument. Based on <input type="checkbox" checked="checked" />

Edit:

Based on comments, a more appropriate manipulation would be:

$( this ).attr( 'checked', true )

And a straight javascript method, more appropriate and efficient:

this.checked = true;

Thanks @Andy E for that.

anaconda - path environment variable in windows

The default location for python.exe should be here: c:\users\xxx\anaconda3 One solution to find where it is, is to open the Anaconda Prompt then execute:

> where python

This will return the absolute path of locations of python eg:

(base) C:\>where python
C:\Users\Chad\Anaconda3\python.exe
C:\ProgramData\Miniconda2\python.exe
C:\dev\Python27\python.exe
C:\dev\Python34\python.exe

What is the best way to test for an empty string with jquery-out-of-the-box?

The link you gave seems to be attempting something different to the test you are trying to avoid repeating.

if (a == null || a=='')

tests if the string is an empty string or null. The article you linked to tests if the string consists entirely of whitespace (or is empty).

The test you described can be replaced by:

if (!a)

Because in javascript, an empty string, and null, both evaluate to false in a boolean context.

Does IE9 support console.log, and is it a real function?

A simple solution to this console.log problem is to define the following at the beginning of your JS code:

if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };

This works for me in all browsers. This creates a dummy function for console.log when the debugger is not active. When the debugger is active, the method console.log is defined and executes normally.

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

Disable scrolling in webview?

I haven't tried this as I have yet to encounter this problem, but perhaps you could overrive the onScroll function?

@Override
public void scrollTo(int x, int y){
super.scrollTo(0,y);
}

div inside table

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  <head>
    <title>test</title>
  </head>
  <body>
    <table>
      <tr>
        <td>
          <div>content</div>
        </td>
      </tr>
    </table>
  </body>
</html>

This document was successfully checked as XHTML 1.0 Transitional!

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

Granted, OP stated very similarly that this didn't work, but it did for me. Based on the notes in my source, it seems it was implemented around the time, or after, OP's post. Perhaps it's more standard now.

document.getElementsByName('MyElementsName')[0].click();

In my case, my button didn't have an ID. If your element has an id, preferably use the following (untested).

document.getElementById('MyElementsId').click();

I originally tried this method and it didn't work. After Googling I came back and realized my element was by name, and didn't have an ID. Double check you're calling the right attribute.

Source: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click

External VS2013 build error "error MSB4019: The imported project <path> was not found"

I had tried all of the above solutions and still no luck. I had heard people installing visual studio on their build servers to fix it, but I only had 5gb of free spaces so I just copied C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio to my build server and called it a day. Started working after that, using team city 9.x and visual studio 2013.

Variable used in lambda expression should be final or effectively final

if it is not necessary to modify the variable than a general workaround for this kind of problem would be to extract the part of code which use lambda and use final keyword on method-parameter.

A KeyValuePair in Java

Android programmers could use BasicNameValuePair

Update:

BasicNameValuePair is now deprecated (API 22). Use Pair instead.

Example usage:

Pair<Integer, String> simplePair = new Pair<>(42, "Second");
Integer first = simplePair.first; // 42
String second = simplePair.second; // "Second"

Passing environment-dependent variables in webpack

I investigated a couple of options on how to set environment-specific variables and ended up with this:

I have 2 webpack configs currently:

webpack.production.config.js

new webpack.DefinePlugin({
  'process.env':{
    'NODE_ENV': JSON.stringify('production'),
    'API_URL': JSON.stringify('http://localhost:8080/bands')
  }
}),

webpack.config.js

new webpack.DefinePlugin({
  'process.env':{
    'NODE_ENV': JSON.stringify('development'),
    'API_URL': JSON.stringify('http://10.10.10.10:8080/bands')
  }
}),

In my code I get the value of API_URL in this (brief) way:

const apiUrl = process.env.API_URL;

EDIT 3rd of Nov, 2016

Webpack docs has an example: https://webpack.js.org/plugins/define-plugin/#usage

new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true),
    VERSION: JSON.stringify("5fa3b9"),
    BROWSER_SUPPORTS_HTML5: true,
    TWO: "1+1",
    "typeof window": JSON.stringify("object")
})

With ESLint you need to specifically allow undefined variables in code, if you have no-undef rule on. http://eslint.org/docs/rules/no-undef like this:

/*global TWO*/
console.log('Running App version ' + TWO);

EDIT 7th of Sep, 2017 (Create-React-App specific)

If you're not into configuring too much, check out Create-React-App: Create-React-App - Adding Custom Environment Variables. Under the hood CRA uses Webpack anyway.

What is the newline character in the C language: \r or \n?

What is the newline character in the C language: \r or \n?

The new-line may be thought of a some char and it has the value of '\n'. C11 5.2.1

This C new-line comes up in 3 places: C source code, as a single char and as an end-of-line in file I/O when in text mode.

  1. Many compilers will treat source text as ASCII. In that case, codes 10, sometimes 13, and sometimes paired 13,10 as new-line for source code. Had the source code been in another character set, different codes may be used. This new-line typically marks the end of a line of source code (actually a bit more complicated here), // comment, and # directives.

  2. In source code, the 2 characters \ and n represent the char new-line as \n. If ASCII is used, this char would have the value of 10.

  3. In file I/O, in text mode, upon reading the bytes of the input file (and stdin), depending on the environment, when bytes with the value(s) of 10 (Unix), 13,10, (*1) (Windows), 13 (Old Mac??) and other variations are translated in to a '\n'. Upon writing a file (or stdout), the reverse translation occurs.
    Note: File I/O in binary mode makes no translation.

The '\r' in source code is the carriage return char.

(*1) A lone 13 and/or 10 may also translate into \n.

Regular expression to validate US phone numbers?

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

What is a None value?

largest=none
smallest =none 
While True :
          num =raw_input ('enter a number ') 
          if num =="done ": break 
          try :
           inp =int (inp) 
          except:
              Print'Invalid input' 
           if largest is none :
               largest=inp
           elif inp>largest:
                largest =none 
           print 'maximum', largest

          if smallest is none:
               smallest =none
          elif inp<smallest :
               smallest =inp
          print 'minimum', smallest 

print 'maximum, minimum, largest, smallest 

PHP - Getting the index of a element from a array

I recently had to figure this out for myself and ended up on a solution inspired by @Zahymaka 's answer, but solving the 2x looping of the array.

What you can do is create an array with all your keys, in the order they exist, and then loop through that.

        $keys=array_keys($items);
        foreach($keys as $index=>$key){
                    echo "position: $index".PHP_EOL."item: ".PHP_EOL;
                    var_dump($items[$key]);
                    ...
        }

PS: I know this is very late to the party, but since I found myself searching for this, maybe this could be helpful to someone else

Jquery post, response in new window

I did it with an ajax post and then returned using a data url:

$(document).ready(function () {
    var exportClick = function () {
        $.ajax({
           url: "/api/test.php",
           type: "POST",
           dataType: "text",
           data: {
              action: "getCSV",
              filter: "name = 'smith'",
           },
           success: function(data) {
              var w = window.open('data:text/csv;charset=utf-8,' + encodeURIComponent(data));
              w.focus();
           },
           error: function () {
              alert('Problem getting data');
           },
        });
    }
});

Get host domain from URL?

WWW is an alias, so you don't need it if you want a domain. Here is my litllte function to get the real domain from a string

private string GetDomain(string url)
    {
        string[] split = url.Split('.');
        if (split.Length > 2)
            return split[split.Length - 2] + "." + split[split.Length - 1];
        else
            return url;

    }

How to revert uncommitted changes including files and folders?

Please note that there might still be files that won't seem to disappear - they might be unedited, but git might have marked them as being edited because of CRLF / LF changes. See if you've made some changes in .gitattributes recently.

In my case I've added CRLF settings into the .gitattributes file and all the files remained in the "modified files" list because of this. Changing the .gitattributes settings made them disappear.

WPF ListView - detect when selected item is clicked

I would also suggest deselecting an item after it has been clicked and use the MouseDoubleClick event

private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    try {
        //Do your stuff here
        listBox.SelectedItem = null;
        listBox.SelectedIndex = -1;
    } catch (Exception ex) {
        System.Diagnostics.Debug.WriteLine(ex.Message);
    }
}

Exporting functions from a DLL with dllexport

If you want plain C exports, use a C project not C++. C++ DLLs rely on name-mangling for all the C++isms (namespaces etc...). You can compile your code as C by going into your project settings under C/C++->Advanced, there is an option "Compile As" which corresponds to the compiler switches /TP and /TC.

If you still want to use C++ to write the internals of your lib but export some functions unmangled for use outside C++, see the second section below.

Exporting/Importing DLL Libs in VC++

What you really want to do is define a conditional macro in a header that will be included in all of the source files in your DLL project:

#ifdef LIBRARY_EXPORTS
#    define LIBRARY_API __declspec(dllexport)
#else
#    define LIBRARY_API __declspec(dllimport)
#endif

Then on a function that you want to be exported you use LIBRARY_API:

LIBRARY_API int GetCoolInteger();

In your library build project create a define LIBRARY_EXPORTS this will cause your functions to be exported for your DLL build.

Since LIBRARY_EXPORTS will not be defined in a project consuming the DLL, when that project includes the header file of your library all of the functions will be imported instead.

If your library is to be cross-platform you can define LIBRARY_API as nothing when not on Windows:

#ifdef _WIN32
#    ifdef LIBRARY_EXPORTS
#        define LIBRARY_API __declspec(dllexport)
#    else
#        define LIBRARY_API __declspec(dllimport)
#    endif
#elif
#    define LIBRARY_API
#endif

When using dllexport/dllimport you do not need to use DEF files, if you use DEF files you do not need to use dllexport/dllimport. The two methods accomplish the same task different ways, I believe that dllexport/dllimport is the recommended method out of the two.

Exporting unmangled functions from a C++ DLL for LoadLibrary/PInvoke

If you need this to use LoadLibrary and GetProcAddress, or maybe importing from another language (i.e PInvoke from .NET, or FFI in Python/R etc) you can use extern "C" inline with your dllexport to tell the C++ compiler not to mangle the names. And since we are using GetProcAddress instead of dllimport we don't need to do the ifdef dance from above, just a simple dllexport:

The Code:

#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)

EXTERN_DLL_EXPORT int getEngineVersion() {
  return 1;
}

EXTERN_DLL_EXPORT void registerPlugin(Kernel &K) {
  K.getGraphicsServer().addGraphicsDriver(
    auto_ptr<GraphicsServer::GraphicsDriver>(new OpenGLGraphicsDriver())
  );
}

And here's what the exports look like with Dumpbin /exports:

  Dump of file opengl_plugin.dll

  File Type: DLL

  Section contains the following exports for opengl_plugin.dll

    00000000 characteristics
    49866068 time date stamp Sun Feb 01 19:54:32 2009
        0.00 version
           1 ordinal base
           2 number of functions
           2 number of names

    ordinal hint RVA      name

          1    0 0001110E getEngineVersion = @ILT+265(_getEngineVersion)
          2    1 00011028 registerPlugin = @ILT+35(_registerPlugin)

So this code works fine:

m_hDLL = ::LoadLibrary(T"opengl_plugin.dll");

m_pfnGetEngineVersion = reinterpret_cast<fnGetEngineVersion *>(
  ::GetProcAddress(m_hDLL, "getEngineVersion")
);
m_pfnRegisterPlugin = reinterpret_cast<fnRegisterPlugin *>(
  ::GetProcAddress(m_hDLL, "registerPlugin")
);

Is there a .NET/C# wrapper for SQLite?

sqlite-net is an open source, minimal library to allow .NET and Mono applications to store data in SQLite 3 databases. More information at the wiki page.

It is written in C# and is meant to be simply compiled in with your projects. It was first designed to work with MonoTouch on the iPhone, but has grown up to work on all the platforms (Mono for Android, .NET, Silverlight, WP7, WinRT, Azure, etc.).

It is available as a Nuget package, where it is the 2nd most popular SQLite package with over 60,000 downloads as of 2014.

sqlite-net was designed as a quick and convenient database layer. Its design follows from these goals:

  • Very easy to integrate with existing projects and with MonoTouch projects.
  • Thin wrapper over SQLite and should be fast and efficient. (The library should not be the performance bottleneck of your queries.)
  • Very simple methods for executing CRUD operations and queries safely (using parameters) and for retrieving the results of those query in a strongly typed fashion.
  • Works with your data model without forcing you to change your classes. (Contains a small reflection-driven ORM layer.)
  • 0 dependencies aside from a compiled form of the sqlite2 library.

Non-goals include:

  • Not an ADO.NET implementation. This is not a full SQLite driver. If you need that, use System.Data.SQLite.

Fit background image to div

background-position-x: center;
background-position-y: center;

How can I show figures separately in matplotlib?

None of the above solutions seems to work in my case, with matplotlib 3.1.0 and Python 3.7.3. Either both the figures show up on calling show() or none show up in different answers posted above.

Building upon @Ivan's answer, and taking hint from here, the following seemed to work well for me:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(1) # Creates figure fig and add an axes, ax.
fig2, ax2 = plt.subplots(1) # Another figure

ax.plot(range(20)) #Add a straight line to the axes of the first figure.
ax2.plot(range(100)) #Add a straight line to the axes of the first figure.

# plt.close(fig) # For not showing fig
plt.close(fig2) # For not showing fig2
plt.show()

How do I list the symbols in a .so file

If you just want to know if there are symbols present you can use

objdump -h /path/to/object

or to list the debug info

objdump -g /path/to/object

Ruby, Difference between exec, system and %x() or Backticks

They do different things. exec replaces the current process with the new process and never returns. system invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.

How can I "reset" an Arduino board?

Make sure you plug the Arduino directly into the computer and not through a hub. Using a hub will give you this error.

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

With Bootstrap 4 .hidden-* classes were completely removed (yes, they were replaced by hidden-*-* but those classes are also gone from v4 alphas).

Starting with v4-beta, you can combine .d-*-none and .d-*-block classes to achieve the same result.

visible-* was removed as well; instead of using explicit .visible-* classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:

<div class="col d-none d-sm-block">
    <span class="vcard">
        …
    </span>
</div>
<div class="col d-none d-xl-block">
    <div class="d-none d-md-block">
                …
    </div>
    <div class="d-none d-sm-block">
                …
    </div>
</div>

class="hidden-xs" becomes class="d-none d-sm-block" (or d-none d-sm-inline-block) ...

<span class="d-none d-sm-inline">hidden-xs</span>

<span class="d-none d-sm-inline-block">hidden-xs</span>

An example of Bootstrap 4 responsive utilities:

<div class="d-none d-sm-block"> hidden-xs           
  <div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
    <div class="d-none d-lg-block"> visible-lg and up  (hidden-md and down)
      <div class="d-none d-xl-block"> visible-xl </div>
    </div>
  </div>
</div>

<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>

<div class="d-xl-none"> hidden-xl (visible-lg and down)         
  <div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
    <div class="d-md-none d-lg-none d-xl-none"> visible-sm and down  (or hidden-md and up)
      <div class="d-sm-none"> visible-xs </div>
    </div>
  </div>
</div>

Documentation

How to kill a child process by the parent process?

In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.

When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).

Remember to call wait() on the child process to prevent any lingering zombies.

Sending HTTP POST Request In Java

I recomend use http-request built on apache http api.

HttpRequest<String> httpRequest = HttpRequestBuilder.createPost("http://www.example.com/page.php", String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();

public void send(){
   String response = httpRequest.execute("id", "10").get();
}

Javascript getElementById based on a partial string

You can use the querySelector for that:

document.querySelector('[id^="poll-"]').id;

The selector means: get an element where the attribute [id] begins with the string "poll-".

^ matches the start
* matches any position
$ matches the end

jsfiddle

Make an existing Git branch track a remote branch?

Given a branch foo and a remote upstream:

As of Git 1.8.0:

git branch -u upstream/foo

Or, if local branch foo is not the current branch:

git branch -u upstream/foo foo

Or, if you like to type longer commands, these are equivalent to the above two:

git branch --set-upstream-to=upstream/foo

git branch --set-upstream-to=upstream/foo foo

As of Git 1.7.0 (before 1.8.0):

git branch --set-upstream foo upstream/foo

Notes:

  • All of the above commands will cause local branch foo to track remote branch foo from remote upstream.
  • The old (1.7.x) syntax is deprecated in favor of the new (1.8+) syntax. The new syntax is intended to be more intuitive and easier to remember.
  • Defining an upstream branch will fail when run against newly-created remotes that have not already been fetched. In that case, run git fetch upstream beforehand.

See also: Why do I need to do `--set-upstream` all the time?

Download history stock prices automatically from yahoo finance in python

Short answer: Yes. Use Python's urllib to pull the historical data pages for the stocks you want. Go with Yahoo! Finance; Google is both less reliable, has less data coverage, and is more restrictive in how you can use it once you have it. Also, I believe Google specifically prohibits you from scraping the data in their ToS.

Longer answer: This is the script I use to pull all the historical data on a particular company. It pulls the historical data page for a particular ticker symbol, then saves it to a csv file named by that symbol. You'll have to provide your own list of ticker symbols that you want to pull.

import urllib

base_url = "http://ichart.finance.yahoo.com/table.csv?s="
def make_url(ticker_symbol):
    return base_url + ticker_symbol

output_path = "C:/path/to/output/directory"
def make_filename(ticker_symbol, directory="S&P"):
    return output_path + "/" + directory + "/" + ticker_symbol + ".csv"

def pull_historical_data(ticker_symbol, directory="S&P"):
    try:
        urllib.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
    except urllib.ContentTooShortError as e:
        outfile = open(make_filename(ticker_symbol, directory), "w")
        outfile.write(e.content)
        outfile.close()

If table exists drop table then create it, if it does not exist just create it

Just use DROP TABLE IF EXISTS:

DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );

Try searching the MySQL documentation first if you have any other problems.

Best Regular Expression for Email Validation in C#

Updated answer for 2019.

Regex object is thread-safe for Matching functions. Knowing that and there are some performance options or cultural / language issues, I propose this simple solution.

public static Regex _regex = new Regex(
    @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
    RegexOptions.CultureInvariant | RegexOptions.Singleline);

public static bool IsValidEmailFormat(string emailInput)
{
    return _regex.IsMatch(emailInput);
}

Alternative Configuration for Regex:

public static Regex _regex = new Regex(
    @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
    RegexOptions.CultureInvariant | RegexOptions.Compiled);

I find that compiled is only faster on big string matches, like book parsing for example. Simple email matching is faster just letting Regex interpret.

Thread Safety And Regex
Regex Best Practices

How to access the value of a promise?

Maybe this small Typescript code example will help.

private getAccount(id: Id) : Account {
    let account = Account.empty();
    this.repository.get(id)
        .then(res => account = res)
        .catch(e => Notices.results(e));
    return account;
}

Here the repository.get(id) returns a Promise<Account>. I assign it to the variable account within the then statement.

execute shell command from android

Process p;
StringBuffer output = new StringBuffer();
try {
    p = Runtime.getRuntime().exec(params[0]);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
        p.waitFor();
    }
} 
catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}
String response = output.toString();
return response;

Class is not abstract and does not override abstract method

If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

Does document.body.innerHTML = "" clear the web page?

To expound on Douwem's answer, in your script tag, put your code in an onload:

<script type="text/javascript">
    window.onload=function(){
       document.body.innerHTML = "";
    }
</script>

How to change line width in IntelliJ (from 120 character)

I didn't understand why my this didn't work but I found out that this setting is now also under the programming language itself at:

'Editor' | 'Code Style' | < your language > | 'Wrapping and Braces' | 'Right margin (columns)'

HTML list-style-type dash

One of the top answers did not work for me, because, after a little bit trial and error, the li:before also needed the css rule display:inline-block.

So this is a fully working answer for me:

ul.dashes{
  list-style: none;
  padding-left: 2em;
  li{
    &:before{
      content: "-";
      text-indent: -2em;
      display: inline-block;
    }
  }
}

Conditional formatting based on another cell's value

I'm disappointed at how long it took to work this out.

I want to see which values in my range are outside standard deviation.

  1. Add the standard deviation calc to a cell somewhere =STDEV(L3:L32)*2
  2. Select the range to be highlighted, right click, conditional formatting
  3. Pick Format Cells if Greater than
  4. In the Value or Formula box type =$L$32 (whatever cell your stdev is in)

I couldn't work out how to put the STDEv inline. I tried many things with unexpected results.

How do I restrict an input to only accept numbers?

<input type="text" ng-model="employee.age" valid-input input-pattern="[^0-9]+" placeholder="Enter an age" />

<script>
var app = angular.module('app', []);

app.controller('dataCtrl', function($scope) {
});

app.directive('validInput', function() {
  return {
    require: '?ngModel',
    scope: {
      "inputPattern": '@'
    },
    link: function(scope, element, attrs, ngModelCtrl) {

      var regexp = null;

      if (scope.inputPattern !== undefined) {
        regexp = new RegExp(scope.inputPattern, "g");
      }

      if(!ngModelCtrl) {
        return;
      }

      ngModelCtrl.$parsers.push(function(val) {
        if (regexp) {
          var clean = val.replace(regexp, '');
          if (val !== clean) {
            ngModelCtrl.$setViewValue(clean);
            ngModelCtrl.$render();
          }
          return clean;
        }
        else {
          return val;
        }

      });

      element.bind('keypress', function(event) {
        if(event.keyCode === 32) {
          event.preventDefault();
        }
      });
    }
}}); </script>

How to set a dropdownlist item as selected in ASP.NET?

You can use the FindByValue method to search the DropDownList for an Item with a Value matching the parameter.

dropdownlist.ClearSelection();
dropdownlist.Items.FindByValue(value).Selected = true;

Alternatively you can use the FindByText method to search the DropDownList for an Item with Text matching the parameter.

Before using the FindByValue method, don't forget to reset the DropDownList so that no items are selected by using the ClearSelection() method. It clears out the list selection and sets the Selected property of all items to false. Otherwise you will get the following exception.

"Cannot have multiple items selected in a DropDownList"

Python urllib2, basic HTTP authentication, and tr.im

The recommended way is to use requests module:

#!/usr/bin/env python
import requests # $ python -m pip install requests
####from pip._vendor import requests # bundled with python

url = 'https://httpbin.org/hidden-basic-auth/user/passwd'
user, password = 'user', 'passwd'

r = requests.get(url, auth=(user, password)) # send auth unconditionally
r.raise_for_status() # raise an exception if the authentication fails

Here's a single source Python 2/3 compatible urllib2-based variant:

#!/usr/bin/env python
import base64
try:
    from urllib.request import Request, urlopen
except ImportError: # Python 2
    from urllib2 import Request, urlopen

credentials = '{user}:{password}'.format(**vars()).encode()
urlopen(Request(url, headers={'Authorization': # send auth unconditionally
    b'Basic ' + base64.b64encode(credentials)})).close()

Python 3.5+ introduces HTTPPasswordMgrWithPriorAuth() that allows:

..to eliminate unnecessary 401 response handling, or to unconditionally send credentials on the first request in order to communicate with servers that return a 404 response instead of a 401 if the Authorization header is not sent..

#!/usr/bin/env python3
import urllib.request as urllib2

password_manager = urllib2.HTTPPasswordMgrWithPriorAuth()
password_manager.add_password(None, url, user, password,
                              is_authenticated=True) # to handle 404 variant
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)

opener.open(url).close()

It is easy to replace HTTPBasicAuthHandler() with ProxyBasicAuthHandler() if necessary in this case.

How to embed a SWF file in an HTML page?

As mentioned SWF Object is great. UFO is worth a look as well

Rename a dictionary key

I am using @wim 's answer above, with dict.pop() when renaming keys, but I found a gotcha. Cycling through the dict to change the keys, without separating the list of old keys completely from the dict instance, resulted in cycling new, changed keys into the loop, and missing some existing keys.

To start with, I did it this way:

for current_key in my_dict:
    new_key = current_key.replace(':','_')
    fixed_metadata[new_key] = fixed_metadata.pop(current_key)

I found that cycling through the dict in this way, the dictionary kept finding keys even when it shouldn't, i.e., the new keys, the ones I had changed! I needed to separate the instances completely from each other to (a) avoid finding my own changed keys in the for loop, and (b) find some keys that were not being found within the loop for some reason.

I am doing this now:

current_keys = list(my_dict.keys())
for current_key in current_keys:
    and so on...

Converting the my_dict.keys() to a list was necessary to get free of the reference to the changing dict. Just using my_dict.keys() kept me tied to the original instance, with the strange side effects.

postgresql duplicate key violates unique constraint

From http://www.postgresql.org/docs/current/interactive/datatype.html

Note: Prior to PostgreSQL 7.3, serial implied UNIQUE. This is no longer automatic. If you wish a serial column to be in a unique constraint or a primary key, it must now be specified, same as with any other data type.

How can you sort an array without mutating the original array?

You can use slice with no arguments to copy an array:

var foo,
    bar;
foo = [3,1,2];
bar = foo.slice().sort();

ETag vs Header Expires

Another summary:

You need to use both. ETags are a "server side" information. Expires are a "Client side" caching.

  • Use ETags except if you have a load-balanced server. They are safe and will let clients know they should get new versions of your server files every time you change something on your side.

  • Expires must be used with caution, as if you set a expiration date far in the future but want to change one of the files immediatelly (a JS file for instance), some users may not get the modified version until a long time!

get all the elements of a particular form

let formFields     = form.querySelectorAll(`input:not([type='hidden']), select`)

ES6 version that has the advantage of ignoring the hidden fields if that is what you want

Throw away local commits in Git

For those interested in the Visual Studio solution, here is the drill:

  1. In the Team Explorer window, connect to the target repo.
  2. Then from Branches, right-click the branch of interest and select View history.
  3. Right-click a commit in the History window and choose Reset -> Delete changes (--hard).

That will throw away your local commits and reset the state of your repo to the selected commit. I.e. Your changes after you pulled the repo will be lost.

Design DFA accepting binary strings divisible by a number 'n'

You can build DFA using simple modular arithmetics. We can interpret w which is a string of k-ary numbers using a following rule

V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])

V[|w|] is a number that w is representing. If modify this rule to find w mod N, the rule becomes this.

V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N

and each V[i] is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.

See an example.

k = 2, N = 5

| V | (V*2 + 0) mod 5     | (V*2 + 1) mod 5     |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |

k = 3, N = 5

| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |

Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.

Getting list of tables, and fields in each, in a database

Your other inbuilt friend here is the system sproc SP_HELP.

sample usage ::

sp_help <MyTableName>

It returns a lot more info than you will really need, but at least 90% of your possible requirements will be catered for.

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

View.GONE makes the view invisible without the view taking up space in the layout. View.INVISIBLE makes the view just invisible still taking up space.

You are first using GONE and then INVISIBLE on the same view.Since, the code is executed sequentially, first the view becomes GONE then it is overridden by the INVISIBLE type still taking up space.

You should add button listener on the button and inside the onClick() method make the views visible. This should be the logic according to me in your onCreate() method.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setting);

    final DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
    final Button btn2 = (Button) findViewById(R.id.btnDate2);
    final Button btn3 = (Button) findViewById(R.id.btnVisibility);

    dp2.setVisibility(View.INVISIBLE);
    btn2.setVisibility(View.INVISIBLE);

    bt3.setOnClickListener(new View.OnCLickListener(){ 
    @Override
    public void onClick(View view)
    {
        dp2.setVisibility(View.VISIBLE);
        bt2.setVisibility(View.VISIBLE);
    }
  });
}

I think this should work easily. Hope this helps.

Is it possible to print a variable's type in standard C++?

You could use a traits class for this. Something like:

#include <iostream>
using namespace std;

template <typename T> class type_name {
public:
    static const char *name;
};

#define DECLARE_TYPE_NAME(x) template<> const char *type_name<x>::name = #x;
#define GET_TYPE_NAME(x) (type_name<typeof(x)>::name)

DECLARE_TYPE_NAME(int);

int main()
{
    int a = 12;
    cout << GET_TYPE_NAME(a) << endl;
}

The DECLARE_TYPE_NAME define exists to make your life easier in declaring this traits class for all the types you expect to need.

This might be more useful than the solutions involving typeid because you get to control the output. For example, using typeid for long long on my compiler gives "x".

How to run (not only install) an android application using .apk file?

I put this in my makefile, right the next line after adb install ...

adb shell monkey -p `cat .identifier` -c android.intent.category.LAUNCHER 1

For this to work there must be a .identifier file with the app's bundle identifier in it, like com.company.ourfirstapp

No need to hunt activity name.

Show an image preview before upload

_x000D_
_x000D_
function handleFileSelect(evt) {_x000D_
    var files = evt.target.files;_x000D_
_x000D_
    // Loop through the FileList and render image files as thumbnails._x000D_
    for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
      // Only process image files._x000D_
      if (!f.type.match('image.*')) {_x000D_
        continue;_x000D_
      }_x000D_
_x000D_
      var reader = new FileReader();_x000D_
_x000D_
      // Closure to capture the file information._x000D_
      reader.onload = (function(theFile) {_x000D_
        return function(e) {_x000D_
          // Render thumbnail._x000D_
          var span = document.createElement('span');_x000D_
          span.innerHTML = _x000D_
          [_x000D_
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
            e.target.result,_x000D_
            '" title="', escape(theFile.name), _x000D_
            '"/>'_x000D_
          ].join('');_x000D_
          _x000D_
          document.getElementById('list').insertBefore(span, null);_x000D_
        };_x000D_
      })(f);_x000D_
_x000D_
      // Read in the image file as a data URL._x000D_
      reader.readAsDataURL(f);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
_x000D_
_x000D_

Where is the documentation for the values() method of Enum?

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

Is there a way to get rid of accents and convert a whole string to regular letters?

System.out.println(Normalizer.normalize("àèé", Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""));

worked for me. The output of the snippet above gives "aee" which is what I wanted, but

System.out.println(Normalizer.normalize("àèé", Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", ""));

didn't do any substitution.

Android Split string

.split method will work, but it uses regular expressions. In this example it would be (to steal from Cristian):

String[] separated = CurrentString.split("\\:");
separated[0]; // this will contain "Fruit"
separated[1]; // this will contain " they taste good"

Also, this came from: Android split not working correctly

MySQL query to get column names?

I have tried this query in SQL Server and this worked for me :

SELECT name FROM sys.columns WHERE OBJECT_ID = OBJECT_ID('table_name')

(HTML) Download a PDF file instead of opening them in browser when clicked

When you want to direct download any image or pdf file from browser instead on opening it in new tab then in javascript you should set value to download attribute of create dynamic link

    var path= "your file path will be here"; 
    var save = document.createElement('a');  
    save.href = filePath; 
    save.download = "Your file name here"; 
    save.target = '_blank'; 
    var event = document.createEvent('Event');
    event.initEvent('click', true, true); 
    save.dispatchEvent(event);
   (window.URL || window.webkitURL).revokeObjectURL(save.href);

For new Chrome update some time event is not working. for that following code will be use

  var path= "your file path will be here"; 
    var save = document.createElement('a');  
    save.href = filePath; 
    save.download = "Your file name here"; 
    save.target = '_blank'; 
    document.body.appendChild(save);
    save.click();
    document.body.removeChild(save);

Appending child and removing child is useful for Firefox, Internet explorer browser only. On chrome it will work without appending and removing child

How do I get a string format of the current date time, in python?

>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%B %d, %Y")
'July 23, 2010'

What is the difference between Integer and int in Java?

int is a primitive type. Variables of type int store the actual binary value for the integer you want to represent. int.parseInt("1") doesn't make sense because int is not a class and therefore doesn't have any methods.

Integer is a class, no different from any other in the Java language. Variables of type Integer store references to Integer objects, just as with any other reference (object) type. Integer.parseInt("1") is a call to the static method parseInt from class Integer (note that this method actually returns an int and not an Integer).

To be more specific, Integer is a class with a single field of type int. This class is used where you need an int to be treated like any other object, such as in generic types or situations where you need nullability.

Note that every primitive type in Java has an equivalent wrapper class:

  • byte has Byte
  • short has Short
  • int has Integer
  • long has Long
  • boolean has Boolean
  • char has Character
  • float has Float
  • double has Double

Wrapper classes inherit from Object class, and primitive don't. So it can be used in collections with Object reference or with Generics.

Since java 5 we have autoboxing, and the conversion between primitive and wrapper class is done automatically. Beware, however, as this can introduce subtle bugs and performance problems; being explicit about conversions never hurts.

Visual Studio: Relative Assembly References Paths

Yes, just create a directory in your solution like lib/, and then add your dll to that directory in the filesystem and add it in the project (Add->Existing Item->etc). Then add the reference based on your project.

I have done this several times under svn and under cvs.

How to add a ScrollBar to a Stackpanel

It works like this:

<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" Width="340" HorizontalAlignment="Left" Margin="12,0,0,0">
        <StackPanel Name="stackPanel1" Width="311">

        </StackPanel>
</ScrollViewer>

TextBox tb = new TextBox();
tb.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
stackPanel1.Children.Add(tb);

plot is not defined

Change that import to

from matplotlib.pyplot import *

Note that this style of imports (from X import *) is generally discouraged. I would recommend using the following instead:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])

Insert value into a string at a certain position?

If you have a string and you know the index you want to put the two variables in the string you can use:

string temp = temp.Substring(0,index) + textbox1.Text + ":" + textbox2.Text +temp.Substring(index);

But if it is a simple line you can use it this way:

string temp = string.Format("your text goes here {0} rest of the text goes here : {1} , textBox1.Text , textBox2.Text ) ;"

Material UI and Grid system

From the description of material design specs:

Grid Lists are an alternative to standard list views. Grid lists are distinct from grids used for layouts and other visual presentations.

If you are looking for a much lightweight Grid component library, I'm using React-Flexbox-Grid, the implementation of flexboxgrid.css in React.

On top of that, React-Flexbox-Grid played nicely with both material-ui, and react-toolbox (the alternative material design implementation).

Initialize a string in C to empty string

To achieve this you can use:

strcpy(string, "");

Nesting await in Parallel.ForEach

This should be pretty efficient, and easier than getting the whole TPL Dataflow working:

var customers = await ids.SelectAsync(async i =>
{
    ICustomerRepo repo = new CustomerRepo();
    return await repo.GetCustomer(i);
});

...

public static async Task<IList<TResult>> SelectAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector, int maxDegreesOfParallelism = 4)
{
    var results = new List<TResult>();

    var activeTasks = new HashSet<Task<TResult>>();
    foreach (var item in source)
    {
        activeTasks.Add(selector(item));
        if (activeTasks.Count >= maxDegreesOfParallelism)
        {
            var completed = await Task.WhenAny(activeTasks);
            activeTasks.Remove(completed);
            results.Add(completed.Result);
        }
    }

    results.AddRange(await Task.WhenAll(activeTasks));
    return results;
}

Maven error "Failure to transfer..."

Remove all your failed downloads:

find ~/.m2  -name "*.lastUpdated" -exec grep -q "Could not transfer" {} \; -print -exec rm {} \;

For windows:

cd %userprofile%\.m2\repository
for /r %i in (*.lastUpdated) do del %i

Then rightclick on your project in eclipse and choose Maven->"Update Project ...", make sure "Update Dependencies" is checked in the resulting dialog and click OK.

JavaScript .replace only replaces first Match

You need a /g on there, like this:

_x000D_
_x000D_
var textTitle = "this is a test";_x000D_
var result = textTitle.replace(/ /g, '%20');_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

You can play with it here, the default .replace() behavior is to replace only the first match, the /g modifier (global) tells it to replace all occurrences.

Convert HH:MM:SS string to seconds only in javascript

Since the getTime function of the Date object gets the milliseconds since 1970/01/01, we can do this:

var time = '12:23:00';
var seconds = new Date('1970-01-01T' + time + 'Z').getTime() / 1000;

Could not find module "@angular-devkit/build-angular"

From the ionic forum this worked for me.

npm i @ionic/angular-toolkit@latest

How to normalize a 2-dimensional numpy array in python less verbose?

it appears that this also works

def normalizeRows(M):
    row_sums = M.sum(axis=1)
    return M / row_sums

What happens if you mount to a non-empty mount point with fuse?

Apparently nothing happens, it fails in a non-destructive way and gives you a warning.

I've had this happen as well very recently. One way you can solve this is by moving all the files in the non-empty mount point to somewhere else, e.g.:

mv /nonEmptyMountPoint/* ~/Desktop/mountPointDump/

This way your mount point is now empty, and your mount command will work.

How to update maven repository in Eclipse?

You can right-click on your project then Maven > Update Project..., then select Force Update of Snapshots/Releases checkbox then click OK.

Counting Number of Letters in a string variable

myString.Length; //will get you your result
//alternatively, if you only want the count of letters:
myString.Count(char.IsLetter);
//however, if you want to display the words as ***_***** (where _ is a space)
//you can also use this:
//small note: that will fail with a repeated word, so check your repeats!
myString.Split(' ').ToDictionary(n => n, n => n.Length);
//or if you just want the strings and get the counts later:
myString.Split(' ');
//will not fail with repeats
//and neither will this, which will also get you the counts:
myString.Split(' ').Select(n => new KeyValuePair<string, int>(n, n.Length));

How to add form validation pattern in Angular 2?

Now, you don't need to use FormBuilder and all this complicated valiation angular stuff. I put more details from this (Angular 2.0.8 - 3march2016): https://github.com/angular/angular/commit/38cb526

Example from repo :

<input [ngControl]="fullName" pattern="[a-zA-Z ]*">

I test it and it works :) - here is my code:

<form (ngSubmit)="onSubmit(room)" #roomForm='ngForm'  >
...
<input 
  id='room-capacity' 
  type="text" 
  class="form-control" 
  [(ngModel)]='room.capacity' 
  ngControl="capacity" 
  required
  pattern="[0-9]+" 
  #capacity='ngForm'>

Alternative approach (UPDATE June 2017)

Validation is ONLY on server side. If something is wrong then server return error code e.g HTTP 400 and following json object in response body (as example):

this.err = { 
    "capacity" : "too_small"
    "filed_name" : "error_name", 
    "field2_name" : "other_error_name",
    ... 
}

In html template I use separate tag (div/span/small etc.)

<input [(ngModel)]='room.capacity' ...>
<small *ngIf="err.capacity" ...>{{ translate(err.capacity) }}</small>

If in 'capacity' is error then tag with msg translation will be visible. This approach have following advantages:

  • it is very simple
  • avoid backend validation code duplication on frontend (for regexp validation this can either prevent or complicate ReDoS attacks)
  • control on way the error is shown (e.g. <small> tag)
  • backend return error_name which is easy to translate to proper language in frontend

Of course sometimes I make exception if validation is needed on frontend side (e.g. retypePassword field on registration is never send to server).

How to get image height and width using java?

I have found another way to read an image size (more generic). You can use ImageIO class in cooperation with ImageReaders. Here is the sample code:

private Dimension getImageDim(final String path) {
    Dimension result = null;
    String suffix = this.getFileSuffix(path);
    Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
    if (iter.hasNext()) {
        ImageReader reader = iter.next();
        try {
            ImageInputStream stream = new FileImageInputStream(new File(path));
            reader.setInput(stream);
            int width = reader.getWidth(reader.getMinIndex());
            int height = reader.getHeight(reader.getMinIndex());
            result = new Dimension(width, height);
        } catch (IOException e) {
            log(e.getMessage());
        } finally {
            reader.dispose();
        }
    } else {
        log("No reader found for given format: " + suffix));
    }
    return result;
}

Note that getFileSuffix is method that returns extension of path without "." so e.g.: png, jpg etc. Example implementation is:

private String getFileSuffix(final String path) {
    String result = null;
    if (path != null) {
        result = "";
        if (path.lastIndexOf('.') != -1) {
            result = path.substring(path.lastIndexOf('.'));
            if (result.startsWith(".")) {
                result = result.substring(1);
            }
        }
    }
    return result;
}

This solution is very quick as only image size is read from the file and not the whole image. I tested it and there is no comparison to ImageIO.read performance. I hope someone will find this useful.

Python coding standards/best practices

I follow the PEP8, it is a great piece of coding style.

Change input value onclick button - pure javascript or jQuery

And here is the non jQuery answer.

Fiddle: http://jsfiddle.net/J7m7m/7/

function changeText(value) {
     document.getElementById('count').value = 500 * value;   
}

HTML slight modification:

Product price: $500
<br>
Total price: $500
<br>
<input type="button" onclick="changeText(2)" value="2&#x00A;Qty">
<input type="button" class="mnozstvi_sleva" value="4&#x00A;Qty" onClick="changeText(4)">
<br>
Total <input type="text" id="count" value="1"/>

EDIT: It is very clear that this is a non-desired way as pointed out below (I had it coming). So in essence, this is how you would do it in plain old javascript. Most people would suggest you to use jQuery (other answer has the jQuery version) for good reason.

Most pythonic way to delete a file which may not exist

Matt's answer is the right one for older Pythons and Kevin's the right answer for newer ones.

If you wish not to copy the function for silentremove, this functionality is exposed in path.py as remove_p:

from path import Path
Path(filename).remove_p()

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

You can install the Microsoft Report Viewer 2012 Runtime and change your references so they point to the ones installed by the runtime.

http://www.microsoft.com/en-gb/download/details.aspx?id=35747

I have installed the runtime without it asking for SQL Server 2012. Before installing try uninstalling any previous versions of report viewer.

Computational complexity of Fibonacci Sequence

There's a very nice discussion of this specific problem over at MIT. On page 5, they make the point that, if you assume that an addition takes one computational unit, the time required to compute Fib(N) is very closely related to the result of Fib(N).

As a result, you can skip directly to the very close approximation of the Fibonacci series:

Fib(N) = (1/sqrt(5)) * 1.618^(N+1) (approximately)

and say, therefore, that the worst case performance of the naive algorithm is

O((1/sqrt(5)) * 1.618^(N+1)) = O(1.618^(N+1))

PS: There is a discussion of the closed form expression of the Nth Fibonacci number over at Wikipedia if you'd like more information.

How to deal with "data of class uneval" error from ggplot2?

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.

How to grep a string in a directory and all its subdirectories?

If your grep supports -R, do:

grep -R 'string' dir/

If not, then use find:

find dir/ -type f -exec grep -H 'string' {} +

Programmatically scroll a UIScrollView

Swift 3

let point = CGPoint(x: 0, y: 200) // 200 or any value you like.
scrollView.contentOffset = point

Apache default VirtualHost

The other answers here didn't work for me, but I found a pretty simple solution that did work.

I made the default one the last one listed, and I gave it ServerAlias *.

For example:

NameVirtualHost *:80

<VirtualHost *:80>
    ServerName www.secondwebsite.com
    ServerAlias secondwebsite.com *.secondwebsite.com
    DocumentRoot /home/secondwebsite/web
</VirtualHost>

<VirtualHost *:80>
    ServerName www.defaultwebsite.com
    ServerAlias *
    DocumentRoot /home/defaultwebsite/web
</VirtualHost>

If the visitor didn't explicitly choose to go to something ending in secondwebsite.com, they get the default website.

Pure CSS collapse/expand div

You just need to iterate the anchors in the two links.

<a href="#hide2" class="hide" id="hide2">+</a>
<a href="#show2" class="show" id="show2">-</a>

See this jsfiddle http://jsfiddle.net/eJX8z/

I also added some margin to the FAQ call to improve the format.

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

Convert a string representation of a hex dump to a byte array using Java?

One-liners:

import javax.xml.bind.DatatypeConverter;

public static String toHexString(byte[] array) {
    return DatatypeConverter.printHexBinary(array);
}

public static byte[] toByteArray(String s) {
    return DatatypeConverter.parseHexBinary(s);
}

For those of you interested in the actual code behind the One-liners from FractalizeR (I needed that since javax.xml.bind is not available for Android (by default)), this comes from com.sun.xml.internal.bind.DatatypeConverterImpl.java :

public byte[] parseHexBinary(String s) {
    final int len = s.length();

    // "111" is not a valid hex encoding.
    if( len%2 != 0 )
        throw new IllegalArgumentException("hexBinary needs to be even-length: "+s);

    byte[] out = new byte[len/2];

    for( int i=0; i<len; i+=2 ) {
        int h = hexToBin(s.charAt(i  ));
        int l = hexToBin(s.charAt(i+1));
        if( h==-1 || l==-1 )
            throw new IllegalArgumentException("contains illegal character for hexBinary: "+s);

        out[i/2] = (byte)(h*16+l);
    }

    return out;
}

private static int hexToBin( char ch ) {
    if( '0'<=ch && ch<='9' )    return ch-'0';
    if( 'A'<=ch && ch<='F' )    return ch-'A'+10;
    if( 'a'<=ch && ch<='f' )    return ch-'a'+10;
    return -1;
}

private static final char[] hexCode = "0123456789ABCDEF".toCharArray();

public String printHexBinary(byte[] data) {
    StringBuilder r = new StringBuilder(data.length*2);
    for ( byte b : data) {
        r.append(hexCode[(b >> 4) & 0xF]);
        r.append(hexCode[(b & 0xF)]);
    }
    return r.toString();
}

What is the official "preferred" way to install pip and virtualenv systemwide?

I use get-pip and virtualenv-burrito to install all this. Not sure if python-setuptools is required.

# might be optional. I install as part of my standard ubuntu setup script
sudo apt-get -y install python-setuptools

# install pip (using get-pip.py from pip contrib)
curl -O https://raw.github.com/pypa/pip/develop/contrib/get-pip.py && sudo python get-pip.py

# one-line virtualenv and virtualenvwrapper using virtualenv-burrito
curl -s https://raw.github.com/brainsik/virtualenv-burrito/master/virtualenv-burrito.sh | bash

Insert into ... values ( SELECT ... FROM ... )

Postgres supports next: create table company.monitor2 as select * from company.monitor;

NoClassDefFoundError for code in an Java library on Android

1)In Manifest file mention your activity name and action for it and also category . 2)In your Activity mention your starting contentview and mention your view id's in the activity.

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

Go to "app manager", then go to "all", then click on "Google Services Framework" and then "Clear Data". Reboot and it is done.

How can bcrypt have built-in salts?

I believe that phrase should have been worded as follows:

bcrypt has salts built into the generated hashes to prevent rainbow table attacks.

The bcrypt utility itself does not appear to maintain a list of salts. Rather, salts are generated randomly and appended to the output of the function so that they are remembered later on (according to the Java implementation of bcrypt). Put another way, the "hash" generated by bcrypt is not just the hash. Rather, it is the hash and the salt concatenated.

Ignore parent padding

If your after a way for the hr to go straight from the left side of a screen to the right this is the code to use to ensure the view width isn't effected.

hr {
position: absolute;
left: 0;
right: 0;
}

What is the "assert" function?

The assert computer statement is analogous to the statement make sure in English.

mappedBy reference an unknown target entity property

public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "USER_ID")
    Long userId;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> receiver;
}

public class Notification implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id

    @Column(name = "NOTIFICATION_ID")
    Long notificationId;

    @Column(name = "TEXT")
    String text;

    @Column(name = "ALERT_STATUS")
    @Enumerated(EnumType.STRING)
    AlertStatus alertStatus = AlertStatus.NEW;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SENDER_ID")
    @JsonIgnore
    User sender;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "RECEIVER_ID")
    @JsonIgnore
    User receiver;
}

What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..

User model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
    List<Notification> receiver;

Notification model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> **sender**;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> **receiver**;

I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.

How to prevent text in a table cell from wrapping

<th nowrap="nowrap">

or

<th style="white-space:nowrap;">

or

<th class="nowrap">
<style type="text/css">
.nowrap { white-space: nowrap; }
</style>

C# '@' before a String

It means to interpret the string literally (that is, you cannot escape any characters within the string if you use the @ prefix). It enhances readability in cases where it can be used.

For example, if you were working with a UNC path, this:

@"\\servername\share\folder"

is nicer than this:

"\\\\servername\\share\\folder"

A potentially dangerous Request.Path value was detected from the client (*)

If you're using .NET 4.0 you should be able to allow these urls via the web.config

<system.web>
    <httpRuntime 
            requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,:,\,?" />
</system.web>

Note, I've just removed the asterisk (*), the original default string is:

<httpRuntime 
          requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,:,\,?" />

See this question for more details.

Should black box or white box testing be the emphasis for testers?

Black Box

1 Focuses on the functionality of the system Focuses on the structure (Program) of the system

2 Techniques used are :

· Equivalence partitioning

· Boundary-value analysis

· Error guessing

· Race conditions

· Cause-effect graphing

· Syntax testing

· State transition testing

· Graph matrix

Tester can be non technical

Helps to identify the vagueness and contradiction in functional specifications

White Box

Techniques used are:

· Basis Path Testing

· Flow Graph Notation

· Control Structure Testing

  1. Condition Testing

  2. Data Flow testing

· Loop Testing

  1. Simple Loops

  2. Nested Loops

  3. Concatenated Loops

  4. Unstructured Loops

    Tester should be technical

    Helps to identify the logical and coding issues.

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

Python: Append item to list N times

For immutable data types:

l = [0] * 100
# [0, 0, 0, 0, 0, ...]

l = ['foo'] * 100
# ['foo', 'foo', 'foo', 'foo', ...]

For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):

l = [{} for x in range(100)]

(The reason why the first method is only a good idea for constant values, like ints or strings, is because only a shallow copy is does when using the <list>*<number> syntax, and thus if you did something like [{}]*100, you'd end up with 100 references to the same dictionary - so changing one of them would change them all. Since ints and strings are immutable, this isn't a problem for them.)

If you want to add to an existing list, you can use the extend() method of that list (in conjunction with the generation of a list of things to add via the above techniques):

a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]

Set type for function parameters?

No, instead you would need to do something like this depending on your needs:

function myFunction(myDate, myString) {
  if(arguments.length > 1 && typeof(Date.parse(myDate)) == "number" && typeof(myString) == "string") {
    //Code here
  }
}

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

With Java 8 there is this API method to accomplish your requirement.

map.putIfAbsent(key, value)

If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

On CYGwin, you can install this as a typical package in the first screen. Look for

libssl-devel

JavaScript query string

I like to keep it simple, readable and small.

function searchToObject(search) {
    var pairs = search.substring(1).split("&"),
        obj = {}, pair;

    for (var i in pairs) {
        if (pairs[i] === "") continue;
        pair = pairs[i].split("=");
        obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
    }
    return obj;
}

searchToObject(location.search);

Example:

searchToObject('?query=myvalue')['query']; // spits out: 'myvalue'

Remove or uninstall library previously added : cocoapods

The unwanted side effects of simple folder delete or installing over existing installation have been removed by a script written by Kyle Fuller - deintegrate and here is the proper workflow:

  1. Install clean:

    $ sudo gem install cocoapods-clean
    
  2. Run deintegrate in the folder of the project:

    $ pod deintegrate
    
  3. Clean (this tool is no longer available):

    $ pod clean
    
  4. Modify your podfile (delete the lines with the pods you don't want to use anymore) and run:

    $ pod install
    

Done.